Debian Codegraph @

src/com/google/javascript/jscomp/regex/CharRanges.java

raw symbols SCIP
1 /*
2 * Copyright 2011 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp.regex;
18
19 import java.util.Arrays;
20
21 /**
22 * An immutable sparse bitset that deals well where the data is chunky:
23 * where P(bit[x+1] == bit[x]). E.g. [101,102,103,104,105,1001,1002,1003,1004]
24 * is chunky.
25 *
26 * @author [email protected] (Mike Samuel)
27 */
28 final class CharRanges {
29 /**
30 * A strictly increasing set of bit indices where even members are the
31 * inclusive starts of ranges, and odd members are the exclusive ends.
32 * <p>
33 * E.g., { 1, 5, 6, 10 } represents the set ( 1, 2, 3, 4, 6, 7, 8, 9 ).
34 */
35 private final int[] ranges;
36
37 public static final CharRanges EMPTY = new CharRanges(new int[0]);
38
39 public static final CharRanges ALL_CODE_UNITS
40 = new CharRanges(new int[] { 0, 0x10000 });
41
42 public static CharRanges inclusive(int start, int end) {
43 if (start > end) {
44 throw new IndexOutOfBoundsException(start + " > " + end);
45 }
46 return new CharRanges(new int[] { start, end + 1 });
47 }
48
49 /**
50 * Returns an instance containing all and only the given members.
51 */
52 public static CharRanges withMembers(int... members) {
53 return new CharRanges(intArrayToRanges(members.clone()));
54 }
55
56 /**
57 * Returns an instance containing the given ranges.
58 * @param ranges An even-length ordered sequence of non-overlapping,
59 * non-contiguous, [inclusive start, exclusive end) ranges.
60 */
61 public static CharRanges withRanges(int... ranges) {
62 ranges = ranges.clone();
63 if ((ranges.length & 1) != 0) { throw new IllegalArgumentException(); }
64 for (int i = 1; i < ranges.length; ++i) {
65 if (ranges[i] <= ranges[i - 1]) {
66 throw new IllegalArgumentException(ranges[i] + " > " + ranges[i - 1]);
67 }
68 }
69 return new CharRanges(ranges);
70 }
71
72 private CharRanges(int[] ranges) {
73 this.ranges = ranges;
74 }
75
76 private static int[] intArrayToRanges(int[] members) {
77 int nMembers = members.length;
78 if (nMembers == 0) {
79 return new int[0];
80 }
81
82 Arrays.sort(members);
83
84 // Count the number of runs.
85 int nRuns = 1;
86 for (int i = 1; i < nMembers; ++i) {
87 int current = members[i], last = members[i - 1];
88 if (current == last) { continue; }
89 if (current != last + 1) { ++nRuns; }
90 }
91
92 int[] ranges = new int[nRuns * 2];
93 ranges[0] = members[0];
94 int k = 0;
95 for (int i = 1; k + 2 < ranges.length; ++i) {
96 int current = members[i], last = members[i - 1];
97 if (current == last) { continue; }
98 if (current != last + 1) {
99 ranges[++k] = last + 1; // add 1 to make end exclusive
100 ranges[++k] = current;
101 }
102 }
103 ranges[++k] = members[nMembers - 1] + 1; // add 1 to make end exclusive
104 return ranges;
105 }
106
107 public boolean contains(int bit) {
108 return (Arrays.binarySearch(ranges, bit) & 1) == 0;
109 // By the contract of Arrays.binarySearch, its result is either the position
110 // of bit in ranges or it is the bitwise inverse of the position of the
111 // least element greater than bit.
112
113 // Two cases
114 // case (idx >= 0)
115 // We ended up exactly on a range boundary.
116 // Starts are inclusive and ends are both exclusive, so this contains
117 // bit iff idx is even.
118 //
119 // case (idx < 0)
120 // If the least element greater than bit is an odd element,
121 // then bit must be greater than a start and less than an end, so
122 // contained.
123 //
124 // If bit is greater than all elements, then idx will be past the end of
125 // the array, and will be even since ranges.length is even.
126 //
127 // Otherwise, bit must be in the space between two runs, so not
128 // contained.
129 //
130 // In all cases, oddness is equivalent to containedness.
131
132 // Those two cases lead to
133 // idx >= 0 ? ((idx & 1) == 0) : ((~idx & 1) == 1)
134
135 // But ~n & bit == bit <=> n & bit == 0, so
136 // idx >= 0 ? ((idx & 1) == 0) : ((~idx & 1) == 1)
137 // => idx >= 0 ? ((idx & 1) == 0) : ((idx & 1) == 0)
138 // => (idx & 1) == 0
139 }
140
141 public int minSetBit() {
142 return ranges.length >= 0 ? ranges[0] : Integer.MIN_VALUE;
143 }
144
145 public boolean isEmpty() {
146 return ranges.length == 0;
147 }
148
149 public int getNumRanges() { return ranges.length >> 1; }
150
151 public int start(int i) { return ranges[i << 1]; }
152
153 public int end(int i) { return ranges[(i << 1) | 1]; }
154
155 public CharRanges union(CharRanges other) {
156 // Index of the input ranges
157 int[] q = this.ranges, r = other.ranges;
158 // Lengths of the inputs
159 int m = q.length, n = r.length;
160
161 if (m == 0) { return other; }
162 if (n == 0) { return this; }
163
164 // The output array. The length is m+n in the worst case when all the
165 // ranges in a are disjoint from the ranges in b.
166 int[] out = new int[m + n];
167
168 // Indexes into the various arrays
169 int i = 0, j = 0, k = 0;
170 // Since there are three arrays, and indices into them the following
171 // should never occur in this function:
172 // (1) q[j] or q[k] -- q is indexed by i
173 // (2) r[i] or r[k] -- r is indexed by j
174 // (3) out[i] or out[j] -- out is indexed by k
175 // (4) i < n or j < m -- index compared to wrong limit
176
177 // This loop exits because we always increment at least one of i,j.
178 while (i < m && j < n) {
179 // Range starts and ends.
180 int a0 = q[i], a1 = q[i + 1],
181 b0 = r[j], b1 = r[j + 1];
182 if (a1 < b0) { // [a0, a1) ends before [b0, b1) starts
183 out[k++] = a0;
184 out[k++] = a1;
185 i += 2;
186 } else if (b1 < a0) { // [b0, b1) ends before [a0, a1) starts
187 out[k++] = b0;
188 out[k++] = b1;
189 j += 2;
190 } else { // ranges overlap
191 // We need to compute a new range based on the set of ranges that
192 // transitively overlap.
193 // AAAAAAAAA AAA
194 // BBB BBB* BBB
195 // In the range above, the start comes from one set, and the end from
196 // another. The range with the asterisk next to it is subsumed entirely
197 // by a range from the other, and so not all ranges on the input
198 // contribute a value to the output.
199 // The last BBB run serves only as a bridge -- it overlaps two
200 // disjoint ranges in the other one so establishes that they
201 // transitively overlap.
202 int start = Math.min(a0, b0);
203 // Guess at the end, and lookahead to come up with a more complete
204 // estimate.
205 int end = Math.max(a1, b1);
206 i += 2;
207 j += 2;
208 while (i < m || j < n) {
209 if (i < m && q[i] <= end) {
210 end = Math.max(end, q[i + 1]);
211 i += 2;
212 } else if (j < n && r[j] <= end) {
213 end = Math.max(end, r[j + 1]);
214 j += 2;
215 } else {
216 break;
217 }
218 }
219 out[k++] = start;
220 out[k++] = end;
221 }
222 }
223 // There may be unprocessed ranges at the end of one of the inputs.
224 if (i < m) {
225 System.arraycopy(q, i, out, k, m - i);
226 k += m - i;
227 } else if (j < n) {
228 System.arraycopy(r, j, out, k, n - j);
229 k += n - j;
230 }
231 // We guessed at the output length above. Cut off the tail.
232 if (k != out.length) {
233 int[] clipped = new int[k];
234 System.arraycopy(out, 0, clipped, 0, k);
235 out = clipped;
236 }
237 return new CharRanges(out);
238 }
239
240 public CharRanges intersection(CharRanges other) {
241 int[] aRanges = ranges, bRanges = other.ranges;
242 int aLen = aRanges.length, bLen = bRanges.length;
243 if (aLen == 0) { return this; }
244 if (bLen == 0) { return other; }
245 int aIdx = 0, bIdx = 0;
246 int[] intersection = new int[Math.min(aLen, bLen)];
247 int intersectionIdx = 0;
248 int pos = Math.min(aRanges[0], bRanges[0]);
249 while (aIdx < aLen && bIdx < bLen) {
250 if (aRanges[aIdx + 1] <= pos) {
251 aIdx += 2;
252 } else if (bRanges[bIdx + 1] <= pos) {
253 bIdx += 2;
254 } else {
255 int start = Math.max(aRanges[aIdx], bRanges[bIdx]);
256 if (pos < start) { // Advance to start of common block.
257 pos = start;
258 } else {
259 // Now we know that pos is less than the ends of the two ranges and
260 // greater or equal to the starts of the two ranges.
261 int end = Math.min(aRanges[aIdx + 1], bRanges[bIdx + 1]);
262 if (intersectionIdx != 0
263 && pos == intersection[intersectionIdx - 1]) {
264 intersection[intersectionIdx - 1] = end;
265 } else {
266 if (intersectionIdx == intersection.length) {
267 int[] newArr = new int[intersectionIdx * 2];
268 System.arraycopy(intersection, 0, newArr, 0, intersectionIdx);
269 intersection = newArr;
270 }
271 intersection[intersectionIdx++] = pos;
272 intersection[intersectionIdx++] = end;
273 }
274 pos = end;
275 }
276 }
277 }
278 if (intersectionIdx != intersection.length) {
279 int[] newArr = new int[intersectionIdx];
280 System.arraycopy(intersection, 0, newArr, 0, intersectionIdx);
281 intersection = newArr;
282 }
283 return new CharRanges(intersection);
284 }
285
286 public CharRanges difference(CharRanges subtrahendRanges) {
287 // difference = minuend - subtrahend
288 int[] minuend = this.ranges;
289 int[] subtrahend = subtrahendRanges.ranges;
290
291 int mn = minuend.length, sn = subtrahend.length;
292 if (mn == 0 || sn == 0) { return this; }
293
294 int[] difference = new int[minuend.length];
295
296 // Indices into minuend.ranges, subtrahend.ranges, and difference.
297 int mIdx = 0, sIdx = 0, dIdx = 0;
298
299 int pos = minuend[0];
300 while (mIdx < mn) {
301 if (pos >= minuend[mIdx + 1]) {
302 mIdx += 2;
303 } else if (pos < minuend[mIdx]) {
304 // Skip gaps in the minuend.
305 pos = minuend[mIdx];
306 } else if (sIdx < sn && pos >= subtrahend[sIdx]) {
307 // Skip over a removed part.
308 pos = subtrahend[sIdx + 1];
309 sIdx += 2;
310 } else {
311 // Now we know that pos is between [minuend[i], minuend[i + 1])
312 // and outside [subtrahend[j], subtrahend[j + 1]).
313 int end = sIdx < sn
314 ? Math.min(minuend[mIdx + 1], subtrahend[sIdx]) : minuend[mIdx + 1];
315 if (dIdx != 0 && difference[dIdx - 1] == pos) {
316 difference[dIdx - 1] = pos;
317 } else {
318 if (dIdx == difference.length) {
319 int[] newArr = new int[dIdx * 2];
320 System.arraycopy(difference, 0, newArr, 0, dIdx);
321 difference = newArr;
322 }
323 difference[dIdx++] = pos;
324 difference[dIdx++] = end;
325 }
326 pos = end;
327 }
328 }
329
330 if (dIdx != difference.length) {
331 int[] newArr = new int[dIdx];
332 System.arraycopy(difference, 0, newArr, 0, dIdx);
333 difference = newArr;
334 }
335
336 return new CharRanges(difference);
337 }
338
339 public boolean containsAll(CharRanges sub) {
340 int[] superRanges = this.ranges;
341 int[] subRanges = sub.ranges;
342
343 int superIdx = 0, subIdx = 0;
344 int superLen = superRanges.length, subLen = subRanges.length;
345 while (subIdx < subLen) {
346 if (superIdx == superLen) {
347 return false;
348 }
349 if (superRanges[superIdx + 1] <= subRanges[subIdx]) {
350 // Super range ends before subRange starts.
351 superIdx += 2;
352 } else if (superRanges[superIdx] > subRanges[subIdx]) {
353 // Uncontained portion at start of sub range.
354 return false;
355 } else if (superRanges[superIdx + 1] >= subRanges[subIdx + 1]) {
356 // A sub range is completely contained in the super range.
357 // We know this because of the above condition and we have already
358 // ruled out that subRanges[subIdx] < superRanges[superIdx].
359 subIdx += 2;
360 } else {
361 // Uncontained portion at end of sub range.
362 return false;
363 }
364 }
365 return subIdx == subLen;
366 }
367
368 /**
369 * Shifts the bits matched by the given delta.
370 * So if this has the bits (a, b, c, ..., z) set then the result has the bits
371 * ((a - delta), (b - delta), (c - delta), ...., (z - delta)) set.
372 *
373 * @throws IndexOutOfBoundsException if shifting by delta would cause an
374 * overflow or underflow in a 32 bit {@code signed int} range boundary.
375 * Since the end boundaries of ranges are exclusive, even if there is no
376 * range containing {@link Integer#MAX_VALUE}, shifting by a delta of 1
377 * can cause an overflow.
378 */
379 public CharRanges shift(int delta) {
380 int n = ranges.length;
381 if (delta == 0 || n == 0) { return this; }
382 // Test overflow/underflow
383 if (delta < 0) {
384 long lmin = ranges[0] + delta;
385 if (lmin < Integer.MIN_VALUE) { throw new IndexOutOfBoundsException(); }
386 } else {
387 long lmax = ranges[n - 1] + delta;
388 if (lmax > Integer.MAX_VALUE) { throw new IndexOutOfBoundsException(); }
389 }
390 // Create a shifted range.
391 int[] shiftedRanges = new int[n];
392 for (int i = n; --i >= 0;) {
393 shiftedRanges[i] = ranges[i] + delta;
394 }
395 return new CharRanges(shiftedRanges);
396 }
397
398 @Override
399 public String toString() {
400 StringBuilder sb = new StringBuilder();
401 sb.append('[');
402 for (int i = 0; i < ranges.length; ++i) {
403 if ((i & 1) != 0 && ranges[i] == ranges[i - 1] + 1) { continue; }
404 if (i != 0) { sb.append((i & 1) == 0 ? ' ' : '-'); }
405 sb.append("0x").append(Integer.toString(ranges[i] - (i & 1), 16));
406 }
407 sb.append(']');
408 return sb.toString();
409 }
410
411 @Override
412 public boolean equals(Object o) {
413 if (!(o instanceof CharRanges)) { return false; }
414 return Arrays.equals(this.ranges, ((CharRanges) o).ranges);
415 }
416
417 @Override
418 public int hashCode() {
419 int hc = 0;
420 for (int i = 0, n = Math.min(16, ranges.length); i < n; ++i) {
421 hc = (hc << 2) + ranges[i];
422 }
423 return hc;
424 }
425 }