Debian Codegraph @

net/sf/saxon/tree/util/FastStringBuffer.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.tree.util;
9
10 import net.sf.saxon.regex.BMPString;
11 import net.sf.saxon.regex.GeneralUnicodeString;
12 import net.sf.saxon.regex.UnicodeString;
13 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
14 import net.sf.saxon.tree.tiny.AppendableCharSequence;
15 import net.sf.saxon.tree.tiny.CharSlice;
16 import net.sf.saxon.tree.tiny.CompressedWhitespace;
17
18 import java.io.Writer;
19 import java.util.Arrays;
20
21 /**
22 * A simple implementation of a class similar to StringBuffer. Unlike
23 * StringBuffer it is not synchronized. It also offers the capability
24 * to remove unused space. (This class could possibly be replaced by
25 * StringBuilder in JDK 1.5, but using our own class gives more control.)
26 */
27
28 public final class FastStringBuffer implements AppendableCharSequence {
29
30 public static final int C16 = 16;
31 public static final int C64 = 64;
32 public static final int C256 = 256;
33 public static final int C1024 = 1024;
34
35 private char[] array;
36 private int used = 0;
37
38 /**
39 * Create a FastStringBuffer with a given initial capacity
40 *
41 * @param initialSize the initial capacity
42 */
43
44 public FastStringBuffer(int initialSize) {
45 //System.err.println("FSB " + initialSize);
46 array = new char[initialSize];
47 }
48
49 /**
50 * Create a FastStringBuffer with initial content
51 *
52 * @param cs the initial content. The buffer is created with just enough capacity for
53 * this content (it will be expanded if more content is added later).
54 */
55
56 public FastStringBuffer(CharSequence cs) {
57 array = new char[cs.length()];
58 append(cs);
59 }
60
61 /**
62 * Append the contents of a String to the buffer
63 *
64 * @param s the String to be appended
65 */
66
67 public void append(String s) {
68 int len = s.length();
69 ensureCapacity(len);
70 s.getChars(0, len, array, used);
71 used += len;
72 }
73
74 /**
75 * Append the contents of a CharSlice to the buffer
76 *
77 * @param s the String to be appended
78 */
79
80 public void append(CharSlice s) {
81 int len = s.length();
82 ensureCapacity(len);
83 s.copyTo(array, used);
84 used += len;
85 }
86
87 /**
88 * Append the contents of a FastStringBuffer to the buffer
89 *
90 * @param s the FastStringBuffer to be appended
91 */
92
93 public void append(FastStringBuffer s) {
94 int len = s.length();
95 ensureCapacity(len);
96 s.getChars(0, len, array, used);
97 used += len;
98 }
99
100 /**
101 * Append the contents of a StringBuffer to the buffer
102 *
103 * @param s the StringBuffer to be appended
104 */
105
106 public void append(StringBuffer s) {
107 int len = s.length();
108 ensureCapacity(len);
109 s.getChars(0, len, array, used);
110 used += len;
111 }
112
113 /**
114 * Append the contents of a general CharSequence to the buffer
115 *
116 * @param s the CharSequence to be appended
117 */
118
119 public void append(CharSequence s) {
120 // Although we provide variants of this method for different subtypes, Java decides which to use based
121 // on the static type of the operand. We want to use the right method based on the dynamic type, to avoid
122 // creating objects and copying strings unnecessarily. So we do a dynamic dispatch.
123 final int len = s.length();
124 ensureCapacity(len);
125 if (s instanceof CharSlice) {
126 ((CharSlice) s).copyTo(array, used);
127 } else if (s instanceof String) {
128 ((String) s).getChars(0, len, array, used);
129 } else if (s instanceof FastStringBuffer) {
130 ((FastStringBuffer) s).getChars(0, len, array, used);
131 } else if (s instanceof CompressedWhitespace) {
132 ((CompressedWhitespace) s).uncompress(this);
133 return;
134 } else if (s instanceof BMPString) {
135 append(((BMPString) s).getCharSequence());
136 return;
137 } else if (s instanceof GeneralUnicodeString) {
138 for (int i = 0; i < ((GeneralUnicodeString)s).uLength(); i++) {
139 appendWideChar(((GeneralUnicodeString)s).uCharAt(i));
140 }
141 return;
142 } else {
143 s.toString().getChars(0, len, array, used);
144 }
145 used += len;
146 }
147
148 /**
149 * Append the contents of a character array to the buffer
150 *
151 * @param srcArray the array whose contents are to be added
152 * @param start the offset of the first character in the array to be copied
153 * @param length the number of characters to be copied
154 */
155
156 public void append(char[] srcArray, int start, int length) {
157 ensureCapacity(length);
158 System.arraycopy(srcArray, start, array, used, length);
159 used += length;
160 }
161
162 /**
163 * Append the entire contents of a character array to the buffer
164 *
165 * @param srcArray the array whose contents are to be added
166 */
167
168 public void append(char[] srcArray) {
169 final int length = srcArray.length;
170 ensureCapacity(length);
171 System.arraycopy(srcArray, 0, array, used, length);
172 used += length;
173 }
174
175 /**
176 * Append a character to the buffer
177 *
178 * @param ch the character to be added
179 */
180
181 public void append(char ch) {
182 ensureCapacity(1);
183 array[used++] = ch;
184 }
185
186 /**
187 * Append a wide character to the buffer (as a surrogate pair if necessary)
188 *
189 * @param ch the character, as a 32-bit Unicode codepoint
190 */
191
192 public void appendWideChar(int ch) {
193 if (ch > 0xffff) {
194 append(UTF16CharacterSet.highSurrogate(ch));
195 append(UTF16CharacterSet.lowSurrogate(ch));
196 } else {
197 append((char) ch);
198 }
199 }
200
201 /**
202 * Append a UnicodeString to the buffer (using surrogate pairs if necessary)
203 *
204 * @param str the UnicodeString
205 */
206
207 public void append(UnicodeString str) {
208 if (str instanceof BMPString) {
209 append(((BMPString) str).getCharSequence());
210 } else {
211 for (int i = 0; i < str.uLength(); i++) {
212 appendWideChar(str.uCharAt(i));
213 }
214 }
215 }
216
217 /**
218 * Prepend a wide character to the buffer (as a surrogate pair if necessary)
219 *
220 * @param ch the character, as a 32-bit Unicode codepoint
221 */
222
223 public void prependWideChar(int ch) {
224 if (ch > 0xffff) {
225 prepend(UTF16CharacterSet.lowSurrogate(ch));
226 prepend(UTF16CharacterSet.highSurrogate(ch));
227 } else {
228 prepend((char) ch);
229 }
230 }
231
232 /**
233 * Returns the length of this character sequence. The length is the number
234 * of 16-bit <code>char</code>s in the sequence.
235 *
236 * @return the number of <code>char</code>s in this sequence
237 */
238 public int length() {
239 return used;
240 }
241
242 /**
243 * Ask whether the string buffer is empty
244 * @return true if the buffer is empty (length()==0)
245 */
246
247 public boolean isEmpty() {
248 return used==0;
249 }
250
251 /**
252 * Returns the <code>char</code> value at the specified index. An index ranges from zero
253 * to <tt>length() - 1</tt>. The first <code>char</code> value of the sequence is at
254 * index zero, the next at index one, and so on, as for array
255 * indexing.
256 * <p>If the <code>char</code> value specified by the index is a
257 * <a href="Character.html#unicode">surrogate</a>, the surrogate
258 * value is returned.</p>
259 *
260 * @param index the index of the <code>char</code> value to be returned
261 * @return the specified <code>char</code> value
262 * @throws IndexOutOfBoundsException if the <tt>index</tt> argument is negative or not less than
263 * <tt>length()</tt>
264 */
265 public char charAt(int index) {
266 if (index >= used) {
267 throw new IndexOutOfBoundsException("" + index);
268 }
269 return array[index];
270 }
271
272 /**
273 * Returns a new <code>CharSequence</code> that is a subsequence of this sequence.
274 * The subsequence starts with the <code>char</code> value at the specified index and
275 * ends with the <code>char</code> value at index <tt>end - 1</tt>. The length
276 * (in <code>char</code>s) of the
277 * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>
278 * then an empty sequence is returned.
279 *
280 * @param start the start index, inclusive
281 * @param end the end index, exclusive
282 * @return the specified subsequence
283 * @throws IndexOutOfBoundsException if <tt>start</tt> or <tt>end</tt> are negative,
284 * if <tt>end</tt> is greater than <tt>length()</tt>,
285 * or if <tt>start</tt> is greater than <tt>end</tt>
286 */
287 public CharSequence subSequence(int start, int end) {
288 return new CharSlice(array, start, end - start);
289 }
290
291 /**
292 * Copies characters from this FastStringBuffer into the destination character
293 * array.
294 * <p>The first character to be copied is at index <code>srcBegin</code>;
295 * the last character to be copied is at index <code>srcEnd-1</code>
296 * (thus the total number of characters to be copied is
297 * <code>srcEnd-srcBegin</code>). The characters are copied into the
298 * subarray of <code>dst</code> starting at index <code>dstBegin</code>
299 * and ending at index:</p>
300 * <blockquote><pre>
301 * dstbegin + (srcEnd-srcBegin) - 1
302 * </pre></blockquote>
303 *
304 * @param srcBegin index of the first character in the string
305 * to copy.
306 * @param srcEnd index after the last character in the string
307 * to copy.
308 * @param dst the destination array.
309 * @param dstBegin the start offset in the destination array.
310 * @throws IndexOutOfBoundsException If any of the following
311 * is true:
312 * <ul><li><code>srcBegin</code> is negative.
313 * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
314 * <li><code>srcEnd</code> is greater than the length of this
315 * string
316 * <li><code>dstBegin</code> is negative
317 * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
318 * <code>dst.length</code></ul>
319 */
320 public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
321 if (srcBegin < 0) {
322 throw new StringIndexOutOfBoundsException(srcBegin);
323 }
324 if (srcEnd > used) {
325 throw new StringIndexOutOfBoundsException(srcEnd);
326 }
327 if (srcBegin > srcEnd) {
328 throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
329 }
330 System.arraycopy(array, srcBegin, dst, dstBegin, srcEnd - srcBegin);
331 }
332
333 /**
334 * Get the index of the first character equal to a given value
335 *
336 * @param ch the character to search for
337 * @return the position of the first occurrence, or -1 if not found
338 */
339
340 public int indexOf(char ch) {
341 for (int i = 0; i < used; i++) {
342 if (array[i] == ch) {
343 return i;
344 }
345 }
346 return -1;
347 }
348
349 /**
350 * Convert contents of the FastStringBuffer to a string
351 */
352
353 public String toString() {
354 condense(); // has side-effects which is nasty on the debugger!
355 return new String(array, 0, used);
356 }
357
358 /**
359 * Compare equality
360 */
361
362 public boolean equals(Object other) {
363 return other instanceof CharSequence && toString().equals(other.toString());
364 }
365
366 /**
367 * Generate a hash code
368 */
369
370 public int hashCode() {
371 // Same algorithm as String#hashCode(), but not cached
372 int h = 0;
373 for (int i = 0; i < used; i++) {
374 h = 31 * h + array[i];
375 }
376 return h;
377 }
378
379
380 /**
381 * Get a char[] array containing the characters. The caller should not modify the
382 * array.
383 *
384 * @return a char[] array containing the characters.
385 */
386
387 public char[] toCharArray() {
388 if (used == array.length) {
389 return array;
390 } else {
391 char[] chars = new char[used];
392 System.arraycopy(array, 0, chars, 0, used);
393 return chars;
394 }
395 }
396
397 /**
398 * Set the character at a particular offset
399 *
400 * @param index the index of the character to be set
401 * @param ch the new character to overwrite the existing character at that location
402 * @throws IndexOutOfBoundsException if int&lt;0 or int&gt;=length()
403 */
404
405 public void setCharAt(int index, char ch) {
406 if (index < 0 || index > used) {
407 throw new IndexOutOfBoundsException("" + index);
408 }
409 array[index] = ch;
410 }
411
412 /**
413 * Insert a character at a particular offset
414 *
415 * @param index the index of the character to be set
416 * @param ch the new character to insert at that location
417 * @throws IndexOutOfBoundsException if int&lt;0 or int&gt;=length()
418 */
419
420 public void insert(int index, char ch) {
421 if (index < 0 || index > used) {
422 throw new IndexOutOfBoundsException("" + index);
423 }
424 ensureCapacity(1);
425 System.arraycopy(array, index, array, index + 1, used - index);
426 used++;
427 array[index] = ch;
428 }
429
430 /**
431 * Insert wide character at a particular offset
432 *
433 * @param index the index of the character to be set
434 * @param ch the character, as a 32-bit Unicode codepoint
435 * @throws IndexOutOfBoundsException if int&lt;0 or int&gt;=length()
436 */
437
438 public void insertWideChar(int index, int ch) {
439 if (index < 0 || index > used) {
440 throw new IndexOutOfBoundsException("" + index);
441 }
442 if (ch > 0xffff) {
443 ensureCapacity(2);
444 System.arraycopy(array, index, array, index + 2, used - index);
445 used += 2;
446 array[index] = UTF16CharacterSet.highSurrogate(ch);
447 array[index + 1] = UTF16CharacterSet.lowSurrogate(ch);
448 } else {
449 ensureCapacity(1);
450 System.arraycopy(array, index, array, index + 1, used - index);
451 used++;
452 array[index] = (char) ch;
453 }
454 }
455
456
457 /**
458 * Remove a character at a particular offset
459 *
460 * @param index the index of the character to be set
461 * @throws IndexOutOfBoundsException if int&lt;0 or int&gt;=length()
462 */
463
464 public void removeCharAt(int index) {
465 if (index < 0 || index > used) {
466 throw new IndexOutOfBoundsException("" + index);
467 }
468 used--;
469 System.arraycopy(array, index + 1, array, index, used - index);
470 }
471
472 /**
473 * Insert a given character at the start of the buffer
474 *
475 * @param ch the character to insert
476 */
477
478 public void prepend(char ch) {
479 char[] a2 = new char[array.length + 1];
480 System.arraycopy(array, 0, a2, 1, used);
481 a2[0] = ch;
482 used += 1;
483 array = a2;
484 }
485
486 /**
487 * Insert a given string at the start of the buffer
488 *
489 * @param str the string to insert
490 */
491
492 public void prepend(CharSequence str) {
493 int len = str.length();
494 char[] a2 = new char[array.length + len];
495 System.arraycopy(array, 0, a2, len, used);
496 for (int i = 0; i < len; i++) {
497 a2[i] = str.charAt(i);
498 }
499 used += len;
500 array = a2;
501 }
502
503 /**
504 * Insert a given character N times at the start of the buffer
505 *
506 * @param ch the character to insert
507 * @param repeat the number of occurrences required. Supplying 0 or a negative number is OK,
508 * and is treated as a no-op.
509 */
510
511 public void prependRepeated(char ch, int repeat) {
512 if (repeat > 0) {
513 char[] a2 = new char[array.length + repeat];
514 System.arraycopy(array, 0, a2, repeat, used);
515 Arrays.fill(a2, 0, repeat, ch);
516 used += repeat;
517 array = a2;
518 }
519 }
520
521 /**
522 * Set the length. If this exceeds the current length, this method is a no-op.
523 * If this is less than the current length, characters beyond the specified point
524 * are deleted.
525 *
526 * @param length the new length
527 */
528
529 public void setLength(int length) {
530 if (length < 0 || length > used) {
531 return;
532 }
533 used = length;
534 }
535
536 /**
537 * Expand the character array if necessary to ensure capacity for appended data
538 *
539 * @param extra the amount of additional capacity needed, in characters
540 */
541
542 public void ensureCapacity(int extra) {
543 if (used + extra > array.length) {
544 int newlen = array.length * 2;
545 if (newlen < used + extra) {
546 newlen = used + extra * 2;
547 }
548 array = Arrays.copyOf(array, newlen);
549 }
550 }
551
552 /**
553 * Remove surplus space from the array. This doesn't reduce the array to the minimum
554 * possible size; it only reclaims space if it seems worth doing. Specifically, it
555 * contracts the array if the amount of wasted space is more than 256 characters, or
556 * more than half the allocated size and more than 20 chars.
557 *
558 * @return the buffer after removing unused space
559 */
560
561 public FastStringBuffer condense() {
562 if (array.length - used > 256 || (array.length > used * 2 && array.length - used > 20)) {
563 array = Arrays.copyOf(array, used);
564 }
565 return this;
566 }
567
568 /**
569 * Write the value to a writer
570 *
571 * @param writer the writer to which the content is to be written
572 */
573
574 public void write(Writer writer) throws java.io.IOException {
575 writer.write(array, 0, used);
576 }
577
578 /**
579 * Diagnostic print of the contents of a CharSequence. Ordinary printable ASCII characters
580 * are displayed as themselves; anything else is displayed as a \\uNNNN escape sequence
581 *
582 * @param in the CharSequence whose contents are to be displayed.
583 * @return the diagnostic output
584 */
585
586 public static String diagnosticPrint(/*@NotNull*/ CharSequence in) {
587 FastStringBuffer buff = new FastStringBuffer(in.length() * 2);
588 for (int i = 0; i < in.length(); i++) {
589 char c = in.charAt(i);
590 if (c > 32 && c < 127) {
591 buff.append(c);
592 } else {
593 buff.append("\\u");
594 for (int d = 12; d >= 0; d -= 4) {
595 buff.append("0123456789ABCDEF".charAt((c >> d) & 0xf));
596 }
597 }
598 }
599 return buff.toString();
600 }
601
602 }
603