• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.lang;
27 
28 import sun.misc.FloatingDecimal;
29 import java.util.Arrays;
30 
31 /**
32  * A mutable sequence of characters.
33  * <p>
34  * Implements a modifiable string. At any point in time it contains some
35  * particular sequence of characters, but the length and content of the
36  * sequence can be changed through certain method calls.
37  *
38  * <p>Unless otherwise noted, passing a {@code null} argument to a constructor
39  * or method in this class will cause a {@link NullPointerException} to be
40  * thrown.
41  *
42  * @author      Michael McCloskey
43  * @author      Martin Buchholz
44  * @author      Ulf Zibis
45  * @since       1.5
46  */
47 abstract class AbstractStringBuilder implements Appendable, CharSequence {
48     /**
49      * The value is used for character storage.
50      */
51     char[] value;
52 
53     /**
54      * The count is the number of characters used.
55      */
56     int count;
57 
58     /**
59      * This no-arg constructor is necessary for serialization of subclasses.
60      */
AbstractStringBuilder()61     AbstractStringBuilder() {
62     }
63 
64     /**
65      * Creates an AbstractStringBuilder of the specified capacity.
66      */
AbstractStringBuilder(int capacity)67     AbstractStringBuilder(int capacity) {
68         value = new char[capacity];
69     }
70 
71     /**
72      * Returns the length (character count).
73      *
74      * @return  the length of the sequence of characters currently
75      *          represented by this object
76      */
77     @Override
length()78     public int length() {
79         return count;
80     }
81 
82     /**
83      * Returns the current capacity. The capacity is the amount of storage
84      * available for newly inserted characters, beyond which an allocation
85      * will occur.
86      *
87      * @return  the current capacity
88      */
capacity()89     public int capacity() {
90         return value.length;
91     }
92 
93     /**
94      * Ensures that the capacity is at least equal to the specified minimum.
95      * If the current capacity is less than the argument, then a new internal
96      * array is allocated with greater capacity. The new capacity is the
97      * larger of:
98      * <ul>
99      * <li>The {@code minimumCapacity} argument.
100      * <li>Twice the old capacity, plus {@code 2}.
101      * </ul>
102      * If the {@code minimumCapacity} argument is nonpositive, this
103      * method takes no action and simply returns.
104      * Note that subsequent operations on this object can reduce the
105      * actual capacity below that requested here.
106      *
107      * @param   minimumCapacity   the minimum desired capacity.
108      */
ensureCapacity(int minimumCapacity)109     public void ensureCapacity(int minimumCapacity) {
110         if (minimumCapacity > 0)
111             ensureCapacityInternal(minimumCapacity);
112     }
113 
114     /**
115      * For positive values of {@code minimumCapacity}, this method
116      * behaves like {@code ensureCapacity}, however it is never
117      * synchronized.
118      * If {@code minimumCapacity} is non positive due to numeric
119      * overflow, this method throws {@code OutOfMemoryError}.
120      */
ensureCapacityInternal(int minimumCapacity)121     private void ensureCapacityInternal(int minimumCapacity) {
122         // overflow-conscious code
123         if (minimumCapacity - value.length > 0) {
124             value = Arrays.copyOf(value,
125                     newCapacity(minimumCapacity));
126         }
127     }
128 
129     /**
130      * The maximum size of array to allocate (unless necessary).
131      * Some VMs reserve some header words in an array.
132      * Attempts to allocate larger arrays may result in
133      * OutOfMemoryError: Requested array size exceeds VM limit
134      */
135     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
136 
137     /**
138      * Returns a capacity at least as large as the given minimum capacity.
139      * Returns the current capacity increased by the same amount + 2 if
140      * that suffices.
141      * Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
142      * unless the given minimum capacity is greater than that.
143      *
144      * @param  minCapacity the desired minimum capacity
145      * @throws OutOfMemoryError if minCapacity is less than zero or
146      *         greater than Integer.MAX_VALUE
147      */
newCapacity(int minCapacity)148     private int newCapacity(int minCapacity) {
149         // overflow-conscious code
150         int newCapacity = (value.length << 1) + 2;
151         if (newCapacity - minCapacity < 0) {
152             newCapacity = minCapacity;
153         }
154         return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
155             ? hugeCapacity(minCapacity)
156             : newCapacity;
157     }
158 
hugeCapacity(int minCapacity)159     private int hugeCapacity(int minCapacity) {
160         if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
161             throw new OutOfMemoryError();
162         }
163         return (minCapacity > MAX_ARRAY_SIZE)
164             ? minCapacity : MAX_ARRAY_SIZE;
165     }
166 
167     /**
168      * Attempts to reduce storage used for the character sequence.
169      * If the buffer is larger than necessary to hold its current sequence of
170      * characters, then it may be resized to become more space efficient.
171      * Calling this method may, but is not required to, affect the value
172      * returned by a subsequent call to the {@link #capacity()} method.
173      */
trimToSize()174     public void trimToSize() {
175         if (count < value.length) {
176             value = Arrays.copyOf(value, count);
177         }
178     }
179 
180     /**
181      * Sets the length of the character sequence.
182      * The sequence is changed to a new character sequence
183      * whose length is specified by the argument. For every nonnegative
184      * index <i>k</i> less than {@code newLength}, the character at
185      * index <i>k</i> in the new character sequence is the same as the
186      * character at index <i>k</i> in the old sequence if <i>k</i> is less
187      * than the length of the old character sequence; otherwise, it is the
188      * null character {@code '\u005Cu0000'}.
189      *
190      * In other words, if the {@code newLength} argument is less than
191      * the current length, the length is changed to the specified length.
192      * <p>
193      * If the {@code newLength} argument is greater than or equal
194      * to the current length, sufficient null characters
195      * ({@code '\u005Cu0000'}) are appended so that
196      * length becomes the {@code newLength} argument.
197      * <p>
198      * The {@code newLength} argument must be greater than or equal
199      * to {@code 0}.
200      *
201      * @param      newLength   the new length
202      * @throws     IndexOutOfBoundsException  if the
203      *               {@code newLength} argument is negative.
204      */
setLength(int newLength)205     public void setLength(int newLength) {
206         if (newLength < 0)
207             throw new StringIndexOutOfBoundsException(newLength);
208         ensureCapacityInternal(newLength);
209 
210         if (count < newLength) {
211             Arrays.fill(value, count, newLength, '\0');
212         }
213 
214         count = newLength;
215     }
216 
217     /**
218      * Returns the {@code char} value in this sequence at the specified index.
219      * The first {@code char} value is at index {@code 0}, the next at index
220      * {@code 1}, and so on, as in array indexing.
221      * <p>
222      * The index argument must be greater than or equal to
223      * {@code 0}, and less than the length of this sequence.
224      *
225      * <p>If the {@code char} value specified by the index is a
226      * <a href="Character.html#unicode">surrogate</a>, the surrogate
227      * value is returned.
228      *
229      * @param      index   the index of the desired {@code char} value.
230      * @return     the {@code char} value at the specified index.
231      * @throws     IndexOutOfBoundsException  if {@code index} is
232      *             negative or greater than or equal to {@code length()}.
233      */
234     @Override
charAt(int index)235     public char charAt(int index) {
236         if ((index < 0) || (index >= count))
237             throw new StringIndexOutOfBoundsException(index);
238         return value[index];
239     }
240 
241     /**
242      * Returns the character (Unicode code point) at the specified
243      * index. The index refers to {@code char} values
244      * (Unicode code units) and ranges from {@code 0} to
245      * {@link #length()}{@code  - 1}.
246      *
247      * <p> If the {@code char} value specified at the given index
248      * is in the high-surrogate range, the following index is less
249      * than the length of this sequence, and the
250      * {@code char} value at the following index is in the
251      * low-surrogate range, then the supplementary code point
252      * corresponding to this surrogate pair is returned. Otherwise,
253      * the {@code char} value at the given index is returned.
254      *
255      * @param      index the index to the {@code char} values
256      * @return     the code point value of the character at the
257      *             {@code index}
258      * @exception  IndexOutOfBoundsException  if the {@code index}
259      *             argument is negative or not less than the length of this
260      *             sequence.
261      */
codePointAt(int index)262     public int codePointAt(int index) {
263         if ((index < 0) || (index >= count)) {
264             throw new StringIndexOutOfBoundsException(index);
265         }
266         return Character.codePointAtImpl(value, index, count);
267     }
268 
269     /**
270      * Returns the character (Unicode code point) before the specified
271      * index. The index refers to {@code char} values
272      * (Unicode code units) and ranges from {@code 1} to {@link
273      * #length()}.
274      *
275      * <p> If the {@code char} value at {@code (index - 1)}
276      * is in the low-surrogate range, {@code (index - 2)} is not
277      * negative, and the {@code char} value at {@code (index -
278      * 2)} is in the high-surrogate range, then the
279      * supplementary code point value of the surrogate pair is
280      * returned. If the {@code char} value at {@code index -
281      * 1} is an unpaired low-surrogate or a high-surrogate, the
282      * surrogate value is returned.
283      *
284      * @param     index the index following the code point that should be returned
285      * @return    the Unicode code point value before the given index.
286      * @exception IndexOutOfBoundsException if the {@code index}
287      *            argument is less than 1 or greater than the length
288      *            of this sequence.
289      */
codePointBefore(int index)290     public int codePointBefore(int index) {
291         int i = index - 1;
292         if ((i < 0) || (i >= count)) {
293             throw new StringIndexOutOfBoundsException(index);
294         }
295         return Character.codePointBeforeImpl(value, index, 0);
296     }
297 
298     /**
299      * Returns the number of Unicode code points in the specified text
300      * range of this sequence. The text range begins at the specified
301      * {@code beginIndex} and extends to the {@code char} at
302      * index {@code endIndex - 1}. Thus the length (in
303      * {@code char}s) of the text range is
304      * {@code endIndex-beginIndex}. Unpaired surrogates within
305      * this sequence count as one code point each.
306      *
307      * @param beginIndex the index to the first {@code char} of
308      * the text range.
309      * @param endIndex the index after the last {@code char} of
310      * the text range.
311      * @return the number of Unicode code points in the specified text
312      * range
313      * @exception IndexOutOfBoundsException if the
314      * {@code beginIndex} is negative, or {@code endIndex}
315      * is larger than the length of this sequence, or
316      * {@code beginIndex} is larger than {@code endIndex}.
317      */
codePointCount(int beginIndex, int endIndex)318     public int codePointCount(int beginIndex, int endIndex) {
319         if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
320             throw new IndexOutOfBoundsException();
321         }
322         return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
323     }
324 
325     /**
326      * Returns the index within this sequence that is offset from the
327      * given {@code index} by {@code codePointOffset} code
328      * points. Unpaired surrogates within the text range given by
329      * {@code index} and {@code codePointOffset} count as
330      * one code point each.
331      *
332      * @param index the index to be offset
333      * @param codePointOffset the offset in code points
334      * @return the index within this sequence
335      * @exception IndexOutOfBoundsException if {@code index}
336      *   is negative or larger then the length of this sequence,
337      *   or if {@code codePointOffset} is positive and the subsequence
338      *   starting with {@code index} has fewer than
339      *   {@code codePointOffset} code points,
340      *   or if {@code codePointOffset} is negative and the subsequence
341      *   before {@code index} has fewer than the absolute value of
342      *   {@code codePointOffset} code points.
343      */
offsetByCodePoints(int index, int codePointOffset)344     public int offsetByCodePoints(int index, int codePointOffset) {
345         if (index < 0 || index > count) {
346             throw new IndexOutOfBoundsException();
347         }
348         return Character.offsetByCodePointsImpl(value, 0, count,
349                                                 index, codePointOffset);
350     }
351 
352     /**
353      * Characters are copied from this sequence into the
354      * destination character array {@code dst}. The first character to
355      * be copied is at index {@code srcBegin}; the last character to
356      * be copied is at index {@code srcEnd-1}. The total number of
357      * characters to be copied is {@code srcEnd-srcBegin}. The
358      * characters are copied into the subarray of {@code dst} starting
359      * at index {@code dstBegin} and ending at index:
360      * <pre>{@code
361      * dstbegin + (srcEnd-srcBegin) - 1
362      * }</pre>
363      *
364      * @param      srcBegin   start copying at this offset.
365      * @param      srcEnd     stop copying at this offset.
366      * @param      dst        the array to copy the data into.
367      * @param      dstBegin   offset into {@code dst}.
368      * @throws     IndexOutOfBoundsException  if any of the following is true:
369      *             <ul>
370      *             <li>{@code srcBegin} is negative
371      *             <li>{@code dstBegin} is negative
372      *             <li>the {@code srcBegin} argument is greater than
373      *             the {@code srcEnd} argument.
374      *             <li>{@code srcEnd} is greater than
375      *             {@code this.length()}.
376      *             <li>{@code dstBegin+srcEnd-srcBegin} is greater than
377      *             {@code dst.length}
378      *             </ul>
379      */
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)380     public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
381     {
382         if (srcBegin < 0)
383             throw new StringIndexOutOfBoundsException(srcBegin);
384         if ((srcEnd < 0) || (srcEnd > count))
385             throw new StringIndexOutOfBoundsException(srcEnd);
386         if (srcBegin > srcEnd)
387             throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
388         System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
389     }
390 
391     /**
392      * The character at the specified index is set to {@code ch}. This
393      * sequence is altered to represent a new character sequence that is
394      * identical to the old character sequence, except that it contains the
395      * character {@code ch} at position {@code index}.
396      * <p>
397      * The index argument must be greater than or equal to
398      * {@code 0}, and less than the length of this sequence.
399      *
400      * @param      index   the index of the character to modify.
401      * @param      ch      the new character.
402      * @throws     IndexOutOfBoundsException  if {@code index} is
403      *             negative or greater than or equal to {@code length()}.
404      */
setCharAt(int index, char ch)405     public void setCharAt(int index, char ch) {
406         if ((index < 0) || (index >= count))
407             throw new StringIndexOutOfBoundsException(index);
408         value[index] = ch;
409     }
410 
411     /**
412      * Appends the string representation of the {@code Object} argument.
413      * <p>
414      * The overall effect is exactly as if the argument were converted
415      * to a string by the method {@link String#valueOf(Object)},
416      * and the characters of that string were then
417      * {@link #append(String) appended} to this character sequence.
418      *
419      * @param   obj   an {@code Object}.
420      * @return  a reference to this object.
421      */
append(Object obj)422     public AbstractStringBuilder append(Object obj) {
423         return append(String.valueOf(obj));
424     }
425 
426     /**
427      * Appends the specified string to this character sequence.
428      * <p>
429      * The characters of the {@code String} argument are appended, in
430      * order, increasing the length of this sequence by the length of the
431      * argument. If {@code str} is {@code null}, then the four
432      * characters {@code "null"} are appended.
433      * <p>
434      * Let <i>n</i> be the length of this character sequence just prior to
435      * execution of the {@code append} method. Then the character at
436      * index <i>k</i> in the new character sequence is equal to the character
437      * at index <i>k</i> in the old character sequence, if <i>k</i> is less
438      * than <i>n</i>; otherwise, it is equal to the character at index
439      * <i>k-n</i> in the argument {@code str}.
440      *
441      * @param   str   a string.
442      * @return  a reference to this object.
443      */
append(String str)444     public AbstractStringBuilder append(String str) {
445         if (str == null)
446             return appendNull();
447         int len = str.length();
448         ensureCapacityInternal(count + len);
449         str.getChars(0, len, value, count);
450         count += len;
451         return this;
452     }
453 
454     // Documentation in subclasses because of synchro difference
append(StringBuffer sb)455     public AbstractStringBuilder append(StringBuffer sb) {
456         if (sb == null)
457             return appendNull();
458         int len = sb.length();
459         ensureCapacityInternal(count + len);
460         sb.getChars(0, len, value, count);
461         count += len;
462         return this;
463     }
464 
465     /**
466      * @since 1.8
467      */
append(AbstractStringBuilder asb)468     AbstractStringBuilder append(AbstractStringBuilder asb) {
469         if (asb == null)
470             return appendNull();
471         int len = asb.length();
472         ensureCapacityInternal(count + len);
473         asb.getChars(0, len, value, count);
474         count += len;
475         return this;
476     }
477 
478     // Documentation in subclasses because of synchro difference
479     @Override
append(CharSequence s)480     public AbstractStringBuilder append(CharSequence s) {
481         if (s == null)
482             return appendNull();
483         if (s instanceof String)
484             return this.append((String)s);
485         if (s instanceof AbstractStringBuilder)
486             return this.append((AbstractStringBuilder)s);
487 
488         return this.append(s, 0, s.length());
489     }
490 
appendNull()491     private AbstractStringBuilder appendNull() {
492         int c = count;
493         ensureCapacityInternal(c + 4);
494         final char[] value = this.value;
495         value[c++] = 'n';
496         value[c++] = 'u';
497         value[c++] = 'l';
498         value[c++] = 'l';
499         count = c;
500         return this;
501     }
502 
503     /**
504      * Appends a subsequence of the specified {@code CharSequence} to this
505      * sequence.
506      * <p>
507      * Characters of the argument {@code s}, starting at
508      * index {@code start}, are appended, in order, to the contents of
509      * this sequence up to the (exclusive) index {@code end}. The length
510      * of this sequence is increased by the value of {@code end - start}.
511      * <p>
512      * Let <i>n</i> be the length of this character sequence just prior to
513      * execution of the {@code append} method. Then the character at
514      * index <i>k</i> in this character sequence becomes equal to the
515      * character at index <i>k</i> in this sequence, if <i>k</i> is less than
516      * <i>n</i>; otherwise, it is equal to the character at index
517      * <i>k+start-n</i> in the argument {@code s}.
518      * <p>
519      * If {@code s} is {@code null}, then this method appends
520      * characters as if the s parameter was a sequence containing the four
521      * characters {@code "null"}.
522      *
523      * @param   s the sequence to append.
524      * @param   start   the starting index of the subsequence to be appended.
525      * @param   end     the end index of the subsequence to be appended.
526      * @return  a reference to this object.
527      * @throws     IndexOutOfBoundsException if
528      *             {@code start} is negative, or
529      *             {@code start} is greater than {@code end} or
530      *             {@code end} is greater than {@code s.length()}
531      */
532     @Override
append(CharSequence s, int start, int end)533     public AbstractStringBuilder append(CharSequence s, int start, int end) {
534         if (s == null)
535             s = "null";
536         if ((start < 0) || (start > end) || (end > s.length()))
537             throw new IndexOutOfBoundsException(
538                 "start " + start + ", end " + end + ", s.length() "
539                 + s.length());
540         int len = end - start;
541         ensureCapacityInternal(count + len);
542         for (int i = start, j = count; i < end; i++, j++)
543             value[j] = s.charAt(i);
544         count += len;
545         return this;
546     }
547 
548     /**
549      * Appends the string representation of the {@code char} array
550      * argument to this sequence.
551      * <p>
552      * The characters of the array argument are appended, in order, to
553      * the contents of this sequence. The length of this sequence
554      * increases by the length of the argument.
555      * <p>
556      * The overall effect is exactly as if the argument were converted
557      * to a string by the method {@link String#valueOf(char[])},
558      * and the characters of that string were then
559      * {@link #append(String) appended} to this character sequence.
560      *
561      * @param   str   the characters to be appended.
562      * @return  a reference to this object.
563      */
append(char[] str)564     public AbstractStringBuilder append(char[] str) {
565         int len = str.length;
566         ensureCapacityInternal(count + len);
567         System.arraycopy(str, 0, value, count, len);
568         count += len;
569         return this;
570     }
571 
572     /**
573      * Appends the string representation of a subarray of the
574      * {@code char} array argument to this sequence.
575      * <p>
576      * Characters of the {@code char} array {@code str}, starting at
577      * index {@code offset}, are appended, in order, to the contents
578      * of this sequence. The length of this sequence increases
579      * by the value of {@code len}.
580      * <p>
581      * The overall effect is exactly as if the arguments were converted
582      * to a string by the method {@link String#valueOf(char[],int,int)},
583      * and the characters of that string were then
584      * {@link #append(String) appended} to this character sequence.
585      *
586      * @param   str      the characters to be appended.
587      * @param   offset   the index of the first {@code char} to append.
588      * @param   len      the number of {@code char}s to append.
589      * @return  a reference to this object.
590      * @throws IndexOutOfBoundsException
591      *         if {@code offset < 0} or {@code len < 0}
592      *         or {@code offset+len > str.length}
593      */
append(char str[], int offset, int len)594     public AbstractStringBuilder append(char str[], int offset, int len) {
595         if (len > 0)                // let arraycopy report AIOOBE for len < 0
596             ensureCapacityInternal(count + len);
597         System.arraycopy(str, offset, value, count, len);
598         count += len;
599         return this;
600     }
601 
602     /**
603      * Appends the string representation of the {@code boolean}
604      * argument to the sequence.
605      * <p>
606      * The overall effect is exactly as if the argument were converted
607      * to a string by the method {@link String#valueOf(boolean)},
608      * and the characters of that string were then
609      * {@link #append(String) appended} to this character sequence.
610      *
611      * @param   b   a {@code boolean}.
612      * @return  a reference to this object.
613      */
append(boolean b)614     public AbstractStringBuilder append(boolean b) {
615         if (b) {
616             ensureCapacityInternal(count + 4);
617             value[count++] = 't';
618             value[count++] = 'r';
619             value[count++] = 'u';
620             value[count++] = 'e';
621         } else {
622             ensureCapacityInternal(count + 5);
623             value[count++] = 'f';
624             value[count++] = 'a';
625             value[count++] = 'l';
626             value[count++] = 's';
627             value[count++] = 'e';
628         }
629         return this;
630     }
631 
632     /**
633      * Appends the string representation of the {@code char}
634      * argument to this sequence.
635      * <p>
636      * The argument is appended to the contents of this sequence.
637      * The length of this sequence increases by {@code 1}.
638      * <p>
639      * The overall effect is exactly as if the argument were converted
640      * to a string by the method {@link String#valueOf(char)},
641      * and the character in that string were then
642      * {@link #append(String) appended} to this character sequence.
643      *
644      * @param   c   a {@code char}.
645      * @return  a reference to this object.
646      */
647     @Override
append(char c)648     public AbstractStringBuilder append(char c) {
649         ensureCapacityInternal(count + 1);
650         value[count++] = c;
651         return this;
652     }
653 
654     /**
655      * Appends the string representation of the {@code int}
656      * argument to this sequence.
657      * <p>
658      * The overall effect is exactly as if the argument were converted
659      * to a string by the method {@link String#valueOf(int)},
660      * and the characters of that string were then
661      * {@link #append(String) appended} to this character sequence.
662      *
663      * @param   i   an {@code int}.
664      * @return  a reference to this object.
665      */
append(int i)666     public AbstractStringBuilder append(int i) {
667         if (i == Integer.MIN_VALUE) {
668             append("-2147483648");
669             return this;
670         }
671         int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
672                                      : Integer.stringSize(i);
673         int spaceNeeded = count + appendedLength;
674         ensureCapacityInternal(spaceNeeded);
675         Integer.getChars(i, spaceNeeded, value);
676         count = spaceNeeded;
677         return this;
678     }
679 
680     /**
681      * Appends the string representation of the {@code long}
682      * argument to this sequence.
683      * <p>
684      * The overall effect is exactly as if the argument were converted
685      * to a string by the method {@link String#valueOf(long)},
686      * and the characters of that string were then
687      * {@link #append(String) appended} to this character sequence.
688      *
689      * @param   l   a {@code long}.
690      * @return  a reference to this object.
691      */
append(long l)692     public AbstractStringBuilder append(long l) {
693         if (l == Long.MIN_VALUE) {
694             append("-9223372036854775808");
695             return this;
696         }
697         int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
698                                      : Long.stringSize(l);
699         int spaceNeeded = count + appendedLength;
700         ensureCapacityInternal(spaceNeeded);
701         Long.getChars(l, spaceNeeded, value);
702         count = spaceNeeded;
703         return this;
704     }
705 
706     /**
707      * Appends the string representation of the {@code float}
708      * argument to this sequence.
709      * <p>
710      * The overall effect is exactly as if the argument were converted
711      * to a string by the method {@link String#valueOf(float)},
712      * and the characters of that string were then
713      * {@link #append(String) appended} to this character sequence.
714      *
715      * @param   f   a {@code float}.
716      * @return  a reference to this object.
717      */
append(float f)718     public AbstractStringBuilder append(float f) {
719         FloatingDecimal.appendTo(f,this);
720         return this;
721     }
722 
723     /**
724      * Appends the string representation of the {@code double}
725      * argument to this sequence.
726      * <p>
727      * The overall effect is exactly as if the argument were converted
728      * to a string by the method {@link String#valueOf(double)},
729      * and the characters of that string were then
730      * {@link #append(String) appended} to this character sequence.
731      *
732      * @param   d   a {@code double}.
733      * @return  a reference to this object.
734      */
append(double d)735     public AbstractStringBuilder append(double d) {
736         FloatingDecimal.appendTo(d,this);
737         return this;
738     }
739 
740     /**
741      * Removes the characters in a substring of this sequence.
742      * The substring begins at the specified {@code start} and extends to
743      * the character at index {@code end - 1} or to the end of the
744      * sequence if no such character exists. If
745      * {@code start} is equal to {@code end}, no changes are made.
746      *
747      * @param      start  The beginning index, inclusive.
748      * @param      end    The ending index, exclusive.
749      * @return     This object.
750      * @throws     StringIndexOutOfBoundsException  if {@code start}
751      *             is negative, greater than {@code length()}, or
752      *             greater than {@code end}.
753      */
delete(int start, int end)754     public AbstractStringBuilder delete(int start, int end) {
755         if (start < 0)
756             throw new StringIndexOutOfBoundsException(start);
757         if (end > count)
758             end = count;
759         if (start > end)
760             throw new StringIndexOutOfBoundsException();
761         int len = end - start;
762         if (len > 0) {
763             System.arraycopy(value, start+len, value, start, count-end);
764             count -= len;
765         }
766         return this;
767     }
768 
769     /**
770      * Appends the string representation of the {@code codePoint}
771      * argument to this sequence.
772      *
773      * <p> The argument is appended to the contents of this sequence.
774      * The length of this sequence increases by
775      * {@link Character#charCount(int) Character.charCount(codePoint)}.
776      *
777      * <p> The overall effect is exactly as if the argument were
778      * converted to a {@code char} array by the method
779      * {@link Character#toChars(int)} and the character in that array
780      * were then {@link #append(char[]) appended} to this character
781      * sequence.
782      *
783      * @param   codePoint   a Unicode code point
784      * @return  a reference to this object.
785      * @exception IllegalArgumentException if the specified
786      * {@code codePoint} isn't a valid Unicode code point
787      */
appendCodePoint(int codePoint)788     public AbstractStringBuilder appendCodePoint(int codePoint) {
789         final int count = this.count;
790 
791         if (Character.isBmpCodePoint(codePoint)) {
792             ensureCapacityInternal(count + 1);
793             value[count] = (char) codePoint;
794             this.count = count + 1;
795         } else if (Character.isValidCodePoint(codePoint)) {
796             ensureCapacityInternal(count + 2);
797             Character.toSurrogates(codePoint, value, count);
798             this.count = count + 2;
799         } else {
800             throw new IllegalArgumentException();
801         }
802         return this;
803     }
804 
805     /**
806      * Removes the {@code char} at the specified position in this
807      * sequence. This sequence is shortened by one {@code char}.
808      *
809      * <p>Note: If the character at the given index is a supplementary
810      * character, this method does not remove the entire character. If
811      * correct handling of supplementary characters is required,
812      * determine the number of {@code char}s to remove by calling
813      * {@code Character.charCount(thisSequence.codePointAt(index))},
814      * where {@code thisSequence} is this sequence.
815      *
816      * @param       index  Index of {@code char} to remove
817      * @return      This object.
818      * @throws      StringIndexOutOfBoundsException  if the {@code index}
819      *              is negative or greater than or equal to
820      *              {@code length()}.
821      */
deleteCharAt(int index)822     public AbstractStringBuilder deleteCharAt(int index) {
823         if ((index < 0) || (index >= count))
824             throw new StringIndexOutOfBoundsException(index);
825         System.arraycopy(value, index+1, value, index, count-index-1);
826         count--;
827         return this;
828     }
829 
830     /**
831      * Replaces the characters in a substring of this sequence
832      * with characters in the specified {@code String}. The substring
833      * begins at the specified {@code start} and extends to the character
834      * at index {@code end - 1} or to the end of the
835      * sequence if no such character exists. First the
836      * characters in the substring are removed and then the specified
837      * {@code String} is inserted at {@code start}. (This
838      * sequence will be lengthened to accommodate the
839      * specified String if necessary.)
840      *
841      * @param      start    The beginning index, inclusive.
842      * @param      end      The ending index, exclusive.
843      * @param      str   String that will replace previous contents.
844      * @return     This object.
845      * @throws     StringIndexOutOfBoundsException  if {@code start}
846      *             is negative, greater than {@code length()}, or
847      *             greater than {@code end}.
848      */
replace(int start, int end, String str)849     public AbstractStringBuilder replace(int start, int end, String str) {
850         if (start < 0)
851             throw new StringIndexOutOfBoundsException(start);
852         if (start > count)
853             throw new StringIndexOutOfBoundsException("start > length()");
854         if (start > end)
855             throw new StringIndexOutOfBoundsException("start > end");
856 
857         if (end > count)
858             end = count;
859         int len = str.length();
860         int newCount = count + len - (end - start);
861         ensureCapacityInternal(newCount);
862 
863         System.arraycopy(value, end, value, start + len, count - end);
864         str.getChars(value, start);
865         count = newCount;
866         return this;
867     }
868 
869     /**
870      * Returns a new {@code String} that contains a subsequence of
871      * characters currently contained in this character sequence. The
872      * substring begins at the specified index and extends to the end of
873      * this sequence.
874      *
875      * @param      start    The beginning index, inclusive.
876      * @return     The new string.
877      * @throws     StringIndexOutOfBoundsException  if {@code start} is
878      *             less than zero, or greater than the length of this object.
879      */
substring(int start)880     public String substring(int start) {
881         return substring(start, count);
882     }
883 
884     /**
885      * Returns a new character sequence that is a subsequence of this sequence.
886      *
887      * <p> An invocation of this method of the form
888      *
889      * <pre>{@code
890      * sb.subSequence(begin,&nbsp;end)}</pre>
891      *
892      * behaves in exactly the same way as the invocation
893      *
894      * <pre>{@code
895      * sb.substring(begin,&nbsp;end)}</pre>
896      *
897      * This method is provided so that this class can
898      * implement the {@link CharSequence} interface.
899      *
900      * @param      start   the start index, inclusive.
901      * @param      end     the end index, exclusive.
902      * @return     the specified subsequence.
903      *
904      * @throws  IndexOutOfBoundsException
905      *          if {@code start} or {@code end} are negative,
906      *          if {@code end} is greater than {@code length()},
907      *          or if {@code start} is greater than {@code end}
908      * @spec JSR-51
909      */
910     @Override
subSequence(int start, int end)911     public CharSequence subSequence(int start, int end) {
912         return substring(start, end);
913     }
914 
915     /**
916      * Returns a new {@code String} that contains a subsequence of
917      * characters currently contained in this sequence. The
918      * substring begins at the specified {@code start} and
919      * extends to the character at index {@code end - 1}.
920      *
921      * @param      start    The beginning index, inclusive.
922      * @param      end      The ending index, exclusive.
923      * @return     The new string.
924      * @throws     StringIndexOutOfBoundsException  if {@code start}
925      *             or {@code end} are negative or greater than
926      *             {@code length()}, or {@code start} is
927      *             greater than {@code end}.
928      */
substring(int start, int end)929     public String substring(int start, int end) {
930         if (start < 0)
931             throw new StringIndexOutOfBoundsException(start);
932         if (end > count)
933             throw new StringIndexOutOfBoundsException(end);
934         if (start > end)
935             throw new StringIndexOutOfBoundsException(end - start);
936         return new String(value, start, end - start);
937     }
938 
939     /**
940      * Inserts the string representation of a subarray of the {@code str}
941      * array argument into this sequence. The subarray begins at the
942      * specified {@code offset} and extends {@code len} {@code char}s.
943      * The characters of the subarray are inserted into this sequence at
944      * the position indicated by {@code index}. The length of this
945      * sequence increases by {@code len} {@code char}s.
946      *
947      * @param      index    position at which to insert subarray.
948      * @param      str       A {@code char} array.
949      * @param      offset   the index of the first {@code char} in subarray to
950      *             be inserted.
951      * @param      len      the number of {@code char}s in the subarray to
952      *             be inserted.
953      * @return     This object
954      * @throws     StringIndexOutOfBoundsException  if {@code index}
955      *             is negative or greater than {@code length()}, or
956      *             {@code offset} or {@code len} are negative, or
957      *             {@code (offset+len)} is greater than
958      *             {@code str.length}.
959      */
insert(int index, char[] str, int offset, int len)960     public AbstractStringBuilder insert(int index, char[] str, int offset,
961                                         int len)
962     {
963         if ((index < 0) || (index > length()))
964             throw new StringIndexOutOfBoundsException(index);
965         if ((offset < 0) || (len < 0) || (offset > str.length - len))
966             throw new StringIndexOutOfBoundsException(
967                 "offset " + offset + ", len " + len + ", str.length "
968                 + str.length);
969         ensureCapacityInternal(count + len);
970         System.arraycopy(value, index, value, index + len, count - index);
971         System.arraycopy(str, offset, value, index, len);
972         count += len;
973         return this;
974     }
975 
976     /**
977      * Inserts the string representation of the {@code Object}
978      * argument into this character sequence.
979      * <p>
980      * The overall effect is exactly as if the second argument were
981      * converted to a string by the method {@link String#valueOf(Object)},
982      * and the characters of that string were then
983      * {@link #insert(int,String) inserted} into this character
984      * sequence at the indicated offset.
985      * <p>
986      * The {@code offset} argument must be greater than or equal to
987      * {@code 0}, and less than or equal to the {@linkplain #length() length}
988      * of this sequence.
989      *
990      * @param      offset   the offset.
991      * @param      obj      an {@code Object}.
992      * @return     a reference to this object.
993      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
994      */
insert(int offset, Object obj)995     public AbstractStringBuilder insert(int offset, Object obj) {
996         return insert(offset, String.valueOf(obj));
997     }
998 
999     /**
1000      * Inserts the string into this character sequence.
1001      * <p>
1002      * The characters of the {@code String} argument are inserted, in
1003      * order, into this sequence at the indicated offset, moving up any
1004      * characters originally above that position and increasing the length
1005      * of this sequence by the length of the argument. If
1006      * {@code str} is {@code null}, then the four characters
1007      * {@code "null"} are inserted into this sequence.
1008      * <p>
1009      * The character at index <i>k</i> in the new character sequence is
1010      * equal to:
1011      * <ul>
1012      * <li>the character at index <i>k</i> in the old character sequence, if
1013      * <i>k</i> is less than {@code offset}
1014      * <li>the character at index <i>k</i>{@code -offset} in the
1015      * argument {@code str}, if <i>k</i> is not less than
1016      * {@code offset} but is less than {@code offset+str.length()}
1017      * <li>the character at index <i>k</i>{@code -str.length()} in the
1018      * old character sequence, if <i>k</i> is not less than
1019      * {@code offset+str.length()}
1020      * </ul><p>
1021      * The {@code offset} argument must be greater than or equal to
1022      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1023      * of this sequence.
1024      *
1025      * @param      offset   the offset.
1026      * @param      str      a string.
1027      * @return     a reference to this object.
1028      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1029      */
insert(int offset, String str)1030     public AbstractStringBuilder insert(int offset, String str) {
1031         if ((offset < 0) || (offset > length()))
1032             throw new StringIndexOutOfBoundsException(offset);
1033         if (str == null)
1034             str = "null";
1035         int len = str.length();
1036         ensureCapacityInternal(count + len);
1037         System.arraycopy(value, offset, value, offset + len, count - offset);
1038         str.getChars(value, offset);
1039         count += len;
1040         return this;
1041     }
1042 
1043     /**
1044      * Inserts the string representation of the {@code char} array
1045      * argument into this sequence.
1046      * <p>
1047      * The characters of the array argument are inserted into the
1048      * contents of this sequence at the position indicated by
1049      * {@code offset}. The length of this sequence increases by
1050      * the length of the argument.
1051      * <p>
1052      * The overall effect is exactly as if the second argument were
1053      * converted to a string by the method {@link String#valueOf(char[])},
1054      * and the characters of that string were then
1055      * {@link #insert(int,String) inserted} into this character
1056      * sequence at the indicated offset.
1057      * <p>
1058      * The {@code offset} argument must be greater than or equal to
1059      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1060      * of this sequence.
1061      *
1062      * @param      offset   the offset.
1063      * @param      str      a character array.
1064      * @return     a reference to this object.
1065      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1066      */
insert(int offset, char[] str)1067     public AbstractStringBuilder insert(int offset, char[] str) {
1068         if ((offset < 0) || (offset > length()))
1069             throw new StringIndexOutOfBoundsException(offset);
1070         int len = str.length;
1071         ensureCapacityInternal(count + len);
1072         System.arraycopy(value, offset, value, offset + len, count - offset);
1073         System.arraycopy(str, 0, value, offset, len);
1074         count += len;
1075         return this;
1076     }
1077 
1078     /**
1079      * Inserts the specified {@code CharSequence} into this sequence.
1080      * <p>
1081      * The characters of the {@code CharSequence} argument are inserted,
1082      * in order, into this sequence at the indicated offset, moving up
1083      * any characters originally above that position and increasing the length
1084      * of this sequence by the length of the argument s.
1085      * <p>
1086      * The result of this method is exactly the same as if it were an
1087      * invocation of this object's
1088      * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length())
1089      * method.
1090      *
1091      * <p>If {@code s} is {@code null}, then the four characters
1092      * {@code "null"} are inserted into this sequence.
1093      *
1094      * @param      dstOffset   the offset.
1095      * @param      s the sequence to be inserted
1096      * @return     a reference to this object.
1097      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1098      */
insert(int dstOffset, CharSequence s)1099     public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
1100         if (s == null)
1101             s = "null";
1102         if (s instanceof String)
1103             return this.insert(dstOffset, (String)s);
1104         return this.insert(dstOffset, s, 0, s.length());
1105     }
1106 
1107     /**
1108      * Inserts a subsequence of the specified {@code CharSequence} into
1109      * this sequence.
1110      * <p>
1111      * The subsequence of the argument {@code s} specified by
1112      * {@code start} and {@code end} are inserted,
1113      * in order, into this sequence at the specified destination offset, moving
1114      * up any characters originally above that position. The length of this
1115      * sequence is increased by {@code end - start}.
1116      * <p>
1117      * The character at index <i>k</i> in this sequence becomes equal to:
1118      * <ul>
1119      * <li>the character at index <i>k</i> in this sequence, if
1120      * <i>k</i> is less than {@code dstOffset}
1121      * <li>the character at index <i>k</i>{@code +start-dstOffset} in
1122      * the argument {@code s}, if <i>k</i> is greater than or equal to
1123      * {@code dstOffset} but is less than {@code dstOffset+end-start}
1124      * <li>the character at index <i>k</i>{@code -(end-start)} in this
1125      * sequence, if <i>k</i> is greater than or equal to
1126      * {@code dstOffset+end-start}
1127      * </ul><p>
1128      * The {@code dstOffset} argument must be greater than or equal to
1129      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1130      * of this sequence.
1131      * <p>The start argument must be nonnegative, and not greater than
1132      * {@code end}.
1133      * <p>The end argument must be greater than or equal to
1134      * {@code start}, and less than or equal to the length of s.
1135      *
1136      * <p>If {@code s} is {@code null}, then this method inserts
1137      * characters as if the s parameter was a sequence containing the four
1138      * characters {@code "null"}.
1139      *
1140      * @param      dstOffset   the offset in this sequence.
1141      * @param      s       the sequence to be inserted.
1142      * @param      start   the starting index of the subsequence to be inserted.
1143      * @param      end     the end index of the subsequence to be inserted.
1144      * @return     a reference to this object.
1145      * @throws     IndexOutOfBoundsException  if {@code dstOffset}
1146      *             is negative or greater than {@code this.length()}, or
1147      *              {@code start} or {@code end} are negative, or
1148      *              {@code start} is greater than {@code end} or
1149      *              {@code end} is greater than {@code s.length()}
1150      */
insert(int dstOffset, CharSequence s, int start, int end)1151      public AbstractStringBuilder insert(int dstOffset, CharSequence s,
1152                                          int start, int end) {
1153         if (s == null)
1154             s = "null";
1155         if ((dstOffset < 0) || (dstOffset > this.length()))
1156             throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
1157         if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
1158             throw new IndexOutOfBoundsException(
1159                 "start " + start + ", end " + end + ", s.length() "
1160                 + s.length());
1161         int len = end - start;
1162         ensureCapacityInternal(count + len);
1163         System.arraycopy(value, dstOffset, value, dstOffset + len,
1164                          count - dstOffset);
1165         for (int i=start; i<end; i++)
1166             value[dstOffset++] = s.charAt(i);
1167         count += len;
1168         return this;
1169     }
1170 
1171     /**
1172      * Inserts the string representation of the {@code boolean}
1173      * argument into this sequence.
1174      * <p>
1175      * The overall effect is exactly as if the second argument were
1176      * converted to a string by the method {@link String#valueOf(boolean)},
1177      * and the characters of that string were then
1178      * {@link #insert(int,String) inserted} into this character
1179      * sequence at the indicated offset.
1180      * <p>
1181      * The {@code offset} argument must be greater than or equal to
1182      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1183      * of this sequence.
1184      *
1185      * @param      offset   the offset.
1186      * @param      b        a {@code boolean}.
1187      * @return     a reference to this object.
1188      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1189      */
insert(int offset, boolean b)1190     public AbstractStringBuilder insert(int offset, boolean b) {
1191         return insert(offset, String.valueOf(b));
1192     }
1193 
1194     /**
1195      * Inserts the string representation of the {@code char}
1196      * argument into this sequence.
1197      * <p>
1198      * The overall effect is exactly as if the second argument were
1199      * converted to a string by the method {@link String#valueOf(char)},
1200      * and the character in that string were then
1201      * {@link #insert(int,String) inserted} into this character
1202      * sequence at the indicated offset.
1203      * <p>
1204      * The {@code offset} argument must be greater than or equal to
1205      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1206      * of this sequence.
1207      *
1208      * @param      offset   the offset.
1209      * @param      c        a {@code char}.
1210      * @return     a reference to this object.
1211      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1212      */
insert(int offset, char c)1213     public AbstractStringBuilder insert(int offset, char c) {
1214         ensureCapacityInternal(count + 1);
1215         System.arraycopy(value, offset, value, offset + 1, count - offset);
1216         value[offset] = c;
1217         count += 1;
1218         return this;
1219     }
1220 
1221     /**
1222      * Inserts the string representation of the second {@code int}
1223      * argument into this sequence.
1224      * <p>
1225      * The overall effect is exactly as if the second argument were
1226      * converted to a string by the method {@link String#valueOf(int)},
1227      * and the characters of that string were then
1228      * {@link #insert(int,String) inserted} into this character
1229      * sequence at the indicated offset.
1230      * <p>
1231      * The {@code offset} argument must be greater than or equal to
1232      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1233      * of this sequence.
1234      *
1235      * @param      offset   the offset.
1236      * @param      i        an {@code int}.
1237      * @return     a reference to this object.
1238      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1239      */
insert(int offset, int i)1240     public AbstractStringBuilder insert(int offset, int i) {
1241         return insert(offset, String.valueOf(i));
1242     }
1243 
1244     /**
1245      * Inserts the string representation of the {@code long}
1246      * argument into this sequence.
1247      * <p>
1248      * The overall effect is exactly as if the second argument were
1249      * converted to a string by the method {@link String#valueOf(long)},
1250      * and the characters of that string were then
1251      * {@link #insert(int,String) inserted} into this character
1252      * sequence at the indicated offset.
1253      * <p>
1254      * The {@code offset} argument must be greater than or equal to
1255      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1256      * of this sequence.
1257      *
1258      * @param      offset   the offset.
1259      * @param      l        a {@code long}.
1260      * @return     a reference to this object.
1261      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1262      */
insert(int offset, long l)1263     public AbstractStringBuilder insert(int offset, long l) {
1264         return insert(offset, String.valueOf(l));
1265     }
1266 
1267     /**
1268      * Inserts the string representation of the {@code float}
1269      * argument into this sequence.
1270      * <p>
1271      * The overall effect is exactly as if the second argument were
1272      * converted to a string by the method {@link String#valueOf(float)},
1273      * and the characters of that string were then
1274      * {@link #insert(int,String) inserted} into this character
1275      * sequence at the indicated offset.
1276      * <p>
1277      * The {@code offset} argument must be greater than or equal to
1278      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1279      * of this sequence.
1280      *
1281      * @param      offset   the offset.
1282      * @param      f        a {@code float}.
1283      * @return     a reference to this object.
1284      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1285      */
insert(int offset, float f)1286     public AbstractStringBuilder insert(int offset, float f) {
1287         return insert(offset, String.valueOf(f));
1288     }
1289 
1290     /**
1291      * Inserts the string representation of the {@code double}
1292      * argument into this sequence.
1293      * <p>
1294      * The overall effect is exactly as if the second argument were
1295      * converted to a string by the method {@link String#valueOf(double)},
1296      * and the characters of that string were then
1297      * {@link #insert(int,String) inserted} into this character
1298      * sequence at the indicated offset.
1299      * <p>
1300      * The {@code offset} argument must be greater than or equal to
1301      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1302      * of this sequence.
1303      *
1304      * @param      offset   the offset.
1305      * @param      d        a {@code double}.
1306      * @return     a reference to this object.
1307      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1308      */
insert(int offset, double d)1309     public AbstractStringBuilder insert(int offset, double d) {
1310         return insert(offset, String.valueOf(d));
1311     }
1312 
1313     /**
1314      * Returns the index within this string of the first occurrence of the
1315      * specified substring. The integer returned is the smallest value
1316      * <i>k</i> such that:
1317      * <pre>{@code
1318      * this.toString().startsWith(str, <i>k</i>)
1319      * }</pre>
1320      * is {@code true}.
1321      *
1322      * @param   str   any string.
1323      * @return  if the string argument occurs as a substring within this
1324      *          object, then the index of the first character of the first
1325      *          such substring is returned; if it does not occur as a
1326      *          substring, {@code -1} is returned.
1327      */
indexOf(String str)1328     public int indexOf(String str) {
1329         return indexOf(str, 0);
1330     }
1331 
1332     /**
1333      * Returns the index within this string of the first occurrence of the
1334      * specified substring, starting at the specified index.  The integer
1335      * returned is the smallest value {@code k} for which:
1336      * <pre>{@code
1337      *     k >= Math.min(fromIndex, this.length()) &&
1338      *                   this.toString().startsWith(str, k)
1339      * }</pre>
1340      * If no such value of <i>k</i> exists, then -1 is returned.
1341      *
1342      * @param   str         the substring for which to search.
1343      * @param   fromIndex   the index from which to start the search.
1344      * @return  the index within this string of the first occurrence of the
1345      *          specified substring, starting at the specified index.
1346      */
indexOf(String str, int fromIndex)1347     public int indexOf(String str, int fromIndex) {
1348         return String.indexOf(value, 0, count, str, fromIndex);
1349     }
1350 
1351     /**
1352      * Returns the index within this string of the rightmost occurrence
1353      * of the specified substring.  The rightmost empty string "" is
1354      * considered to occur at the index value {@code this.length()}.
1355      * The returned index is the largest value <i>k</i> such that
1356      * <pre>{@code
1357      * this.toString().startsWith(str, k)
1358      * }</pre>
1359      * is true.
1360      *
1361      * @param   str   the substring to search for.
1362      * @return  if the string argument occurs one or more times as a substring
1363      *          within this object, then the index of the first character of
1364      *          the last such substring is returned. If it does not occur as
1365      *          a substring, {@code -1} is returned.
1366      */
lastIndexOf(String str)1367     public int lastIndexOf(String str) {
1368         return lastIndexOf(str, count);
1369     }
1370 
1371     /**
1372      * Returns the index within this string of the last occurrence of the
1373      * specified substring. The integer returned is the largest value <i>k</i>
1374      * such that:
1375      * <pre>{@code
1376      *     k <= Math.min(fromIndex, this.length()) &&
1377      *                   this.toString().startsWith(str, k)
1378      * }</pre>
1379      * If no such value of <i>k</i> exists, then -1 is returned.
1380      *
1381      * @param   str         the substring to search for.
1382      * @param   fromIndex   the index to start the search from.
1383      * @return  the index within this sequence of the last occurrence of the
1384      *          specified substring.
1385      */
lastIndexOf(String str, int fromIndex)1386     public int lastIndexOf(String str, int fromIndex) {
1387         return String.lastIndexOf(value, 0, count, str, fromIndex);
1388     }
1389 
1390     /**
1391      * Causes this character sequence to be replaced by the reverse of
1392      * the sequence. If there are any surrogate pairs included in the
1393      * sequence, these are treated as single characters for the
1394      * reverse operation. Thus, the order of the high-low surrogates
1395      * is never reversed.
1396      *
1397      * Let <i>n</i> be the character length of this character sequence
1398      * (not the length in {@code char} values) just prior to
1399      * execution of the {@code reverse} method. Then the
1400      * character at index <i>k</i> in the new character sequence is
1401      * equal to the character at index <i>n-k-1</i> in the old
1402      * character sequence.
1403      *
1404      * <p>Note that the reverse operation may result in producing
1405      * surrogate pairs that were unpaired low-surrogates and
1406      * high-surrogates before the operation. For example, reversing
1407      * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
1408      * a valid surrogate pair.
1409      *
1410      * @return  a reference to this object.
1411      */
reverse()1412     public AbstractStringBuilder reverse() {
1413         boolean hasSurrogates = false;
1414         int n = count - 1;
1415         for (int j = (n-1) >> 1; j >= 0; j--) {
1416             int k = n - j;
1417             char cj = value[j];
1418             char ck = value[k];
1419             value[j] = ck;
1420             value[k] = cj;
1421             if (Character.isSurrogate(cj) ||
1422                 Character.isSurrogate(ck)) {
1423                 hasSurrogates = true;
1424             }
1425         }
1426         if (hasSurrogates) {
1427             reverseAllValidSurrogatePairs();
1428         }
1429         return this;
1430     }
1431 
1432     /** Outlined helper method for reverse() */
reverseAllValidSurrogatePairs()1433     private void reverseAllValidSurrogatePairs() {
1434         for (int i = 0; i < count - 1; i++) {
1435             char c2 = value[i];
1436             if (Character.isLowSurrogate(c2)) {
1437                 char c1 = value[i + 1];
1438                 if (Character.isHighSurrogate(c1)) {
1439                     value[i++] = c1;
1440                     value[i] = c2;
1441                 }
1442             }
1443         }
1444     }
1445 
1446     /**
1447      * Returns a string representing the data in this sequence.
1448      * A new {@code String} object is allocated and initialized to
1449      * contain the character sequence currently represented by this
1450      * object. This {@code String} is then returned. Subsequent
1451      * changes to this sequence do not affect the contents of the
1452      * {@code String}.
1453      *
1454      * @return  a string representation of this sequence of characters.
1455      */
1456     @Override
toString()1457     public abstract String toString();
1458 
1459     /**
1460      * Needed by {@code String} for the contentEquals method.
1461      */
getValue()1462     final char[] getValue() {
1463         return value;
1464     }
1465 
1466 }
1467