aboutsummaryrefslogtreecommitdiffstats
path: root/document/src/main/java/com/yahoo/document/datatypes/Array.java
blob: f1d1255916c23c37faa8dc640180c30857d617f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.datatypes;

import com.yahoo.collections.CollectionComparator;
import com.yahoo.document.ArrayDataType;
import com.yahoo.document.DataType;
import com.yahoo.document.Field;
import com.yahoo.document.FieldPath;
import com.yahoo.document.serialization.FieldReader;
import com.yahoo.document.serialization.FieldWriter;
import com.yahoo.document.serialization.XmlSerializationHelper;
import com.yahoo.document.serialization.XmlStream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.RandomAccess;

/**
 * FieldValue which encapsulates an Array value
 *
 * @author Einar M R Rosenvinge
 */
public final class Array<T extends FieldValue> extends CollectionFieldValue<T> implements List<T> {

    private List<T> values;

    public Array(DataType type) {
        this(type, 1);
    }

    public Array(DataType type, int initialCapacity) {
        super((ArrayDataType) type);
        this.values = new ArrayList<>(initialCapacity);
    }

    public Array(DataType type, List<T> values) {
        this(type);
        for (T v : values) {
            if (!((ArrayDataType)type).getNestedType().isValueCompatible(v)) {
                throw new IllegalArgumentException("FieldValue " + v + " is not compatible with " + type + ".");
            }
        }
        this.values.addAll(values);
    }

    @Override
    public ArrayDataType getDataType() {
        return (ArrayDataType) super.getDataType();
    }

    @Override
    public Iterator<T> fieldValueIterator() {
        return values.iterator();
    }

    @Override
    public Array<T> clone() {
        Array<T> array = (Array<T>) super.clone();
        array.values = new ArrayList<>(values.size());
        for (T fval : values) {
            array.values.add((T) fval.clone());
        }
        return array;
    }

    @Override
    public void clear() {
        values.clear();
    }

    @Override
    public void assign(Object o) {
        if (!checkAssign(o)) {
            return;
        }

        if (o instanceof Array) {
            if (o == this) return;
            Array a = (Array) o;
            values.clear();
            addAll(a.values);
        } else if (o instanceof List) {
            values = new ListWrapper<T>((List) o);
        } else {
            throw new IllegalArgumentException("Class " + o.getClass() + " not applicable to an " + this.getClass() + " instance.");
        }
    }

    @Override
    public Object getWrappedValue() {
        if (values instanceof ListWrapper) {
            return ((ListWrapper) values).myvalues;
        }
        List tmpWrappedList = new ArrayList();
        for (T value : values) {
            tmpWrappedList.add(value.getWrappedValue());
        }
        return tmpWrappedList;
    }

    public List<T> getValues() {
        return values;
    }

    public FieldValue getFieldValue(int index) {
        return values.get(index);
    }

    @Override
    @Deprecated
    public void printXml(XmlStream xml) {
        XmlSerializationHelper.printArrayXml(this, xml);
    }

    @Override
    public String toString() {
        return values.toString();
    }

    @Override
    public int hashCode() {
        int hashCode = super.hashCode();
        for (FieldValue val : values) {
            hashCode ^= val.hashCode();
        }
        return hashCode;
    }

    private boolean equalsWithListWrapper(List<? extends FieldValue> a, ListWrapper<? extends FieldValue> b) {
        for (int i = 0; i < a.size(); i++) {
            if ( ! b.myvalues.get(i).equals(a.get(i).getWrappedValue()) ) return false;
        }
        return true;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Array a)) return false;
        if (!super.equals(o)) return false;
        if (values.size() != a.values.size()) return false;
        if (values instanceof ListWrapper && !(a.values instanceof ListWrapper)) {
            return equalsWithListWrapper(a.values, (ListWrapper<? extends FieldValue>) values);
        } else if (a.values instanceof ListWrapper && !(values instanceof ListWrapper)) {
            return equalsWithListWrapper(values, (ListWrapper<? extends FieldValue>) a.values);
        }
        return values.equals(a.values);
    }

    // List implementation

    public void add(int index, T o) {
        verifyElementCompatibility(o);
        values.add(index, o);
    }

    public boolean remove(Object o) {
        return values.remove(o);
    }

    public boolean add(T o) {
        verifyElementCompatibility(o);
        return values.add(o);
    }

    @Override
    public boolean contains(Object o) {
        return values.contains(o);
    }

    @Override
    public boolean isEmpty() {
        return super.isEmpty(values);
    }

    @Override
    public Iterator<T> iterator() {
        return values.iterator();
    }

    @Override
    public boolean removeValue(FieldValue o) {
        return super.removeValue(o, values);
    }

    @Override
    public int size() {
        return values.size();
    }

    public boolean addAll(Collection<? extends T> c) {
        for (T t : c) {
            verifyElementCompatibility(t);
        }
        return values.addAll(c);
    }

    public boolean containsAll(Collection<?> c) {
        return values.containsAll(c);
    }

    public Object[] toArray() {
        return values.toArray();
    }

    @SuppressWarnings({"unchecked"})
    public <T> T[] toArray(T[] a) {
        return values.toArray(a);
    }

    public boolean addAll(int index, Collection<? extends T> c) {
        for (T t : c) {
            verifyElementCompatibility(t);
        }
        return values.addAll(index, c);
    }

    public boolean retainAll(Collection<?> c) {
        return values.retainAll(c);
    }

    public boolean removeAll(Collection<?> c) {
        return values.removeAll(c);
    }

    public T get(int index) {
        return values.get(index);
    }

    public int indexOf(Object o) {
        return values.indexOf(o);
    }

    public int lastIndexOf(Object o) {
        return values.lastIndexOf(o);
    }

    public ListIterator<T> listIterator() {
        return values.listIterator();
    }

    public ListIterator<T> listIterator(final int index) {
        return values.listIterator(index);
    }

    public T remove(int index) {
        return values.remove(index);
    }

    public T set(int index, T o) {
        verifyElementCompatibility(o);
        T fval = values.set(index, o);
        return fval;
    }

    public List<T> subList(int fromIndex, int toIndex) {
        return values.subList(fromIndex, toIndex);
    }

    FieldPathIteratorHandler.ModificationStatus iterateSubset(int startPos, int endPos, FieldPath fieldPath, String variable, int nextPos, FieldPathIteratorHandler handler) {
        FieldPathIteratorHandler.ModificationStatus retVal = FieldPathIteratorHandler.ModificationStatus.NOT_MODIFIED;

        LinkedList<Integer> indicesToRemove = new LinkedList<Integer>();

        for (int i = startPos; i <= endPos && i < values.size(); i++) {
            if (variable != null) {
                handler.getVariables().put(variable, new FieldPathIteratorHandler.IndexValue(i));
            }

            FieldValue fv = values.get(i);
            FieldPathIteratorHandler.ModificationStatus status = fv.iterateNested(fieldPath, nextPos, handler);

            if (status == FieldPathIteratorHandler.ModificationStatus.REMOVED) {
                indicesToRemove.addFirst(i);
                retVal = FieldPathIteratorHandler.ModificationStatus.MODIFIED;
            } else if (status == FieldPathIteratorHandler.ModificationStatus.MODIFIED) {
                retVal = status;
            }
        }

        if (variable != null) {
            handler.getVariables().remove(variable);
        }

        for (Integer idx : indicesToRemove) {
            values.remove(idx.intValue());
        }
        return retVal;
    }

    @Override
    FieldPathIteratorHandler.ModificationStatus iterateNested(FieldPath fieldPath, int pos, FieldPathIteratorHandler handler) {
        if (pos < fieldPath.size()) {
            switch (fieldPath.get(pos).getType()) {
                case ARRAY_INDEX:
                    final int elemIndex = fieldPath.get(pos).getLookupIndex();
                    return iterateSubset(elemIndex, elemIndex, fieldPath, null, pos + 1, handler);
                case VARIABLE: {
                    FieldPathIteratorHandler.IndexValue val = handler.getVariables().get(fieldPath.get(pos).getVariableName());
                    if (val != null) {
                        int idx = val.getIndex();

                        if (idx == -1) {
                            throw new IllegalArgumentException("Mismatch between variables - trying to iterate through map and array with the same variable.");
                        }

                        if (idx < values.size()) {
                            return iterateSubset(idx, idx, fieldPath, null, pos + 1, handler);
                        } else {
                            return FieldPathIteratorHandler.ModificationStatus.NOT_MODIFIED;
                        }
                    } else {
                        return iterateSubset(0, values.size() - 1, fieldPath, fieldPath.get(pos).getVariableName(), pos + 1, handler);
                    }
                }
                default:
            }
            return iterateSubset(0, values.size() - 1, fieldPath, null, pos, handler);
        } else {
            FieldPathIteratorHandler.ModificationStatus status = handler.modify(this);

            if (status == FieldPathIteratorHandler.ModificationStatus.REMOVED) {
                return status;
            }

            if (handler.onComplex(this)) {
                if (iterateSubset(0, values.size() - 1, fieldPath, null, pos, handler) != FieldPathIteratorHandler.ModificationStatus.NOT_MODIFIED) {
                    status = FieldPathIteratorHandler.ModificationStatus.MODIFIED;
                }
            }

            return status;
        }
    }

    /**
     * This wrapper class is used to wrap a list that isn't a list of field
     * values. This is done, as to not alter behaviour from previous state,
     * where people could add whatever list to a document, and then keep adding
     * stuff to the list afterwards.
     *
     * <p>
     * TODO: Remove this class and only allow instance of Array to be added.
     */
    class ListWrapper<E> implements List<E>, RandomAccess {
        private final List myvalues;

        private Object unwrap(Object o) {
            return (o instanceof FieldValue ? ((FieldValue) o).getWrappedValue() : o);
        }

        public ListWrapper(List wrapped) {
            myvalues = wrapped;
        }

        public int size() {
            return myvalues.size();
        }

        public boolean isEmpty() {
            return myvalues.isEmpty();
        }

        public boolean contains(Object o) {
            return myvalues.contains(unwrap(o));
        }

        public Iterator<E> iterator() {
            return listIterator();
        }

        public Object[] toArray() {
            return toArray(new Object[myvalues.size()]);
        }

        // It's supposed to blow up if given invalid types
        @SuppressWarnings({ "hiding", "unchecked" })
        public <T> T[] toArray(T[] a) {
            final Class<?> componentType = a.getClass().getComponentType();
            T[] out = (T[]) java.lang.reflect.Array.newInstance(componentType, myvalues.size());

            Arrays.setAll(out, (i) -> (T) createFieldValue(myvalues.get(i)));
            return out;
        }

        public boolean add(E o) {
            return myvalues.add(unwrap(o));
        }

        public boolean remove(Object o) {
            return myvalues.remove(unwrap(o));
        }

        public boolean containsAll(Collection<?> c) {
            for (Object o : c) {
                if (!myvalues.contains(unwrap(o))) return false;
            }
            return true;
        }

        public boolean addAll(Collection<? extends E> c) {
            boolean result = false;
            for (Object o : c) {
                result |= myvalues.add(unwrap(o));
            }
            return result;
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            for (Object o : c) {
                myvalues.add(index++, unwrap(o));
            }
            return true;
        }

        public boolean removeAll(Collection<?> c) {
            boolean result = false;
            for (Object o : c) {
                result |= myvalues.remove(unwrap(o));
            }
            return result;
        }

        public boolean retainAll(Collection<?> c) {
            throw new UnsupportedOperationException("retainAll() not implemented for this type");
        }

        public void clear() {
            myvalues.clear();
        }

        public E get(int index) {
            Object o = myvalues.get(index);
            return (E) (o == null ? null : createFieldValue(o));
        }

        public E set(int index, E element) {
            Object o = myvalues.set(index, unwrap(element));
            return (E) (o == null ? null : createFieldValue(o));
        }

        public void add(int index, E element) {
            myvalues.add(index, unwrap(element));
        }

        public E remove(int index) {
            Object o = myvalues.remove(index);
            return (E) (o == null ? null : createFieldValue(o));
        }

        public int indexOf(Object o) {
            return myvalues.indexOf(unwrap(o));
        }

        public int lastIndexOf(Object o) {
            return myvalues.lastIndexOf(unwrap(o));
        }

        public ListIterator<E> listIterator() {
            return listIterator(0);
        }

        public ListIterator<E> listIterator(final int index) {
            return new ListIterator<E>() {
                ListIterator it = myvalues.listIterator(index);

                public boolean hasNext() {
                    return it.hasNext();
                }

                public E next() {
                    return (E) createFieldValue(it.next());
                }

                public boolean hasPrevious() {
                    return it.hasPrevious();
                }

                public E previous() {
                    return (E) createFieldValue(it.previous());
                }

                public int nextIndex() {
                    return it.nextIndex();
                }

                public int previousIndex() {
                    return it.previousIndex();
                }

                public void remove() {
                    it.remove();
                }

                public void set(E o) {
                    it.set(unwrap(o));
                }

                public void add(E o) {
                    it.add(unwrap(o));
                }
            };
        }

        public List<E> subList(int fromIndex, int toIndex) {
            return new ListWrapper<E>(myvalues.subList(fromIndex, toIndex));
        }

        public String toString() {
            return myvalues.toString();
        }

        @Override
        @SuppressWarnings("deprecation, unchecked")
        public boolean equals(Object o) {
            return this == o || o instanceof ListWrapper && myvalues.equals(((ListWrapper) o).myvalues);
        }

        @Override
        public int hashCode() {
            return myvalues.hashCode();
        }
    }

    @Override
    public void serialize(Field field, FieldWriter writer) {
        writer.write(field, this);
    }

    @Override
    public void deserialize(Field field, FieldReader reader) {
        reader.read(field, this);
    }

    @Override
    public int compareTo(FieldValue fieldValue) {
        int comp = super.compareTo(fieldValue);

        if (comp != 0) {
            return comp;
        }

        //types are equal, this must be of this type
        Array otherValue = (Array) fieldValue;
        return CollectionComparator.compare(values, otherValue.values);
    }
}