Debian Codegraph @

net/sf/saxon/tree/tiny/LargeStringBuffer.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.tiny;
9
10 import net.sf.saxon.tree.util.FastStringBuffer;
11
12 import java.util.Arrays;
13
14
15 /**
16 * This is an implementation of the CharSequence interface: it implements
17 * a CharSequence as a list of arrays of characters (the individual arrays are known
18 * as segments). The segments have a fixed size of 65536 characters.
19 * <p>This is more efficient than a buffer backed by a contiguous array of characters
20 * in cases where the size is likely to grow very large, and where substring operations
21 * are rare. As used within the TinyTree, extraction of the string value of a node
22 * requires character copying only in the case where the value crosses segment
23 * boundaries.</p>
24 */
25
26 public final class LargeStringBuffer implements AppendableCharSequence {
27
28 private final static int BITS = 16;
29 private final static int SEGLEN = 1 << BITS;
30 private final static int MASK = SEGLEN - 1;
31
32 // Variant of LargeStringBuffer using fixed-length segments
33
34 private char[][] data;
35 private int length; // total length of the CharSequence
36 private int segmentsUsed;
37
38 /**
39 * Create an empty LargeStringBuffer with default space allocation
40 */
41
42 public LargeStringBuffer() {
43 data = new char[1][];
44 segmentsUsed = 0;
45 length = 0;
46 }
47
48 /**
49 * Expand the data structure. Note this only involves expanding the "index" (the list of
50 * segments), it does not cause any character data to be copied.
51 *
52 * @param seg the new segment to be added.
53 */
54
55 private void addSegment(char[] seg) {
56 int segs = data.length;
57 if (segmentsUsed + 1 > segs) {
58 if (segmentsUsed == 32768) {
59 throw new IllegalStateException("Source document too large: more than 1G characters in text nodes");
60 }
61 data = Arrays.copyOf(data, segs * 2);
62 }
63 data[segmentsUsed++] = seg;
64 }
65
66 /**
67 * Append a CharSequence to this LargeStringBuffer
68 *
69 * @param s the data to be appended
70 */
71
72 public void append(CharSequence s) {
73 // Although we provide variants of this method for different subtypes, Java decides which to use based
74 // on the static type of the operand. We want to use the right method based on the dynamic type, to avoid
75 // creating objects and copying strings unnecessarily. So we do a dynamic dispatch. (This is only necessary
76 // of course because the CharSequence class offers no getChars() method).
77
78 if (s instanceof CompressedWhitespace) {
79 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
80 ((CompressedWhitespace)s).uncompress(fsb);
81 append(fsb);
82 return;
83 }
84
85 final int len = s.length();
86 char[] firstSeg;
87 int firstSegOffset = length & MASK;
88 if (firstSegOffset == 0) {
89 firstSeg = new char[SEGLEN];
90 addSegment(firstSeg);
91 } else {
92 firstSeg = data[length>>BITS];
93 }
94 int firstSegLen;
95 int fullSegments;
96 int lastSegLen;
97 if (len <= SEGLEN - firstSegOffset) {
98 // all fits in the current segment
99 firstSegLen = len;
100 fullSegments = 0;
101 lastSegLen = 0;
102 } else {
103 firstSegLen = SEGLEN - firstSegOffset;
104 fullSegments = (len - firstSegLen) >> BITS;
105 lastSegLen = (len - firstSegLen) & MASK;
106 }
107
108 if (s instanceof CharSlice) {
109 ((CharSlice)s).getChars(0, firstSegLen, firstSeg, firstSegOffset);
110 int start = firstSegLen;
111 for (int i=0; i<fullSegments; i++) {
112 char[] seg = new char[SEGLEN];
113 addSegment(seg);
114 ((CharSlice)s).getChars(start, start+SEGLEN, seg, 0);
115 start += SEGLEN;
116 }
117 if (lastSegLen > 0) {
118 char[] seg = new char[SEGLEN];
119 addSegment(seg);
120 ((CharSlice)s).getChars(start, len, seg, 0);
121 }
122 length += len;
123
124 } else if (s instanceof FastStringBuffer) {
125 ((FastStringBuffer)s).getChars(0, firstSegLen, firstSeg, firstSegOffset);
126 int start = firstSegLen;
127 for (int i=0; i<fullSegments; i++) {
128 char[] seg = new char[SEGLEN];
129 addSegment(seg);
130 ((FastStringBuffer)s).getChars(start, start+SEGLEN, seg, 0);
131 start += SEGLEN;
132 }
133 if (lastSegLen > 0) {
134 char[] seg = new char[SEGLEN];
135 addSegment(seg);
136 ((FastStringBuffer)s).getChars(start, len, seg, 0);
137 }
138 length += len;
139
140 } else {
141 if (!(s instanceof String)) {
142 s = s.toString();
143 }
144
145 ((String)s).getChars(0, firstSegLen, firstSeg, firstSegOffset);
146 int start = firstSegLen;
147 for (int i=0; i<fullSegments; i++) {
148 char[] seg = new char[SEGLEN];
149 addSegment(seg);
150 ((String)s).getChars(start, start+SEGLEN, seg, 0);
151 start += SEGLEN;
152 }
153 if (lastSegLen > 0) {
154 char[] seg = new char[SEGLEN];
155 addSegment(seg);
156 ((String)s).getChars(start, len, seg, 0);
157 }
158 length += len;
159
160 }
161 }
162
163 /**
164 * Returns the length of this character sequence. The length is the number
165 * of 16-bit UTF-16 characters in the sequence.
166 *
167 * @return the number of characters in this sequence
168 */
169 public int length() {
170 return length;
171 }
172
173 /**
174 * Set the length. If this exceeds the current length, this method is a no-op.
175 * If this is less than the current length, characters beyond the specified point
176 * are deleted.
177 *
178 * @param length the new length
179 */
180
181 public void setLength(int length) {
182 if (length < this.length) {
183 int usedInLastSegment = length & MASK;
184 this.length = length;
185 this.segmentsUsed = length / SEGLEN + (usedInLastSegment == 0 ? 0 : 1);
186 }
187 }
188
189 /**
190 * Returns the character at the specified index. An index ranges from zero
191 * to <tt>length() - 1</tt>. The first character of the sequence is at
192 * index zero, the next at index one, and so on, as for array
193 * indexing.
194 *
195 * @param index the index of the character to be returned
196 * @return the specified character
197 * @throws IndexOutOfBoundsException if the <tt>index</tt> argument is negative or not less than
198 * <tt>length()</tt>
199 */
200 public char charAt(int index) {
201 if (index < 0 || index >= length) {
202 throw new IndexOutOfBoundsException(index + "");
203 }
204 return data[index >> BITS][index & MASK];
205 }
206
207 /**
208 * Returns a new character sequence that is a subsequence of this sequence.
209 * The subsequence starts with the character at the specified index and
210 * ends with the character at index <tt>end - 1</tt>. The length of the
211 * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>
212 * then an empty sequence is returned.
213 *
214 * @param start the start index, inclusive
215 * @param end the end index, exclusive
216 * @return the specified subsequence
217 * @throws IndexOutOfBoundsException if <tt>start</tt> or <tt>end</tt> are negative,
218 * if <tt>end</tt> is greater than <tt>length()</tt>,
219 * or if <tt>start</tt> is greater than <tt>end</tt>
220 */
221 /*@NotNull*/
222 public CharSequence subSequence(int start, int end) {
223 int firstSeg = start >> BITS;
224 int lastSeg = (end - 1) >> BITS;
225 if (firstSeg == lastSeg) {
226 try {
227 return new CharSlice(data[firstSeg], start & MASK, end - start);
228 } catch (ArrayIndexOutOfBoundsException e) {
229 e.printStackTrace();
230 throw e;
231 }
232 } else {
233 FastStringBuffer fsb = new FastStringBuffer(end - start);
234 int firstSegLen = SEGLEN - (start & MASK);
235 fsb.append(data[firstSeg], start & MASK, firstSegLen);
236 int doneTo = start + firstSegLen;
237 while (true) {
238 firstSeg++;
239 if (doneTo + SEGLEN < end) {
240 fsb.append(data[firstSeg]);
241 doneTo += SEGLEN;
242 } else {
243 fsb.append(data[firstSeg], 0, end - doneTo);
244 break;
245 }
246 }
247 return fsb;
248 }
249 }
250
251 /**
252 * Convert to a string
253 */
254
255 public String toString() {
256 return subSequence(0, length).toString();
257 }
258
259 /**
260 * Compare equality
261 */
262
263 public boolean equals(Object other) {
264 return other instanceof CharSequence && toString().equals(other.toString());
265 }
266
267 /**
268 * Generate a hash code
269 */
270
271 public int hashCode() {
272 // Same algorithm as String#hashCode(), but not cached
273 int h = 0;
274 for (char[] chars : data) {
275 for (int i = 0; i < SEGLEN; i++) {
276 h = 31 * h + chars[i];
277 }
278 }
279 return h;
280 }
281
282 /**
283 * Returns a new character sequence that is a subsequence of this sequence.
284 * Unlike subSequence, this is guaranteed to return a String.
285 *
286 * @param start index of the first character to be included
287 * @param end index of the character after the last one to be included
288 * @return the substring at the given position
289 */
290
291 public String substring(int start, int end) {
292 return subSequence(start, end).toString();
293 }
294
295 /**
296 * Write the value to a writer
297 *
298 * @param writer the writer to which the value is to be written
299 * @throws java.io.IOException if an error occurs downstream
300 */
301
302 public void write(java.io.Writer writer) throws java.io.IOException {
303 writer.write(toString());
304 }
305
306 /**
307 * Produce diagnostic dump
308 */
309
310 // public void dumpDataStructure() {
311 // System.err.println("** Segments:");
312 // for (int s = 0; s < segments.size(); s++) {
313 // System.err.println(" SEG " + s + " start offset " + startOffsets[s] + " length "
314 // + ((FastStringBuffer)segments.get(s)).length());
315 // }
316 // }
317
318 // public static void main(String[] args) {
319 // LargeStringBuffer lsb = new LargeStringBuffer();
320 // for (int i=0; i<30; i++) {
321 // char[] chars = new char[i*5000];
322 // Arrays.fill(chars, 'x');
323 // lsb.append(new String(chars));
324 // lsb.append("");
325 // }
326 // for (int i=0; i<lsb.length()-10000; i+=10000) {
327 // System.out.println(i + ":" + lsb.subSequence(i, i+9999).length());
328 // }
329 // lsb.dumpDataStructure();
330 // }
331
332 }
333