summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/util/indexing/containers/ChangeBufferingList.java
blob: a1373c06a23f452b2a7719f0d4d06221891a57c2 (plain)
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
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.util.indexing.containers;

import com.intellij.util.indexing.DebugAssertions;
import com.intellij.util.indexing.ValueContainer;
import gnu.trove.TIntProcedure;

import static com.intellij.util.indexing.DebugAssertions.DEBUG;

/**
 * Class buffers changes in 2 modes:
 * - Accumulating up to MAX_FILES changes appending them *sequentially* to changes array
 * - Adding changes to randomAccessContainer once it is available: later happens if we accumulated many changes or external client queried
 * state of the changes: asked for predicate, iterator, isEmpty, etc. We are trying hard to delay transformation of state upon 2nd reason for
 * performance reasons.
 * It is assumed that add / remove operations as well as read only operations are externally synchronized, the only synchronization is
 * performed upon transforming changes array into randomAccessContainer because it can be done during read only operations in several threads
 */
public class ChangeBufferingList implements Cloneable {
  static final int MAX_FILES = 20000; // less than Short.MAX_VALUE
  //static final int MAX_FILES = 100;
  private volatile int[] changes;
  private short length;
  private boolean hasRemovals;
  private volatile boolean mayHaveDupes;
  private volatile RandomAccessIntContainer randomAccessContainer;

  private IdSet checkSet;

  public ChangeBufferingList() { this(3); }
  public ChangeBufferingList(int length) {
    if (length > MAX_FILES) {
      randomAccessContainer = new IdBitSet(length);
    } else {
      changes = new int[length];
    }
    checkSet = DEBUG ? new IdSet(length) : null;
  }

  static int[] calcMinMax(int[] set, int length) {
    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    for(int i = 0; i < length; ++i) {
      max = Math.max(max, set[i]);
      min = Math.min(min, set[i]);
    }
    return new int[] {min, max};
  }

  public void add(int value) {
    ensureCapacity(1);
    if (DEBUG) checkSet.add(value);
    RandomAccessIntContainer intContainer = randomAccessContainer;
    if (intContainer == null) {
      addChange(value);
    } else {
      intContainer.add(value);
    }
  }

  private void addChange(int value) {
    changes[length++] = value;
    if (value < 0 && !hasRemovals) hasRemovals = true;
    if(!mayHaveDupes) mayHaveDupes = true;
  }

  public void remove(int value) {
    if (DEBUG) checkSet.remove(value);
    RandomAccessIntContainer intContainer = randomAccessContainer;
    if (intContainer == null) {
      ensureCapacity(1);
      addChange(-value);
    }
    else {
      boolean removed = intContainer.remove(value);
      if (removed) intContainer.compact();
    }
  }

  @Override
  public Object clone() {
    try {
      ChangeBufferingList clone = (ChangeBufferingList)super.clone();
      if (changes != null) clone.changes = changes.clone();
      if (randomAccessContainer != null) {
        clone.randomAccessContainer = (RandomAccessIntContainer)randomAccessContainer.clone();
      }
      if (checkSet != null) clone.checkSet = (IdSet)checkSet.clone();
      return clone;
    }
    catch (CloneNotSupportedException e) {
      throw new RuntimeException(e);
    }
  }

  private RandomAccessIntContainer getRandomAccessContainer() {
    int[] currentChanges = changes;
    if (currentChanges == null) return randomAccessContainer;

    synchronized (currentChanges) {
      currentChanges = changes;
      if (currentChanges == null) return randomAccessContainer;
      boolean copyChanges = true;
      RandomAccessIntContainer idSet;

      if (randomAccessContainer == null) {
        int someElementsNumberEstimation = length;
        int[] minMax = calcMinMax(changes, length);

        // todo we can check these lengths instead of only relying upon reaching MAX_FILES
        //int lengthOfBitSet = IdBitSet.sizeInBytes(minMax[1], minMax[0]);
        //int lengthOfIntSet = 4 * length;

        if (someElementsNumberEstimation < MAX_FILES) {
          if (!hasRemovals) {
            if (mayHaveDupes) {
              mergeChangesRemovingDupes();
            }
            idSet = new SortedIdSet(currentChanges, length);

            copyChanges = false;
          } else {
            idSet = new SortedIdSet(Math.max(someElementsNumberEstimation, 3));
          }
        }
        else if (!hasRemovals) {
          idSet = new IdBitSet(changes, length, 0);
          copyChanges = false;
        } else {
          idSet = new IdBitSet(minMax, 0);
        }
      } else if (DEBUG) {
        idSet = (RandomAccessIntContainer)randomAccessContainer.clone();
      } else {
        idSet = randomAccessContainer;
      }

      assert idSet != null;

      if (copyChanges) {
        for(int i = 0, len = length; i < len; ++i) {
          int id = currentChanges[i];
          if (id > 0) {
            idSet.add(id);
          } else {
            idSet.remove(-id);
          }
        }
      }

      if (DEBUG) {
        DebugAssertions.assertTrue(checkSet.size() == idSet.size());
        final RandomAccessIntContainer finalIdSet = idSet;
        checkSet.forEach(new TIntProcedure() {
          @Override
          public boolean execute(int value) {
            DebugAssertions.assertTrue(finalIdSet.contains(value));
            return true;
          }
        });
      }

      length = 0;
      hasRemovals = false;
      mayHaveDupes = false;
      randomAccessContainer = idSet;
      changes = null;
      return randomAccessContainer;
    }
  }

  private void mergeChangesRemovingDupes() { // duplicated ids can be present for some index due to cancellation of indexing for next index
    int[] currentChanges = changes;
    ValueContainer.IntIterator sorted = SortedFileIdSetIterator.getTransientIterator(new ChangesIterator(currentChanges, length));
    int lastIndex = 0;
    while(sorted.hasNext()) {
      currentChanges[lastIndex++] = sorted.next();
    }

    length = (short)lastIndex;
    mayHaveDupes = false;
  }

  public void ensureCapacity(int diff) {
    RandomAccessIntContainer intContainer = randomAccessContainer;
    if (length == MAX_FILES) {
      intContainer = getRandomAccessContainer(); // transform into more compact storage
    }
    if (intContainer != null) {
      randomAccessContainer = intContainer.ensureContainerCapacity(diff);
      return;
    }
    if (changes == null) {
      changes = new int[Math.max(3, diff)];
    } else if (length + diff > changes.length) {
      int[] newChanges = new int[calcNextArraySize(changes.length, length + diff)];
      System.arraycopy(changes, 0, newChanges, 0, length);
      changes = newChanges;
    }
  }

  static int calcNextArraySize(int currentSize, int wantedSize) {
    return Math.min(
      Math.max(currentSize < 1024 ? currentSize << 1 : currentSize + currentSize / 5, wantedSize),
      MAX_FILES
    );
  }

  public boolean isEmpty() {
    if (randomAccessContainer == null) {
      if (changes == null) {
        if (DEBUG) DebugAssertions.assertTrue(checkSet.isEmpty());
        return true;
      }
      if (!hasRemovals) {
        boolean b = length == 0;
        if (DEBUG) DebugAssertions.assertTrue(b == checkSet.isEmpty());
        return b;
      }
    }
    // todo we can calculate isEmpty in more cases (without container)
    RandomAccessIntContainer intContainer = getRandomAccessContainer();
    return intContainer.size() == 0;
  }

  public ValueContainer.IntPredicate intPredicate() {
    final ValueContainer.IntPredicate predicate = getRandomAccessContainer().intPredicate();
    if (DEBUG) {
      return new ValueContainer.IntPredicate() {
        @Override
        public boolean contains(int id) {
          boolean answer = predicate.contains(id);
          DebugAssertions.assertTrue(answer == checkSet.contains(id));
          return answer;
        }
      };
    }
    return predicate;
  }

  public ValueContainer.IntIterator intIterator() {
    RandomAccessIntContainer intContainer = randomAccessContainer;
    if (intContainer == null && !hasRemovals) {
      int[] currentChanges = changes;
      if (currentChanges != null) {
        if (mayHaveDupes) {
          synchronized (currentChanges) {
            if (mayHaveDupes) mergeChangesRemovingDupes();
          }
        }
        return new ChangesIterator(currentChanges, length);
      }
    }
    return getRandomAccessContainer().intIterator();
  }

  public ValueContainer.IntIterator rawIntIterator() {
    RandomAccessIntContainer intContainer = randomAccessContainer;
    if (intContainer == null && !hasRemovals) {
      return new ChangesIterator(changes, length); // dupes are possible
    }
    return getRandomAccessContainer().intIterator();
  }

  public IdSet getCheckSet() {
    return checkSet;
  }

  private static class ChangesIterator implements ValueContainer.IntIterator {
    private int cursor;
    private final int length;
    private final int[] changes;

    ChangesIterator(int[] _changes, int _length) {
      changes = _changes;
      length = _length;
    }

    @Override
    public boolean hasNext() {
      return cursor < length;
    }

    @Override
    public int next() {
      int current = cursor;
      ++cursor;
      return changes[current];
    }

    @Override
    public int size() {
      return length;
    }

    @Override
    public boolean hasAscendingOrder() {
      return false;
    }

    @Override
    public ValueContainer.IntIterator createCopyInInitialState() {
      return new ChangesIterator(changes, length);
    }
  }
}