src/java.base/share/classes/java/lang/AbstractStringBuilder.java

Print this page




  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 import java.util.Spliterator;
  31 import java.util.stream.IntStream;
  32 import java.util.stream.StreamSupport;
  33 






  34 /**
  35  * A mutable sequence of characters.
  36  * <p>
  37  * Implements a modifiable string. At any point in time it contains some
  38  * particular sequence of characters, but the length and content of the
  39  * sequence can be changed through certain method calls.
  40  *
  41  * <p>Unless otherwise noted, passing a {@code null} argument to a constructor
  42  * or method in this class will cause a {@link NullPointerException} to be
  43  * thrown.
  44  *
  45  * @author      Michael McCloskey
  46  * @author      Martin Buchholz
  47  * @author      Ulf Zibis
  48  * @since       1.5
  49  */
  50 abstract class AbstractStringBuilder implements Appendable, CharSequence {
  51     /**
  52      * The value is used for character storage.
  53      */
  54     char[] value;





  55 
  56     /**
  57      * The count is the number of characters used.
  58      */
  59     int count;
  60 
  61     /**
  62      * This no-arg constructor is necessary for serialization of subclasses.
  63      */
  64     AbstractStringBuilder() {
  65     }
  66 
  67     /**
  68      * Creates an AbstractStringBuilder of the specified capacity.
  69      */
  70     AbstractStringBuilder(int capacity) {
  71         value = new char[capacity];






  72     }
  73 
  74     /**
  75      * Returns the length (character count).
  76      *
  77      * @return  the length of the sequence of characters currently
  78      *          represented by this object
  79      */
  80     @Override
  81     public int length() {
  82         return count;
  83     }
  84 
  85     /**
  86      * Returns the current capacity. The capacity is the amount of storage
  87      * available for newly inserted characters, beyond which an allocation
  88      * will occur.
  89      *
  90      * @return  the current capacity
  91      */
  92     public int capacity() {
  93         return value.length;
  94     }
  95 
  96     /**
  97      * Ensures that the capacity is at least equal to the specified minimum.
  98      * If the current capacity is less than the argument, then a new internal
  99      * array is allocated with greater capacity. The new capacity is the
 100      * larger of:
 101      * <ul>
 102      * <li>The {@code minimumCapacity} argument.
 103      * <li>Twice the old capacity, plus {@code 2}.
 104      * </ul>
 105      * If the {@code minimumCapacity} argument is nonpositive, this
 106      * method takes no action and simply returns.
 107      * Note that subsequent operations on this object can reduce the
 108      * actual capacity below that requested here.
 109      *
 110      * @param   minimumCapacity   the minimum desired capacity.
 111      */
 112     public void ensureCapacity(int minimumCapacity) {
 113         if (minimumCapacity > 0)
 114             ensureCapacityInternal(minimumCapacity);
 115     }

 116 
 117     /**
 118      * This method has the same contract as ensureCapacity, but is
 119      * never synchronized.
 120      */
 121     private void ensureCapacityInternal(int minimumCapacity) {
 122         // overflow-conscious code
 123         if (minimumCapacity - value.length > 0)

 124             expandCapacity(minimumCapacity);
 125     }

 126 
 127     /**
 128      * This implements the expansion semantics of ensureCapacity with no
 129      * size check or synchronization.
 130      */
 131     void expandCapacity(int minimumCapacity) {
 132         int newCapacity = value.length * 2 + 2;
 133         if (newCapacity - minimumCapacity < 0)
 134             newCapacity = minimumCapacity;

 135         if (newCapacity < 0) {
 136             if (minimumCapacity < 0) // overflow
 137                 throw new OutOfMemoryError();

 138             newCapacity = Integer.MAX_VALUE;
 139         }
 140         value = Arrays.copyOf(value, newCapacity);




















 141     }
 142 
 143     /**
 144      * Attempts to reduce storage used for the character sequence.
 145      * If the buffer is larger than necessary to hold its current sequence of
 146      * characters, then it may be resized to become more space efficient.
 147      * Calling this method may, but is not required to, affect the value
 148      * returned by a subsequent call to the {@link #capacity()} method.
 149      */
 150     public void trimToSize() {
 151         if (count < value.length) {
 152             value = Arrays.copyOf(value, count);

 153         }
 154     }
 155 
 156     /**
 157      * Sets the length of the character sequence.
 158      * The sequence is changed to a new character sequence
 159      * whose length is specified by the argument. For every nonnegative
 160      * index <i>k</i> less than {@code newLength}, the character at
 161      * index <i>k</i> in the new character sequence is the same as the
 162      * character at index <i>k</i> in the old sequence if <i>k</i> is less
 163      * than the length of the old character sequence; otherwise, it is the
 164      * null character {@code '\u005Cu0000'}.
 165      *
 166      * In other words, if the {@code newLength} argument is less than
 167      * the current length, the length is changed to the specified length.
 168      * <p>
 169      * If the {@code newLength} argument is greater than or equal
 170      * to the current length, sufficient null characters
 171      * ({@code '\u005Cu0000'}) are appended so that
 172      * length becomes the {@code newLength} argument.
 173      * <p>
 174      * The {@code newLength} argument must be greater than or equal
 175      * to {@code 0}.
 176      *
 177      * @param      newLength   the new length
 178      * @throws     IndexOutOfBoundsException  if the
 179      *               {@code newLength} argument is negative.
 180      */
 181     public void setLength(int newLength) {
 182         if (newLength < 0)
 183             throw new StringIndexOutOfBoundsException(newLength);

 184         ensureCapacityInternal(newLength);
 185 
 186         if (count < newLength) {
 187             Arrays.fill(value, count, newLength, '\0');




 188         }
 189 
 190         count = newLength;
 191     }
 192 
 193     /**
 194      * Returns the {@code char} value in this sequence at the specified index.
 195      * The first {@code char} value is at index {@code 0}, the next at index
 196      * {@code 1}, and so on, as in array indexing.
 197      * <p>
 198      * The index argument must be greater than or equal to
 199      * {@code 0}, and less than the length of this sequence.
 200      *
 201      * <p>If the {@code char} value specified by the index is a
 202      * <a href="Character.html#unicode">surrogate</a>, the surrogate
 203      * value is returned.
 204      *
 205      * @param      index   the index of the desired {@code char} value.
 206      * @return     the {@code char} value at the specified index.
 207      * @throws     IndexOutOfBoundsException  if {@code index} is
 208      *             negative or greater than or equal to {@code length()}.
 209      */
 210     @Override
 211     public char charAt(int index) {
 212         if ((index < 0) || (index >= count))
 213             throw new StringIndexOutOfBoundsException(index);
 214         return value[index];


 215     }
 216 
 217     /**
 218      * Returns the character (Unicode code point) at the specified
 219      * index. The index refers to {@code char} values
 220      * (Unicode code units) and ranges from {@code 0} to
 221      * {@link #length()}{@code  - 1}.
 222      *
 223      * <p> If the {@code char} value specified at the given index
 224      * is in the high-surrogate range, the following index is less
 225      * than the length of this sequence, and the
 226      * {@code char} value at the following index is in the
 227      * low-surrogate range, then the supplementary code point
 228      * corresponding to this surrogate pair is returned. Otherwise,
 229      * the {@code char} value at the given index is returned.
 230      *
 231      * @param      index the index to the {@code char} values
 232      * @return     the code point value of the character at the
 233      *             {@code index}
 234      * @exception  IndexOutOfBoundsException  if the {@code index}
 235      *             argument is negative or not less than the length of this
 236      *             sequence.
 237      */
 238     public int codePointAt(int index) {
 239         if ((index < 0) || (index >= count)) {
 240             throw new StringIndexOutOfBoundsException(index);

 241         }
 242         return Character.codePointAtImpl(value, index, count);
 243     }
 244 
 245     /**
 246      * Returns the character (Unicode code point) before the specified
 247      * index. The index refers to {@code char} values
 248      * (Unicode code units) and ranges from {@code 1} to {@link
 249      * #length()}.
 250      *
 251      * <p> If the {@code char} value at {@code (index - 1)}
 252      * is in the low-surrogate range, {@code (index - 2)} is not
 253      * negative, and the {@code char} value at {@code (index -
 254      * 2)} is in the high-surrogate range, then the
 255      * supplementary code point value of the surrogate pair is
 256      * returned. If the {@code char} value at {@code index -
 257      * 1} is an unpaired low-surrogate or a high-surrogate, the
 258      * surrogate value is returned.
 259      *
 260      * @param     index the index following the code point that should be returned
 261      * @return    the Unicode code point value before the given index.
 262      * @exception IndexOutOfBoundsException if the {@code index}
 263      *            argument is less than 1 or greater than the length
 264      *            of this sequence.
 265      */
 266     public int codePointBefore(int index) {
 267         int i = index - 1;
 268         if ((i < 0) || (i >= count)) {
 269             throw new StringIndexOutOfBoundsException(index);
 270         }
 271         return Character.codePointBeforeImpl(value, index, 0);



 272     }
 273 
 274     /**
 275      * Returns the number of Unicode code points in the specified text
 276      * range of this sequence. The text range begins at the specified
 277      * {@code beginIndex} and extends to the {@code char} at
 278      * index {@code endIndex - 1}. Thus the length (in
 279      * {@code char}s) of the text range is
 280      * {@code endIndex-beginIndex}. Unpaired surrogates within
 281      * this sequence count as one code point each.
 282      *
 283      * @param beginIndex the index to the first {@code char} of
 284      * the text range.
 285      * @param endIndex the index after the last {@code char} of
 286      * the text range.
 287      * @return the number of Unicode code points in the specified text
 288      * range
 289      * @exception IndexOutOfBoundsException if the
 290      * {@code beginIndex} is negative, or {@code endIndex}
 291      * is larger than the length of this sequence, or
 292      * {@code beginIndex} is larger than {@code endIndex}.
 293      */
 294     public int codePointCount(int beginIndex, int endIndex) {
 295         if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
 296             throw new IndexOutOfBoundsException();
 297         }
 298         return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);



 299     }
 300 
 301     /**
 302      * Returns the index within this sequence that is offset from the
 303      * given {@code index} by {@code codePointOffset} code
 304      * points. Unpaired surrogates within the text range given by
 305      * {@code index} and {@code codePointOffset} count as
 306      * one code point each.
 307      *
 308      * @param index the index to be offset
 309      * @param codePointOffset the offset in code points
 310      * @return the index within this sequence
 311      * @exception IndexOutOfBoundsException if {@code index}
 312      *   is negative or larger then the length of this sequence,
 313      *   or if {@code codePointOffset} is positive and the subsequence
 314      *   starting with {@code index} has fewer than
 315      *   {@code codePointOffset} code points,
 316      *   or if {@code codePointOffset} is negative and the subsequence
 317      *   before {@code index} has fewer than the absolute value of
 318      *   {@code codePointOffset} code points.
 319      */
 320     public int offsetByCodePoints(int index, int codePointOffset) {
 321         if (index < 0 || index > count) {
 322             throw new IndexOutOfBoundsException();
 323         }
 324         return Character.offsetByCodePointsImpl(value, 0, count,
 325                                                 index, codePointOffset);
 326     }
 327 
 328     /**
 329      * Characters are copied from this sequence into the
 330      * destination character array {@code dst}. The first character to
 331      * be copied is at index {@code srcBegin}; the last character to
 332      * be copied is at index {@code srcEnd-1}. The total number of
 333      * characters to be copied is {@code srcEnd-srcBegin}. The
 334      * characters are copied into the subarray of {@code dst} starting
 335      * at index {@code dstBegin} and ending at index:
 336      * <pre>{@code
 337      * dstbegin + (srcEnd-srcBegin) - 1
 338      * }</pre>
 339      *
 340      * @param      srcBegin   start copying at this offset.
 341      * @param      srcEnd     stop copying at this offset.
 342      * @param      dst        the array to copy the data into.
 343      * @param      dstBegin   offset into {@code dst}.
 344      * @throws     IndexOutOfBoundsException  if any of the following is true:
 345      *             <ul>
 346      *             <li>{@code srcBegin} is negative
 347      *             <li>{@code dstBegin} is negative
 348      *             <li>the {@code srcBegin} argument is greater than
 349      *             the {@code srcEnd} argument.
 350      *             <li>{@code srcEnd} is greater than
 351      *             {@code this.length()}.
 352      *             <li>{@code dstBegin+srcEnd-srcBegin} is greater than
 353      *             {@code dst.length}
 354      *             </ul>
 355      */
 356     public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
 357     {
 358         if (srcBegin < 0)
 359             throw new StringIndexOutOfBoundsException(srcBegin);
 360         if ((srcEnd < 0) || (srcEnd > count))
 361             throw new StringIndexOutOfBoundsException(srcEnd);
 362         if (srcBegin > srcEnd)
 363             throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
 364         System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);

 365     }
 366 
 367     /**
 368      * The character at the specified index is set to {@code ch}. This
 369      * sequence is altered to represent a new character sequence that is
 370      * identical to the old character sequence, except that it contains the
 371      * character {@code ch} at position {@code index}.
 372      * <p>
 373      * The index argument must be greater than or equal to
 374      * {@code 0}, and less than the length of this sequence.
 375      *
 376      * @param      index   the index of the character to modify.
 377      * @param      ch      the new character.
 378      * @throws     IndexOutOfBoundsException  if {@code index} is
 379      *             negative or greater than or equal to {@code length()}.
 380      */
 381     public void setCharAt(int index, char ch) {
 382         if ((index < 0) || (index >= count))
 383             throw new StringIndexOutOfBoundsException(index);
 384         value[index] = ch;






 385     }
 386 
 387     /**
 388      * Appends the string representation of the {@code Object} argument.
 389      * <p>
 390      * The overall effect is exactly as if the argument were converted
 391      * to a string by the method {@link String#valueOf(Object)},
 392      * and the characters of that string were then
 393      * {@link #append(String) appended} to this character sequence.
 394      *
 395      * @param   obj   an {@code Object}.
 396      * @return  a reference to this object.
 397      */
 398     public AbstractStringBuilder append(Object obj) {
 399         return append(String.valueOf(obj));
 400     }
 401 
 402     /**
 403      * Appends the specified string to this character sequence.
 404      * <p>
 405      * The characters of the {@code String} argument are appended, in
 406      * order, increasing the length of this sequence by the length of the
 407      * argument. If {@code str} is {@code null}, then the four
 408      * characters {@code "null"} are appended.
 409      * <p>
 410      * Let <i>n</i> be the length of this character sequence just prior to
 411      * execution of the {@code append} method. Then the character at
 412      * index <i>k</i> in the new character sequence is equal to the character
 413      * at index <i>k</i> in the old character sequence, if <i>k</i> is less
 414      * than <i>n</i>; otherwise, it is equal to the character at index
 415      * <i>k-n</i> in the argument {@code str}.
 416      *
 417      * @param   str   a string.
 418      * @return  a reference to this object.
 419      */
 420     public AbstractStringBuilder append(String str) {
 421         if (str == null)
 422             return appendNull();

 423         int len = str.length();
 424         ensureCapacityInternal(count + len);
 425         str.getChars(0, len, value, count);
 426         count += len;
 427         return this;
 428     }
 429 
 430     // Documentation in subclasses because of synchro difference
 431     public AbstractStringBuilder append(StringBuffer sb) {
 432         if (sb == null)
 433             return appendNull();
 434         int len = sb.length();
 435         ensureCapacityInternal(count + len);
 436         sb.getChars(0, len, value, count);
 437         count += len;
 438         return this;
 439     }
 440 
 441     /**
 442      * @since 1.8
 443      */
 444     AbstractStringBuilder append(AbstractStringBuilder asb) {
 445         if (asb == null)
 446             return appendNull();

 447         int len = asb.length();
 448         ensureCapacityInternal(count + len);
 449         asb.getChars(0, len, value, count);



 450         count += len;
 451         return this;
 452     }
 453 
 454     // Documentation in subclasses because of synchro difference
 455     @Override
 456     public AbstractStringBuilder append(CharSequence s) {
 457         if (s == null)
 458             return appendNull();
 459         if (s instanceof String)

 460             return this.append((String)s);
 461         if (s instanceof AbstractStringBuilder)

 462             return this.append((AbstractStringBuilder)s);
 463 
 464         return this.append(s, 0, s.length());
 465     }
 466 
 467     private AbstractStringBuilder appendNull() {
 468         int c = count;
 469         ensureCapacityInternal(c + 4);
 470         final char[] value = this.value;
 471         value[c++] = 'n';
 472         value[c++] = 'u';
 473         value[c++] = 'l';
 474         value[c++] = 'l';
 475         count = c;








 476         return this;
 477     }
 478 
 479     /**
 480      * Appends a subsequence of the specified {@code CharSequence} to this
 481      * sequence.
 482      * <p>
 483      * Characters of the argument {@code s}, starting at
 484      * index {@code start}, are appended, in order, to the contents of
 485      * this sequence up to the (exclusive) index {@code end}. The length
 486      * of this sequence is increased by the value of {@code end - start}.
 487      * <p>
 488      * Let <i>n</i> be the length of this character sequence just prior to
 489      * execution of the {@code append} method. Then the character at
 490      * index <i>k</i> in this character sequence becomes equal to the
 491      * character at index <i>k</i> in this sequence, if <i>k</i> is less than
 492      * <i>n</i>; otherwise, it is equal to the character at index
 493      * <i>k+start-n</i> in the argument {@code s}.
 494      * <p>
 495      * If {@code s} is {@code null}, then this method appends
 496      * characters as if the s parameter was a sequence containing the four
 497      * characters {@code "null"}.
 498      *
 499      * @param   s the sequence to append.
 500      * @param   start   the starting index of the subsequence to be appended.
 501      * @param   end     the end index of the subsequence to be appended.
 502      * @return  a reference to this object.
 503      * @throws     IndexOutOfBoundsException if
 504      *             {@code start} is negative, or
 505      *             {@code start} is greater than {@code end} or
 506      *             {@code end} is greater than {@code s.length()}
 507      */
 508     @Override
 509     public AbstractStringBuilder append(CharSequence s, int start, int end) {
 510         if (s == null)
 511             s = "null";
 512         if ((start < 0) || (start > end) || (end > s.length()))
 513             throw new IndexOutOfBoundsException(
 514                 "start " + start + ", end " + end + ", s.length() "
 515                 + s.length());
 516         int len = end - start;
 517         ensureCapacityInternal(count + len);
 518         if (s instanceof String) {
 519             ((String)s).getChars(start, end, value, count);
 520         } else {
 521             for (int i = start, j = count; i < end; i++, j++)
 522                 value[j] = s.charAt(i);
 523         }
 524         count += len;
 525         return this;
 526     }
 527 
 528     /**
 529      * Appends the string representation of the {@code char} array
 530      * argument to this sequence.
 531      * <p>
 532      * The characters of the array argument are appended, in order, to
 533      * the contents of this sequence. The length of this sequence
 534      * increases by the length of the argument.
 535      * <p>
 536      * The overall effect is exactly as if the argument were converted
 537      * to a string by the method {@link String#valueOf(char[])},
 538      * and the characters of that string were then
 539      * {@link #append(String) appended} to this character sequence.
 540      *
 541      * @param   str   the characters to be appended.
 542      * @return  a reference to this object.
 543      */
 544     public AbstractStringBuilder append(char[] str) {
 545         int len = str.length;
 546         ensureCapacityInternal(count + len);
 547         System.arraycopy(str, 0, value, count, len);
 548         count += len;
 549         return this;
 550     }
 551 
 552     /**
 553      * Appends the string representation of a subarray of the
 554      * {@code char} array argument to this sequence.
 555      * <p>
 556      * Characters of the {@code char} array {@code str}, starting at
 557      * index {@code offset}, are appended, in order, to the contents
 558      * of this sequence. The length of this sequence increases
 559      * by the value of {@code len}.
 560      * <p>
 561      * The overall effect is exactly as if the arguments were converted
 562      * to a string by the method {@link String#valueOf(char[],int,int)},
 563      * and the characters of that string were then
 564      * {@link #append(String) appended} to this character sequence.
 565      *
 566      * @param   str      the characters to be appended.
 567      * @param   offset   the index of the first {@code char} to append.
 568      * @param   len      the number of {@code char}s to append.
 569      * @return  a reference to this object.
 570      * @throws IndexOutOfBoundsException
 571      *         if {@code offset < 0} or {@code len < 0}
 572      *         or {@code offset+len > str.length}
 573      */
 574     public AbstractStringBuilder append(char str[], int offset, int len) {
 575         if (len > 0)                // let arraycopy report AIOOBE for len < 0

 576             ensureCapacityInternal(count + len);
 577         System.arraycopy(str, offset, value, count, len);
 578         count += len;
 579         return this;
 580     }
 581 
 582     /**
 583      * Appends the string representation of the {@code boolean}
 584      * argument to the sequence.
 585      * <p>
 586      * The overall effect is exactly as if the argument were converted
 587      * to a string by the method {@link String#valueOf(boolean)},
 588      * and the characters of that string were then
 589      * {@link #append(String) appended} to this character sequence.
 590      *
 591      * @param   b   a {@code boolean}.
 592      * @return  a reference to this object.
 593      */
 594     public AbstractStringBuilder append(boolean b) {




 595         if (b) {
 596             ensureCapacityInternal(count + 4);
 597             value[count++] = 't';
 598             value[count++] = 'r';
 599             value[count++] = 'u';
 600             value[count++] = 'e';
 601         } else {
 602             ensureCapacityInternal(count + 5);
 603             value[count++] = 'f';
 604             value[count++] = 'a';
 605             value[count++] = 'l';
 606             value[count++] = 's';
 607             value[count++] = 'e';













 608         }


 609         return this;
 610     }
 611 
 612     /**
 613      * Appends the string representation of the {@code char}
 614      * argument to this sequence.
 615      * <p>
 616      * The argument is appended to the contents of this sequence.
 617      * The length of this sequence increases by {@code 1}.
 618      * <p>
 619      * The overall effect is exactly as if the argument were converted
 620      * to a string by the method {@link String#valueOf(char)},
 621      * and the character in that string were then
 622      * {@link #append(String) appended} to this character sequence.
 623      *
 624      * @param   c   a {@code char}.
 625      * @return  a reference to this object.
 626      */
 627     @Override
 628     public AbstractStringBuilder append(char c) {
 629         ensureCapacityInternal(count + 1);
 630         value[count++] = c;







 631         return this;
 632     }
 633 
 634     /**
 635      * Appends the string representation of the {@code int}
 636      * argument to this sequence.
 637      * <p>
 638      * The overall effect is exactly as if the argument were converted
 639      * to a string by the method {@link String#valueOf(int)},
 640      * and the characters of that string were then
 641      * {@link #append(String) appended} to this character sequence.
 642      *
 643      * @param   i   an {@code int}.
 644      * @return  a reference to this object.
 645      */
 646     public AbstractStringBuilder append(int i) {
 647         if (i == Integer.MIN_VALUE) {
 648             append("-2147483648");
 649             return this;
 650         }
 651         int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
 652                                      : Integer.stringSize(i);
 653         int spaceNeeded = count + appendedLength;
 654         ensureCapacityInternal(spaceNeeded);

 655         Integer.getChars(i, spaceNeeded, value);





 656         count = spaceNeeded;
 657         return this;
 658     }
 659 
 660     /**
 661      * Appends the string representation of the {@code long}
 662      * argument to this sequence.
 663      * <p>
 664      * The overall effect is exactly as if the argument were converted
 665      * to a string by the method {@link String#valueOf(long)},
 666      * and the characters of that string were then
 667      * {@link #append(String) appended} to this character sequence.
 668      *
 669      * @param   l   a {@code long}.
 670      * @return  a reference to this object.
 671      */
 672     public AbstractStringBuilder append(long l) {
 673         if (l == Long.MIN_VALUE) {
 674             append("-9223372036854775808");
 675             return this;
 676         }
 677         int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
 678                                      : Long.stringSize(l);
 679         int spaceNeeded = count + appendedLength;
 680         ensureCapacityInternal(spaceNeeded);

 681         Long.getChars(l, spaceNeeded, value);





 682         count = spaceNeeded;
 683         return this;
 684     }
 685 
 686     /**
 687      * Appends the string representation of the {@code float}
 688      * argument to this sequence.
 689      * <p>
 690      * The overall effect is exactly as if the argument were converted
 691      * to a string by the method {@link String#valueOf(float)},
 692      * and the characters of that string were then
 693      * {@link #append(String) appended} to this character sequence.
 694      *
 695      * @param   f   a {@code float}.
 696      * @return  a reference to this object.
 697      */
 698     public AbstractStringBuilder append(float f) {
 699         FloatingDecimal.appendTo(f,this);
 700         return this;
 701     }


 715     public AbstractStringBuilder append(double d) {
 716         FloatingDecimal.appendTo(d,this);
 717         return this;
 718     }
 719 
 720     /**
 721      * Removes the characters in a substring of this sequence.
 722      * The substring begins at the specified {@code start} and extends to
 723      * the character at index {@code end - 1} or to the end of the
 724      * sequence if no such character exists. If
 725      * {@code start} is equal to {@code end}, no changes are made.
 726      *
 727      * @param      start  The beginning index, inclusive.
 728      * @param      end    The ending index, exclusive.
 729      * @return     This object.
 730      * @throws     StringIndexOutOfBoundsException  if {@code start}
 731      *             is negative, greater than {@code length()}, or
 732      *             greater than {@code end}.
 733      */
 734     public AbstractStringBuilder delete(int start, int end) {
 735         if (start < 0)
 736             throw new StringIndexOutOfBoundsException(start);
 737         if (end > count)
 738             end = count;
 739         if (start > end)
 740             throw new StringIndexOutOfBoundsException();
 741         int len = end - start;
 742         if (len > 0) {
 743             System.arraycopy(value, start+len, value, start, count-end);
 744             count -= len;
 745         }
 746         return this;
 747     }
 748 
 749     /**
 750      * Appends the string representation of the {@code codePoint}
 751      * argument to this sequence.
 752      *
 753      * <p> The argument is appended to the contents of this sequence.
 754      * The length of this sequence increases by
 755      * {@link Character#charCount(int) Character.charCount(codePoint)}.
 756      *
 757      * <p> The overall effect is exactly as if the argument were
 758      * converted to a {@code char} array by the method
 759      * {@link Character#toChars(int)} and the character in that array
 760      * were then {@link #append(char[]) appended} to this character
 761      * sequence.
 762      *
 763      * @param   codePoint   a Unicode code point
 764      * @return  a reference to this object.
 765      * @exception IllegalArgumentException if the specified
 766      * {@code codePoint} isn't a valid Unicode code point
 767      */
 768     public AbstractStringBuilder appendCodePoint(int codePoint) {
 769         final int count = this.count;
 770 
 771         if (Character.isBmpCodePoint(codePoint)) {
 772             ensureCapacityInternal(count + 1);
 773             value[count] = (char) codePoint;
 774             this.count = count + 1;
 775         } else if (Character.isValidCodePoint(codePoint)) {
 776             ensureCapacityInternal(count + 2);
 777             Character.toSurrogates(codePoint, value, count);
 778             this.count = count + 2;
 779         } else {
 780             throw new IllegalArgumentException();
 781         }
 782         return this;
 783     }
 784 
 785     /**
 786      * Removes the {@code char} at the specified position in this
 787      * sequence. This sequence is shortened by one {@code char}.
 788      *
 789      * <p>Note: If the character at the given index is a supplementary
 790      * character, this method does not remove the entire character. If
 791      * correct handling of supplementary characters is required,
 792      * determine the number of {@code char}s to remove by calling
 793      * {@code Character.charCount(thisSequence.codePointAt(index))},
 794      * where {@code thisSequence} is this sequence.
 795      *
 796      * @param       index  Index of {@code char} to remove
 797      * @return      This object.
 798      * @throws      StringIndexOutOfBoundsException  if the {@code index}
 799      *              is negative or greater than or equal to
 800      *              {@code length()}.
 801      */
 802     public AbstractStringBuilder deleteCharAt(int index) {
 803         if ((index < 0) || (index >= count))
 804             throw new StringIndexOutOfBoundsException(index);
 805         System.arraycopy(value, index+1, value, index, count-index-1);
 806         count--;
 807         return this;
 808     }
 809 
 810     /**
 811      * Replaces the characters in a substring of this sequence
 812      * with characters in the specified {@code String}. The substring
 813      * begins at the specified {@code start} and extends to the character
 814      * at index {@code end - 1} or to the end of the
 815      * sequence if no such character exists. First the
 816      * characters in the substring are removed and then the specified
 817      * {@code String} is inserted at {@code start}. (This
 818      * sequence will be lengthened to accommodate the
 819      * specified String if necessary.)
 820      *
 821      * @param      start    The beginning index, inclusive.
 822      * @param      end      The ending index, exclusive.
 823      * @param      str   String that will replace previous contents.
 824      * @return     This object.
 825      * @throws     StringIndexOutOfBoundsException  if {@code start}
 826      *             is negative, greater than {@code length()}, or
 827      *             greater than {@code end}.
 828      */
 829     public AbstractStringBuilder replace(int start, int end, String str) {
 830         if (start < 0)
 831             throw new StringIndexOutOfBoundsException(start);
 832         if (start > count)
 833             throw new StringIndexOutOfBoundsException("start > length()");
 834         if (start > end)
 835             throw new StringIndexOutOfBoundsException("start > end");
 836 
 837         if (end > count)
 838             end = count;


 839         int len = str.length();
 840         int newCount = count + len - (end - start);
 841         ensureCapacityInternal(newCount);
 842 
 843         System.arraycopy(value, end, value, start + len, count - end);
 844         str.getChars(value, start);
 845         count = newCount;

 846         return this;
 847     }
 848 
 849     /**
 850      * Returns a new {@code String} that contains a subsequence of
 851      * characters currently contained in this character sequence. The
 852      * substring begins at the specified index and extends to the end of
 853      * this sequence.
 854      *
 855      * @param      start    The beginning index, inclusive.
 856      * @return     The new string.
 857      * @throws     StringIndexOutOfBoundsException  if {@code start} is
 858      *             less than zero, or greater than the length of this object.
 859      */
 860     public String substring(int start) {
 861         return substring(start, count);
 862     }
 863 
 864     /**
 865      * Returns a new character sequence that is a subsequence of this sequence.


 890     @Override
 891     public CharSequence subSequence(int start, int end) {
 892         return substring(start, end);
 893     }
 894 
 895     /**
 896      * Returns a new {@code String} that contains a subsequence of
 897      * characters currently contained in this sequence. The
 898      * substring begins at the specified {@code start} and
 899      * extends to the character at index {@code end - 1}.
 900      *
 901      * @param      start    The beginning index, inclusive.
 902      * @param      end      The ending index, exclusive.
 903      * @return     The new string.
 904      * @throws     StringIndexOutOfBoundsException  if {@code start}
 905      *             or {@code end} are negative or greater than
 906      *             {@code length()}, or {@code start} is
 907      *             greater than {@code end}.
 908      */
 909     public String substring(int start, int end) {
 910         if (start < 0)
 911             throw new StringIndexOutOfBoundsException(start);
 912         if (end > count)
 913             throw new StringIndexOutOfBoundsException(end);
 914         if (start > end)
 915             throw new StringIndexOutOfBoundsException(end - start);
 916         return new String(value, start, end - start);



 917     }
 918 
 919     /**
 920      * Inserts the string representation of a subarray of the {@code str}
 921      * array argument into this sequence. The subarray begins at the
 922      * specified {@code offset} and extends {@code len} {@code char}s.
 923      * The characters of the subarray are inserted into this sequence at
 924      * the position indicated by {@code index}. The length of this
 925      * sequence increases by {@code len} {@code char}s.
 926      *
 927      * @param      index    position at which to insert subarray.
 928      * @param      str       A {@code char} array.
 929      * @param      offset   the index of the first {@code char} in subarray to
 930      *             be inserted.
 931      * @param      len      the number of {@code char}s in the subarray to
 932      *             be inserted.
 933      * @return     This object
 934      * @throws     StringIndexOutOfBoundsException  if {@code index}
 935      *             is negative or greater than {@code length()}, or
 936      *             {@code offset} or {@code len} are negative, or
 937      *             {@code (offset+len)} is greater than
 938      *             {@code str.length}.
 939      */
 940     public AbstractStringBuilder insert(int index, char[] str, int offset,
 941                                         int len)
 942     {
 943         if ((index < 0) || (index > length()))
 944             throw new StringIndexOutOfBoundsException(index);
 945         if ((offset < 0) || (len < 0) || (offset > str.length - len))
 946             throw new StringIndexOutOfBoundsException(
 947                 "offset " + offset + ", len " + len + ", str.length "
 948                 + str.length);
 949         ensureCapacityInternal(count + len);
 950         System.arraycopy(value, index, value, index + len, count - index);
 951         System.arraycopy(str, offset, value, index, len);
 952         count += len;

 953         return this;
 954     }
 955 
 956     /**
 957      * Inserts the string representation of the {@code Object}
 958      * argument into this character sequence.
 959      * <p>
 960      * The overall effect is exactly as if the second argument were
 961      * converted to a string by the method {@link String#valueOf(Object)},
 962      * and the characters of that string were then
 963      * {@link #insert(int,String) inserted} into this character
 964      * sequence at the indicated offset.
 965      * <p>
 966      * The {@code offset} argument must be greater than or equal to
 967      * {@code 0}, and less than or equal to the {@linkplain #length() length}
 968      * of this sequence.
 969      *
 970      * @param      offset   the offset.
 971      * @param      obj      an {@code Object}.
 972      * @return     a reference to this object.


 991      * <ul>
 992      * <li>the character at index <i>k</i> in the old character sequence, if
 993      * <i>k</i> is less than {@code offset}
 994      * <li>the character at index <i>k</i>{@code -offset} in the
 995      * argument {@code str}, if <i>k</i> is not less than
 996      * {@code offset} but is less than {@code offset+str.length()}
 997      * <li>the character at index <i>k</i>{@code -str.length()} in the
 998      * old character sequence, if <i>k</i> is not less than
 999      * {@code offset+str.length()}
1000      * </ul><p>
1001      * The {@code offset} argument must be greater than or equal to
1002      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1003      * of this sequence.
1004      *
1005      * @param      offset   the offset.
1006      * @param      str      a string.
1007      * @return     a reference to this object.
1008      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1009      */
1010     public AbstractStringBuilder insert(int offset, String str) {
1011         if ((offset < 0) || (offset > length()))
1012             throw new StringIndexOutOfBoundsException(offset);
1013         if (str == null)
1014             str = "null";

1015         int len = str.length();
1016         ensureCapacityInternal(count + len);
1017         System.arraycopy(value, offset, value, offset + len, count - offset);
1018         str.getChars(value, offset);
1019         count += len;

1020         return this;
1021     }
1022 
1023     /**
1024      * Inserts the string representation of the {@code char} array
1025      * argument into this sequence.
1026      * <p>
1027      * The characters of the array argument are inserted into the
1028      * contents of this sequence at the position indicated by
1029      * {@code offset}. The length of this sequence increases by
1030      * the length of the argument.
1031      * <p>
1032      * The overall effect is exactly as if the second argument were
1033      * converted to a string by the method {@link String#valueOf(char[])},
1034      * and the characters of that string were then
1035      * {@link #insert(int,String) inserted} into this character
1036      * sequence at the indicated offset.
1037      * <p>
1038      * The {@code offset} argument must be greater than or equal to
1039      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1040      * of this sequence.
1041      *
1042      * @param      offset   the offset.
1043      * @param      str      a character array.
1044      * @return     a reference to this object.
1045      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1046      */
1047     public AbstractStringBuilder insert(int offset, char[] str) {
1048         if ((offset < 0) || (offset > length()))
1049             throw new StringIndexOutOfBoundsException(offset);
1050         int len = str.length;
1051         ensureCapacityInternal(count + len);
1052         System.arraycopy(value, offset, value, offset + len, count - offset);
1053         System.arraycopy(str, 0, value, offset, len);
1054         count += len;

1055         return this;
1056     }
1057 
1058     /**
1059      * Inserts the specified {@code CharSequence} into this sequence.
1060      * <p>
1061      * The characters of the {@code CharSequence} argument are inserted,
1062      * in order, into this sequence at the indicated offset, moving up
1063      * any characters originally above that position and increasing the length
1064      * of this sequence by the length of the argument s.
1065      * <p>
1066      * The result of this method is exactly the same as if it were an
1067      * invocation of this object's
1068      * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length())
1069      * method.
1070      *
1071      * <p>If {@code s} is {@code null}, then the four characters
1072      * {@code "null"} are inserted into this sequence.
1073      *
1074      * @param      dstOffset   the offset.
1075      * @param      s the sequence to be inserted
1076      * @return     a reference to this object.
1077      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1078      */
1079     public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
1080         if (s == null)
1081             s = "null";
1082         if (s instanceof String)

1083             return this.insert(dstOffset, (String)s);

1084         return this.insert(dstOffset, s, 0, s.length());
1085     }
1086 
1087     /**
1088      * Inserts a subsequence of the specified {@code CharSequence} into
1089      * this sequence.
1090      * <p>
1091      * The subsequence of the argument {@code s} specified by
1092      * {@code start} and {@code end} are inserted,
1093      * in order, into this sequence at the specified destination offset, moving
1094      * up any characters originally above that position. The length of this
1095      * sequence is increased by {@code end - start}.
1096      * <p>
1097      * The character at index <i>k</i> in this sequence becomes equal to:
1098      * <ul>
1099      * <li>the character at index <i>k</i> in this sequence, if
1100      * <i>k</i> is less than {@code dstOffset}
1101      * <li>the character at index <i>k</i>{@code +start-dstOffset} in
1102      * the argument {@code s}, if <i>k</i> is greater than or equal to
1103      * {@code dstOffset} but is less than {@code dstOffset+end-start}


1112      * {@code end}.
1113      * <p>The end argument must be greater than or equal to
1114      * {@code start}, and less than or equal to the length of s.
1115      *
1116      * <p>If {@code s} is {@code null}, then this method inserts
1117      * characters as if the s parameter was a sequence containing the four
1118      * characters {@code "null"}.
1119      *
1120      * @param      dstOffset   the offset in this sequence.
1121      * @param      s       the sequence to be inserted.
1122      * @param      start   the starting index of the subsequence to be inserted.
1123      * @param      end     the end index of the subsequence to be inserted.
1124      * @return     a reference to this object.
1125      * @throws     IndexOutOfBoundsException  if {@code dstOffset}
1126      *             is negative or greater than {@code this.length()}, or
1127      *              {@code start} or {@code end} are negative, or
1128      *              {@code start} is greater than {@code end} or
1129      *              {@code end} is greater than {@code s.length()}
1130      */
1131      public AbstractStringBuilder insert(int dstOffset, CharSequence s,
1132                                          int start, int end) {
1133         if (s == null)

1134             s = "null";
1135         if ((dstOffset < 0) || (dstOffset > this.length()))
1136             throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
1137         if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
1138             throw new IndexOutOfBoundsException(
1139                 "start " + start + ", end " + end + ", s.length() "
1140                 + s.length());
1141         int len = end - start;
1142         ensureCapacityInternal(count + len);
1143         System.arraycopy(value, dstOffset, value, dstOffset + len,
1144                          count - dstOffset);
1145         for (int i=start; i<end; i++)
1146             value[dstOffset++] = s.charAt(i);
1147         count += len;

1148         return this;
1149     }
1150 
1151     /**
1152      * Inserts the string representation of the {@code boolean}
1153      * argument into this sequence.
1154      * <p>
1155      * The overall effect is exactly as if the second argument were
1156      * converted to a string by the method {@link String#valueOf(boolean)},
1157      * and the characters of that string were then
1158      * {@link #insert(int,String) inserted} into this character
1159      * sequence at the indicated offset.
1160      * <p>
1161      * The {@code offset} argument must be greater than or equal to
1162      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1163      * of this sequence.
1164      *
1165      * @param      offset   the offset.
1166      * @param      b        a {@code boolean}.
1167      * @return     a reference to this object.


1174     /**
1175      * Inserts the string representation of the {@code char}
1176      * argument into this sequence.
1177      * <p>
1178      * The overall effect is exactly as if the second argument were
1179      * converted to a string by the method {@link String#valueOf(char)},
1180      * and the character in that string were then
1181      * {@link #insert(int,String) inserted} into this character
1182      * sequence at the indicated offset.
1183      * <p>
1184      * The {@code offset} argument must be greater than or equal to
1185      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1186      * of this sequence.
1187      *
1188      * @param      offset   the offset.
1189      * @param      c        a {@code char}.
1190      * @return     a reference to this object.
1191      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1192      */
1193     public AbstractStringBuilder insert(int offset, char c) {

1194         ensureCapacityInternal(count + 1);
1195         System.arraycopy(value, offset, value, offset + 1, count - offset);
1196         value[offset] = c;
1197         count += 1;








1198         return this;
1199     }
1200 
1201     /**
1202      * Inserts the string representation of the second {@code int}
1203      * argument into this sequence.
1204      * <p>
1205      * The overall effect is exactly as if the second argument were
1206      * converted to a string by the method {@link String#valueOf(int)},
1207      * and the characters of that string were then
1208      * {@link #insert(int,String) inserted} into this character
1209      * sequence at the indicated offset.
1210      * <p>
1211      * The {@code offset} argument must be greater than or equal to
1212      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1213      * of this sequence.
1214      *
1215      * @param      offset   the offset.
1216      * @param      i        an {@code int}.
1217      * @return     a reference to this object.


1309     }
1310 
1311     /**
1312      * Returns the index within this string of the first occurrence of the
1313      * specified substring, starting at the specified index.
1314      *
1315      * <p>The returned index is the smallest value {@code k} for which:
1316      * <pre>{@code
1317      *     k >= Math.min(fromIndex, this.length()) &&
1318      *                   this.toString().startsWith(str, k)
1319      * }</pre>
1320      * If no such value of {@code k} exists, then {@code -1} is returned.
1321      *
1322      * @param   str         the substring to search for.
1323      * @param   fromIndex   the index from which to start the search.
1324      * @return  the index of the first occurrence of the specified substring,
1325      *          starting at the specified index,
1326      *          or {@code -1} if there is no such occurrence.
1327      */
1328     public int indexOf(String str, int fromIndex) {
1329         return String.indexOf(value, 0, count, str, fromIndex);
1330     }
1331 
1332     /**
1333      * Returns the index within this string of the last occurrence of the
1334      * specified substring.  The last occurrence of the empty string "" is
1335      * considered to occur at the index value {@code this.length()}.
1336      *
1337      * <p>The returned index is the largest value {@code k} for which:
1338      * <pre>{@code
1339      * this.toString().startsWith(str, k)
1340      * }</pre>
1341      * If no such value of {@code k} exists, then {@code -1} is returned.
1342      *
1343      * @param   str   the substring to search for.
1344      * @return  the index of the last occurrence of the specified substring,
1345      *          or {@code -1} if there is no such occurrence.
1346      */
1347     public int lastIndexOf(String str) {
1348         return lastIndexOf(str, count);
1349     }
1350 
1351     /**
1352      * Returns the index within this string of the last occurrence of the
1353      * specified substring, searching backward starting at the specified index.
1354      *
1355      * <p>The returned index is the largest value {@code k} for which:
1356      * <pre>{@code
1357      *     k <= Math.min(fromIndex, this.length()) &&
1358      *                   this.toString().startsWith(str, k)
1359      * }</pre>
1360      * If no such value of {@code k} exists, then {@code -1} is returned.
1361      *
1362      * @param   str         the substring to search for.
1363      * @param   fromIndex   the index to start the search from.
1364      * @return  the index of the last occurrence of the specified substring,
1365      *          searching backward from the specified index,
1366      *          or {@code -1} if there is no such occurrence.
1367      */
1368     public int lastIndexOf(String str, int fromIndex) {
1369         return String.lastIndexOf(value, 0, count, str, fromIndex);
1370     }
1371 
1372     /**
1373      * Causes this character sequence to be replaced by the reverse of
1374      * the sequence. If there are any surrogate pairs included in the
1375      * sequence, these are treated as single characters for the
1376      * reverse operation. Thus, the order of the high-low surrogates
1377      * is never reversed.
1378      *
1379      * Let <i>n</i> be the character length of this character sequence
1380      * (not the length in {@code char} values) just prior to
1381      * execution of the {@code reverse} method. Then the
1382      * character at index <i>k</i> in the new character sequence is
1383      * equal to the character at index <i>n-k-1</i> in the old
1384      * character sequence.
1385      *
1386      * <p>Note that the reverse operation may result in producing
1387      * surrogate pairs that were unpaired low-surrogates and
1388      * high-surrogates before the operation. For example, reversing
1389      * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
1390      * a valid surrogate pair.
1391      *
1392      * @return  a reference to this object.
1393      */
1394     public AbstractStringBuilder reverse() {
1395         boolean hasSurrogates = false;


1396         int n = count - 1;

1397         for (int j = (n-1) >> 1; j >= 0; j--) {
1398             int k = n - j;
1399             char cj = value[j];
1400             char ck = value[k];
1401             value[j] = ck;
1402             value[k] = cj;









1403             if (Character.isSurrogate(cj) ||
1404                 Character.isSurrogate(ck)) {
1405                 hasSurrogates = true;
1406             }
1407         }
1408         if (hasSurrogates) {
1409             reverseAllValidSurrogatePairs();

1410         }
1411         return this;
1412     }
1413 
1414     /** Outlined helper method for reverse() */
1415     private void reverseAllValidSurrogatePairs() {
1416         for (int i = 0; i < count - 1; i++) {
1417             char c2 = value[i];
1418             if (Character.isLowSurrogate(c2)) {
1419                 char c1 = value[i + 1];
1420                 if (Character.isHighSurrogate(c1)) {
1421                     value[i++] = c1;
1422                     value[i] = c2;
1423                 }
1424             }
1425         }
1426     }
1427 
1428     /**
1429      * Returns a string representing the data in this sequence.
1430      * A new {@code String} object is allocated and initialized to
1431      * contain the character sequence currently represented by this
1432      * object. This {@code String} is then returned. Subsequent
1433      * changes to this sequence do not affect the contents of the
1434      * {@code String}.
1435      *
1436      * @return  a string representation of this sequence of characters.
1437      */
1438     @Override
1439     public abstract String toString();
1440 
1441     /**
1442      * {@inheritDoc}
1443      * @since 1.9
1444      */
1445     @Override
1446     public IntStream chars() {


1447         // Reuse String-based spliterator. This requires a supplier to
1448         // capture the value and count when the terminal operation is executed
1449         return StreamSupport.intStream(
1450                 () -> new String.IntCharArraySpliterator(value, 0, count, 0),

1451                 Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED,
1452                 false);
1453     }
1454 
1455     /**
1456      * {@inheritDoc}
1457      * @since 1.9
1458      */
1459     @Override
1460     public IntStream codePoints() {


1461         // Reuse String-based spliterator. This requires a supplier to
1462         // capture the value and count when the terminal operation is executed
1463         return StreamSupport.intStream(
1464                 () -> new String.CodePointsSpliterator(value, 0, count, 0),

1465                 Spliterator.ORDERED,
1466                 false);
1467     }
1468 
1469     /**
1470      * Needed by {@code String} for the contentEquals method.
1471      */
1472     final char[] getValue() {
1473         return value;
1474     }
1475 











































































































































1476 }


  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 import java.util.Spliterator;
  31 import java.util.stream.IntStream;
  32 import java.util.stream.StreamSupport;
  33 
  34 import static java.lang.String.COMPACT_STRINGS;
  35 import static java.lang.String.UTF16;
  36 import static java.lang.String.LATIN1;
  37 import static java.lang.String.checkIndex;
  38 import static java.lang.String.checkOffset;
  39 
  40 /**
  41  * A mutable sequence of characters.
  42  * <p>
  43  * Implements a modifiable string. At any point in time it contains some
  44  * particular sequence of characters, but the length and content of the
  45  * sequence can be changed through certain method calls.
  46  *
  47  * <p>Unless otherwise noted, passing a {@code null} argument to a constructor
  48  * or method in this class will cause a {@link NullPointerException} to be
  49  * thrown.
  50  *
  51  * @author      Michael McCloskey
  52  * @author      Martin Buchholz
  53  * @author      Ulf Zibis
  54  * @since       1.5
  55  */
  56 abstract class AbstractStringBuilder implements Appendable, CharSequence {
  57     /**
  58      * The value is used for character storage.
  59      */
  60     byte[] value;
  61 
  62     /**
  63      * The id of the encoding used to encode the bytes in {@code value}.
  64      */
  65     byte coder;
  66 
  67     /**
  68      * The count is the number of characters used.
  69      */
  70     int count;
  71 
  72     /**
  73      * This no-arg constructor is necessary for serialization of subclasses.
  74      */
  75     AbstractStringBuilder() {
  76     }
  77 
  78     /**
  79      * Creates an AbstractStringBuilder of the specified capacity.
  80      */
  81     AbstractStringBuilder(int capacity) {
  82         if (COMPACT_STRINGS) {
  83             value = new byte[capacity];
  84             coder = LATIN1;
  85         } else {
  86             value = StringUTF16.newBytesFor(capacity);
  87             coder = UTF16;
  88         }
  89     }
  90 
  91     /**
  92      * Returns the length (character count).
  93      *
  94      * @return  the length of the sequence of characters currently
  95      *          represented by this object
  96      */
  97     @Override
  98     public int length() {
  99         return count;
 100     }
 101 
 102     /**
 103      * Returns the current capacity. The capacity is the amount of storage
 104      * available for newly inserted characters, beyond which an allocation
 105      * will occur.
 106      *
 107      * @return  the current capacity
 108      */
 109     public int capacity() {
 110         return value.length >> coder;
 111     }
 112 
 113     /**
 114      * Ensures that the capacity is at least equal to the specified minimum.
 115      * If the current capacity is less than the argument, then a new internal
 116      * array is allocated with greater capacity. The new capacity is the
 117      * larger of:
 118      * <ul>
 119      * <li>The {@code minimumCapacity} argument.
 120      * <li>Twice the old capacity, plus {@code 2}.
 121      * </ul>
 122      * If the {@code minimumCapacity} argument is nonpositive, this
 123      * method takes no action and simply returns.
 124      * Note that subsequent operations on this object can reduce the
 125      * actual capacity below that requested here.
 126      *
 127      * @param   minimumCapacity   the minimum desired capacity.
 128      */
 129     public void ensureCapacity(int minimumCapacity) {
 130         if (minimumCapacity > 0) {
 131             ensureCapacityInternal(minimumCapacity);
 132         }
 133     }
 134 
 135     /**
 136      * This method has the same contract as ensureCapacity, but is
 137      * never synchronized.
 138      */
 139     private void ensureCapacityInternal(int minimumCapacity) {
 140         // overflow-conscious code
 141         int capacity = value.length >> coder;
 142         if (minimumCapacity - capacity > 0) {
 143             expandCapacity(minimumCapacity);
 144         }
 145     }
 146 
 147     /**
 148      * This implements the expansion semantics of ensureCapacity with no
 149      * size check or synchronization.
 150      */
 151     private void expandCapacity(int minimumCapacity) {
 152         int newCapacity = (value.length >> coder) * 2 + 2;
 153         if (newCapacity - minimumCapacity < 0) {
 154             newCapacity = minimumCapacity;
 155         }
 156         if (newCapacity < 0) {
 157             if (minimumCapacity < 0) {// overflow
 158                 throw new OutOfMemoryError();
 159             }
 160             newCapacity = Integer.MAX_VALUE;
 161         }
 162         if (coder != LATIN1 && newCapacity > StringUTF16.MAX_LENGTH) {
 163             if (minimumCapacity >= StringUTF16.MAX_LENGTH) {
 164                 throw new OutOfMemoryError();
 165             }
 166             newCapacity = StringUTF16.MAX_LENGTH;
 167         }
 168         this.value = Arrays.copyOf(value, newCapacity << coder);
 169     }
 170 
 171     /**
 172      * If the coder is "isLatin1", this inflates the internal 8-bit storage
 173      * to 16-bit <hi=0, low> pair storage.
 174      */
 175     private void inflate() {
 176         if (!isLatin1()) {
 177             return;
 178         }
 179         byte[] buf = StringUTF16.newBytesFor(value.length);
 180         StringLatin1.inflateSB(value, buf, 0, count);
 181         this.value = buf;
 182         this.coder = UTF16;
 183     }
 184 
 185     /**
 186      * Attempts to reduce storage used for the character sequence.
 187      * If the buffer is larger than necessary to hold its current sequence of
 188      * characters, then it may be resized to become more space efficient.
 189      * Calling this method may, but is not required to, affect the value
 190      * returned by a subsequent call to the {@link #capacity()} method.
 191      */
 192     public void trimToSize() {
 193         int length = count << coder;
 194         if (length < value.length) {
 195             value = Arrays.copyOf(value, length);
 196         }
 197     }
 198 
 199     /**
 200      * Sets the length of the character sequence.
 201      * The sequence is changed to a new character sequence
 202      * whose length is specified by the argument. For every nonnegative
 203      * index <i>k</i> less than {@code newLength}, the character at
 204      * index <i>k</i> in the new character sequence is the same as the
 205      * character at index <i>k</i> in the old sequence if <i>k</i> is less
 206      * than the length of the old character sequence; otherwise, it is the
 207      * null character {@code '\u005Cu0000'}.
 208      *
 209      * In other words, if the {@code newLength} argument is less than
 210      * the current length, the length is changed to the specified length.
 211      * <p>
 212      * If the {@code newLength} argument is greater than or equal
 213      * to the current length, sufficient null characters
 214      * ({@code '\u005Cu0000'}) are appended so that
 215      * length becomes the {@code newLength} argument.
 216      * <p>
 217      * The {@code newLength} argument must be greater than or equal
 218      * to {@code 0}.
 219      *
 220      * @param      newLength   the new length
 221      * @throws     IndexOutOfBoundsException  if the
 222      *               {@code newLength} argument is negative.
 223      */
 224     public void setLength(int newLength) {
 225         if (newLength < 0) {
 226             throw new StringIndexOutOfBoundsException(newLength);
 227         }
 228         ensureCapacityInternal(newLength);

 229         if (count < newLength) {
 230             if (isLatin1()) {
 231                 StringLatin1.fillNull(value, count, newLength);
 232             } else {
 233                 StringUTF16.fillNull(value, count, newLength);
 234             }
 235         }

 236         count = newLength;
 237     }
 238 
 239     /**
 240      * Returns the {@code char} value in this sequence at the specified index.
 241      * The first {@code char} value is at index {@code 0}, the next at index
 242      * {@code 1}, and so on, as in array indexing.
 243      * <p>
 244      * The index argument must be greater than or equal to
 245      * {@code 0}, and less than the length of this sequence.
 246      *
 247      * <p>If the {@code char} value specified by the index is a
 248      * <a href="Character.html#unicode">surrogate</a>, the surrogate
 249      * value is returned.
 250      *
 251      * @param      index   the index of the desired {@code char} value.
 252      * @return     the {@code char} value at the specified index.
 253      * @throws     IndexOutOfBoundsException  if {@code index} is
 254      *             negative or greater than or equal to {@code length()}.
 255      */
 256     @Override
 257     public char charAt(int index) {
 258         checkIndex(index, count);
 259         if (isLatin1()) {
 260             return (char)(value[index] & 0xff);
 261         }
 262         return StringUTF16.charAt(value, index);
 263     }
 264 
 265     /**
 266      * Returns the character (Unicode code point) at the specified
 267      * index. The index refers to {@code char} values
 268      * (Unicode code units) and ranges from {@code 0} to
 269      * {@link #length()}{@code  - 1}.
 270      *
 271      * <p> If the {@code char} value specified at the given index
 272      * is in the high-surrogate range, the following index is less
 273      * than the length of this sequence, and the
 274      * {@code char} value at the following index is in the
 275      * low-surrogate range, then the supplementary code point
 276      * corresponding to this surrogate pair is returned. Otherwise,
 277      * the {@code char} value at the given index is returned.
 278      *
 279      * @param      index the index to the {@code char} values
 280      * @return     the code point value of the character at the
 281      *             {@code index}
 282      * @exception  IndexOutOfBoundsException  if the {@code index}
 283      *             argument is negative or not less than the length of this
 284      *             sequence.
 285      */
 286     public int codePointAt(int index) {
 287         checkIndex(index, count);
 288         if (isLatin1()) {
 289             return value[index] & 0xff;
 290         }
 291         return StringUTF16.codePointAtSB(value, index, count);
 292     }
 293 
 294     /**
 295      * Returns the character (Unicode code point) before the specified
 296      * index. The index refers to {@code char} values
 297      * (Unicode code units) and ranges from {@code 1} to {@link
 298      * #length()}.
 299      *
 300      * <p> If the {@code char} value at {@code (index - 1)}
 301      * is in the low-surrogate range, {@code (index - 2)} is not
 302      * negative, and the {@code char} value at {@code (index -
 303      * 2)} is in the high-surrogate range, then the
 304      * supplementary code point value of the surrogate pair is
 305      * returned. If the {@code char} value at {@code index -
 306      * 1} is an unpaired low-surrogate or a high-surrogate, the
 307      * surrogate value is returned.
 308      *
 309      * @param     index the index following the code point that should be returned
 310      * @return    the Unicode code point value before the given index.
 311      * @exception IndexOutOfBoundsException if the {@code index}
 312      *            argument is less than 1 or greater than the length
 313      *            of this sequence.
 314      */
 315     public int codePointBefore(int index) {
 316         int i = index - 1;
 317         if (i < 0 || i >= count) {
 318             throw new StringIndexOutOfBoundsException(index);
 319         }
 320         if (isLatin1()) {
 321             return value[i] & 0xff;
 322         }
 323         return StringUTF16.codePointBeforeSB(value, index);
 324     }
 325 
 326     /**
 327      * Returns the number of Unicode code points in the specified text
 328      * range of this sequence. The text range begins at the specified
 329      * {@code beginIndex} and extends to the {@code char} at
 330      * index {@code endIndex - 1}. Thus the length (in
 331      * {@code char}s) of the text range is
 332      * {@code endIndex-beginIndex}. Unpaired surrogates within
 333      * this sequence count as one code point each.
 334      *
 335      * @param beginIndex the index to the first {@code char} of
 336      * the text range.
 337      * @param endIndex the index after the last {@code char} of
 338      * the text range.
 339      * @return the number of Unicode code points in the specified text
 340      * range
 341      * @exception IndexOutOfBoundsException if the
 342      * {@code beginIndex} is negative, or {@code endIndex}
 343      * is larger than the length of this sequence, or
 344      * {@code beginIndex} is larger than {@code endIndex}.
 345      */
 346     public int codePointCount(int beginIndex, int endIndex) {
 347         if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
 348             throw new IndexOutOfBoundsException();
 349         }
 350         if (isLatin1()) {
 351             return endIndex - beginIndex;
 352         }
 353         return StringUTF16.codePointCountSB(value, beginIndex, endIndex);
 354     }
 355 
 356     /**
 357      * Returns the index within this sequence that is offset from the
 358      * given {@code index} by {@code codePointOffset} code
 359      * points. Unpaired surrogates within the text range given by
 360      * {@code index} and {@code codePointOffset} count as
 361      * one code point each.
 362      *
 363      * @param index the index to be offset
 364      * @param codePointOffset the offset in code points
 365      * @return the index within this sequence
 366      * @exception IndexOutOfBoundsException if {@code index}
 367      *   is negative or larger then the length of this sequence,
 368      *   or if {@code codePointOffset} is positive and the subsequence
 369      *   starting with {@code index} has fewer than
 370      *   {@code codePointOffset} code points,
 371      *   or if {@code codePointOffset} is negative and the subsequence
 372      *   before {@code index} has fewer than the absolute value of
 373      *   {@code codePointOffset} code points.
 374      */
 375     public int offsetByCodePoints(int index, int codePointOffset) {
 376         if (index < 0 || index > count) {
 377             throw new IndexOutOfBoundsException();
 378         }
 379         return Character.offsetByCodePoints(this,
 380                                             index, codePointOffset);
 381     }
 382 
 383     /**
 384      * Characters are copied from this sequence into the
 385      * destination character array {@code dst}. The first character to
 386      * be copied is at index {@code srcBegin}; the last character to
 387      * be copied is at index {@code srcEnd-1}. The total number of
 388      * characters to be copied is {@code srcEnd-srcBegin}. The
 389      * characters are copied into the subarray of {@code dst} starting
 390      * at index {@code dstBegin} and ending at index:
 391      * <pre>{@code
 392      * dstbegin + (srcEnd-srcBegin) - 1
 393      * }</pre>
 394      *
 395      * @param      srcBegin   start copying at this offset.
 396      * @param      srcEnd     stop copying at this offset.
 397      * @param      dst        the array to copy the data into.
 398      * @param      dstBegin   offset into {@code dst}.
 399      * @throws     IndexOutOfBoundsException  if any of the following is true:
 400      *             <ul>
 401      *             <li>{@code srcBegin} is negative
 402      *             <li>{@code dstBegin} is negative
 403      *             <li>the {@code srcBegin} argument is greater than
 404      *             the {@code srcEnd} argument.
 405      *             <li>{@code srcEnd} is greater than
 406      *             {@code this.length()}.
 407      *             <li>{@code dstBegin+srcEnd-srcBegin} is greater than
 408      *             {@code dst.length}
 409      *             </ul>
 410      */
 411     public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
 412     {
 413         checkRangeSIOOBE(srcBegin, srcEnd, count);  // compatible to old version
 414         int n = srcEnd - srcBegin;
 415         checkRange(dstBegin, dstBegin + n, dst.length);
 416         if (isLatin1()) {
 417             StringLatin1.getCharsSB(value, srcBegin, srcEnd, dst, dstBegin);
 418         } else {
 419             StringUTF16.getCharsSB(value, srcBegin, srcEnd, dst, dstBegin);
 420         }
 421     }
 422 
 423     /**
 424      * The character at the specified index is set to {@code ch}. This
 425      * sequence is altered to represent a new character sequence that is
 426      * identical to the old character sequence, except that it contains the
 427      * character {@code ch} at position {@code index}.
 428      * <p>
 429      * The index argument must be greater than or equal to
 430      * {@code 0}, and less than the length of this sequence.
 431      *
 432      * @param      index   the index of the character to modify.
 433      * @param      ch      the new character.
 434      * @throws     IndexOutOfBoundsException  if {@code index} is
 435      *             negative or greater than or equal to {@code length()}.
 436      */
 437     public void setCharAt(int index, char ch) {
 438         checkIndex(index, count);
 439         if (isLatin1() && StringLatin1.canEncode(ch)) {
 440             value[index] = (byte)ch;
 441         } else {
 442             if (isLatin1()) {
 443                 inflate();
 444             }
 445             StringUTF16.putCharSB(value, index, ch);
 446         }
 447     }
 448 
 449     /**
 450      * Appends the string representation of the {@code Object} argument.
 451      * <p>
 452      * The overall effect is exactly as if the argument were converted
 453      * to a string by the method {@link String#valueOf(Object)},
 454      * and the characters of that string were then
 455      * {@link #append(String) appended} to this character sequence.
 456      *
 457      * @param   obj   an {@code Object}.
 458      * @return  a reference to this object.
 459      */
 460     public AbstractStringBuilder append(Object obj) {
 461         return append(String.valueOf(obj));
 462     }
 463 
 464     /**
 465      * Appends the specified string to this character sequence.
 466      * <p>
 467      * The characters of the {@code String} argument are appended, in
 468      * order, increasing the length of this sequence by the length of the
 469      * argument. If {@code str} is {@code null}, then the four
 470      * characters {@code "null"} are appended.
 471      * <p>
 472      * Let <i>n</i> be the length of this character sequence just prior to
 473      * execution of the {@code append} method. Then the character at
 474      * index <i>k</i> in the new character sequence is equal to the character
 475      * at index <i>k</i> in the old character sequence, if <i>k</i> is less
 476      * than <i>n</i>; otherwise, it is equal to the character at index
 477      * <i>k-n</i> in the argument {@code str}.
 478      *
 479      * @param   str   a string.
 480      * @return  a reference to this object.
 481      */
 482     public AbstractStringBuilder append(String str) {
 483         if (str == null) {
 484             return appendNull();
 485         }
 486         int len = str.length();
 487         ensureCapacityInternal(count + len);
 488         putStringAt(count, str);
 489         count += len;
 490         return this;
 491     }
 492 
 493     // Documentation in subclasses because of synchro difference
 494     public AbstractStringBuilder append(StringBuffer sb) {
 495         return this.append((AbstractStringBuilder)sb);






 496     }
 497 
 498     /**
 499      * @since 1.8
 500      */
 501     AbstractStringBuilder append(AbstractStringBuilder asb) {
 502         if (asb == null) {
 503             return appendNull();
 504         }
 505         int len = asb.length();
 506         ensureCapacityInternal(count + len);
 507         if (getCoder() != asb.getCoder()) {
 508             inflate();
 509         }
 510         asb.getBytes(value, count, coder);
 511         count += len;
 512         return this;
 513     }
 514 
 515     // Documentation in subclasses because of synchro difference
 516     @Override
 517     public AbstractStringBuilder append(CharSequence s) {
 518         if (s == null) {
 519             return appendNull();
 520         }
 521         if (s instanceof String) {
 522             return this.append((String)s);
 523         }
 524         if (s instanceof AbstractStringBuilder) {
 525             return this.append((AbstractStringBuilder)s);
 526         }
 527         return this.append(s, 0, s.length());
 528     }
 529 
 530     private AbstractStringBuilder appendNull() {
 531         ensureCapacityInternal(count + 4);
 532         int count = this.count;
 533         byte[] val = this.value;
 534         if (isLatin1()) {
 535             val[count++] = 'n';
 536             val[count++] = 'u';
 537             val[count++] = 'l';
 538             val[count++] = 'l';
 539         } else {
 540             checkOffset(count + 4, val.length >> 1);
 541             StringUTF16.putChar(val, count++, 'n');
 542             StringUTF16.putChar(val, count++, 'u');
 543             StringUTF16.putChar(val, count++, 'l');
 544             StringUTF16.putChar(val, count++, 'l');
 545         }
 546         this.count = count;
 547         return this;
 548     }
 549 
 550     /**
 551      * Appends a subsequence of the specified {@code CharSequence} to this
 552      * sequence.
 553      * <p>
 554      * Characters of the argument {@code s}, starting at
 555      * index {@code start}, are appended, in order, to the contents of
 556      * this sequence up to the (exclusive) index {@code end}. The length
 557      * of this sequence is increased by the value of {@code end - start}.
 558      * <p>
 559      * Let <i>n</i> be the length of this character sequence just prior to
 560      * execution of the {@code append} method. Then the character at
 561      * index <i>k</i> in this character sequence becomes equal to the
 562      * character at index <i>k</i> in this sequence, if <i>k</i> is less than
 563      * <i>n</i>; otherwise, it is equal to the character at index
 564      * <i>k+start-n</i> in the argument {@code s}.
 565      * <p>
 566      * If {@code s} is {@code null}, then this method appends
 567      * characters as if the s parameter was a sequence containing the four
 568      * characters {@code "null"}.
 569      *
 570      * @param   s the sequence to append.
 571      * @param   start   the starting index of the subsequence to be appended.
 572      * @param   end     the end index of the subsequence to be appended.
 573      * @return  a reference to this object.
 574      * @throws     IndexOutOfBoundsException if
 575      *             {@code start} is negative, or
 576      *             {@code start} is greater than {@code end} or
 577      *             {@code end} is greater than {@code s.length()}
 578      */
 579     @Override
 580     public AbstractStringBuilder append(CharSequence s, int start, int end) {
 581         if (s == null) {
 582             s = "null";
 583         }
 584         checkRange(start, end, s.length());


 585         int len = end - start;
 586         ensureCapacityInternal(count + len);
 587         appendChars(s, start, end);






 588         return this;
 589     }
 590 
 591     /**
 592      * Appends the string representation of the {@code char} array
 593      * argument to this sequence.
 594      * <p>
 595      * The characters of the array argument are appended, in order, to
 596      * the contents of this sequence. The length of this sequence
 597      * increases by the length of the argument.
 598      * <p>
 599      * The overall effect is exactly as if the argument were converted
 600      * to a string by the method {@link String#valueOf(char[])},
 601      * and the characters of that string were then
 602      * {@link #append(String) appended} to this character sequence.
 603      *
 604      * @param   str   the characters to be appended.
 605      * @return  a reference to this object.
 606      */
 607     public AbstractStringBuilder append(char[] str) {
 608         int len = str.length;
 609         ensureCapacityInternal(count + len);
 610         appendChars(str, 0, len);

 611         return this;
 612     }
 613 
 614     /**
 615      * Appends the string representation of a subarray of the
 616      * {@code char} array argument to this sequence.
 617      * <p>
 618      * Characters of the {@code char} array {@code str}, starting at
 619      * index {@code offset}, are appended, in order, to the contents
 620      * of this sequence. The length of this sequence increases
 621      * by the value of {@code len}.
 622      * <p>
 623      * The overall effect is exactly as if the arguments were converted
 624      * to a string by the method {@link String#valueOf(char[],int,int)},
 625      * and the characters of that string were then
 626      * {@link #append(String) appended} to this character sequence.
 627      *
 628      * @param   str      the characters to be appended.
 629      * @param   offset   the index of the first {@code char} to append.
 630      * @param   len      the number of {@code char}s to append.
 631      * @return  a reference to this object.
 632      * @throws IndexOutOfBoundsException
 633      *         if {@code offset < 0} or {@code len < 0}
 634      *         or {@code offset+len > str.length}
 635      */
 636     public AbstractStringBuilder append(char str[], int offset, int len) {
 637         int end = offset + len;
 638         checkRange(offset, end, str.length);
 639         ensureCapacityInternal(count + len);
 640         appendChars(str, offset, end);

 641         return this;
 642     }
 643 
 644     /**
 645      * Appends the string representation of the {@code boolean}
 646      * argument to the sequence.
 647      * <p>
 648      * The overall effect is exactly as if the argument were converted
 649      * to a string by the method {@link String#valueOf(boolean)},
 650      * and the characters of that string were then
 651      * {@link #append(String) appended} to this character sequence.
 652      *
 653      * @param   b   a {@code boolean}.
 654      * @return  a reference to this object.
 655      */
 656     public AbstractStringBuilder append(boolean b) {
 657         ensureCapacityInternal(count + (b ? 4 : 5));
 658         int count = this.count;
 659         byte[] val = this.value;
 660         if (isLatin1()) {
 661             if (b) {
 662                 val[count++] = 't';
 663                 val[count++] = 'r';
 664                 val[count++] = 'u';
 665                 val[count++] = 'e';
 666             } else {
 667                 val[count++] = 'f';
 668                 val[count++] = 'a';
 669                 val[count++] = 'l';
 670                 val[count++] = 's';
 671                 val[count++] = 'e';
 672             }
 673         } else {
 674             if (b) {
 675                 checkOffset(count + 4, val.length >> 1);
 676                 StringUTF16.putChar(val, count++, 't');
 677                 StringUTF16.putChar(val, count++, 'r');
 678                 StringUTF16.putChar(val, count++, 'u');
 679                 StringUTF16.putChar(val, count++, 'e');
 680             } else {
 681                 checkOffset(count + 5, val.length >> 1);
 682                 StringUTF16.putChar(val, count++, 'f');
 683                 StringUTF16.putChar(val, count++, 'a');
 684                 StringUTF16.putChar(val, count++, 'l');
 685                 StringUTF16.putChar(val, count++, 's');
 686                 StringUTF16.putChar(val, count++, 'e');
 687             }
 688         }
 689         this.count = count;
 690         return this;
 691     }
 692 
 693     /**
 694      * Appends the string representation of the {@code char}
 695      * argument to this sequence.
 696      * <p>
 697      * The argument is appended to the contents of this sequence.
 698      * The length of this sequence increases by {@code 1}.
 699      * <p>
 700      * The overall effect is exactly as if the argument were converted
 701      * to a string by the method {@link String#valueOf(char)},
 702      * and the character in that string were then
 703      * {@link #append(String) appended} to this character sequence.
 704      *
 705      * @param   c   a {@code char}.
 706      * @return  a reference to this object.
 707      */
 708     @Override
 709     public AbstractStringBuilder append(char c) {
 710         ensureCapacityInternal(count + 1);
 711         if (isLatin1() && StringLatin1.canEncode(c)) {
 712             value[count++] = (byte)c;
 713         } else {
 714             if (isLatin1()) {
 715                 inflate();
 716             }
 717             StringUTF16.putCharSB(value, count++, c);
 718         }
 719         return this;
 720     }
 721 
 722     /**
 723      * Appends the string representation of the {@code int}
 724      * argument to this sequence.
 725      * <p>
 726      * The overall effect is exactly as if the argument were converted
 727      * to a string by the method {@link String#valueOf(int)},
 728      * and the characters of that string were then
 729      * {@link #append(String) appended} to this character sequence.
 730      *
 731      * @param   i   an {@code int}.
 732      * @return  a reference to this object.
 733      */
 734     public AbstractStringBuilder append(int i) {
 735         if (i == Integer.MIN_VALUE) {
 736             append("-2147483648");
 737             return this;
 738         }
 739         int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
 740                                      : Integer.stringSize(i);
 741         int spaceNeeded = count + appendedLength;
 742         ensureCapacityInternal(spaceNeeded);
 743         if (isLatin1()) {
 744             Integer.getChars(i, spaceNeeded, value);
 745         } else {
 746             byte[] val = this.value;
 747             checkOffset(spaceNeeded, val.length >> 1);
 748             Integer.getCharsUTF16(i, spaceNeeded, val);
 749         }
 750         count = spaceNeeded;
 751         return this;
 752     }
 753 
 754     /**
 755      * Appends the string representation of the {@code long}
 756      * argument to this sequence.
 757      * <p>
 758      * The overall effect is exactly as if the argument were converted
 759      * to a string by the method {@link String#valueOf(long)},
 760      * and the characters of that string were then
 761      * {@link #append(String) appended} to this character sequence.
 762      *
 763      * @param   l   a {@code long}.
 764      * @return  a reference to this object.
 765      */
 766     public AbstractStringBuilder append(long l) {
 767         if (l == Long.MIN_VALUE) {
 768             append("-9223372036854775808");
 769             return this;
 770         }
 771         int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
 772                                      : Long.stringSize(l);
 773         int spaceNeeded = count + appendedLength;
 774         ensureCapacityInternal(spaceNeeded);
 775         if (isLatin1()) {
 776             Long.getChars(l, spaceNeeded, value);
 777         } else {
 778             byte[] val = this.value;
 779             checkOffset(spaceNeeded, val.length >> 1);
 780             Long.getCharsUTF16(l, spaceNeeded, val);
 781         }
 782         count = spaceNeeded;
 783         return this;
 784     }
 785 
 786     /**
 787      * Appends the string representation of the {@code float}
 788      * argument to this sequence.
 789      * <p>
 790      * The overall effect is exactly as if the argument were converted
 791      * to a string by the method {@link String#valueOf(float)},
 792      * and the characters of that string were then
 793      * {@link #append(String) appended} to this character sequence.
 794      *
 795      * @param   f   a {@code float}.
 796      * @return  a reference to this object.
 797      */
 798     public AbstractStringBuilder append(float f) {
 799         FloatingDecimal.appendTo(f,this);
 800         return this;
 801     }


 815     public AbstractStringBuilder append(double d) {
 816         FloatingDecimal.appendTo(d,this);
 817         return this;
 818     }
 819 
 820     /**
 821      * Removes the characters in a substring of this sequence.
 822      * The substring begins at the specified {@code start} and extends to
 823      * the character at index {@code end - 1} or to the end of the
 824      * sequence if no such character exists. If
 825      * {@code start} is equal to {@code end}, no changes are made.
 826      *
 827      * @param      start  The beginning index, inclusive.
 828      * @param      end    The ending index, exclusive.
 829      * @return     This object.
 830      * @throws     StringIndexOutOfBoundsException  if {@code start}
 831      *             is negative, greater than {@code length()}, or
 832      *             greater than {@code end}.
 833      */
 834     public AbstractStringBuilder delete(int start, int end) {
 835         if (end > count) {


 836             end = count;
 837         }
 838         checkRangeSIOOBE(start, end, count);
 839         int len = end - start;
 840         if (len > 0) {
 841             shift(end, -len);
 842             count -= len;
 843         }
 844         return this;
 845     }
 846 
 847     /**
 848      * Appends the string representation of the {@code codePoint}
 849      * argument to this sequence.
 850      *
 851      * <p> The argument is appended to the contents of this sequence.
 852      * The length of this sequence increases by
 853      * {@link Character#charCount(int) Character.charCount(codePoint)}.
 854      *
 855      * <p> The overall effect is exactly as if the argument were
 856      * converted to a {@code char} array by the method
 857      * {@link Character#toChars(int)} and the character in that array
 858      * were then {@link #append(char[]) appended} to this character
 859      * sequence.
 860      *
 861      * @param   codePoint   a Unicode code point
 862      * @return  a reference to this object.
 863      * @exception IllegalArgumentException if the specified
 864      * {@code codePoint} isn't a valid Unicode code point
 865      */
 866     public AbstractStringBuilder appendCodePoint(int codePoint) {


 867         if (Character.isBmpCodePoint(codePoint)) {
 868             return append((char)codePoint);








 869         }
 870         return append(Character.toChars(codePoint));
 871     }
 872 
 873     /**
 874      * Removes the {@code char} at the specified position in this
 875      * sequence. This sequence is shortened by one {@code char}.
 876      *
 877      * <p>Note: If the character at the given index is a supplementary
 878      * character, this method does not remove the entire character. If
 879      * correct handling of supplementary characters is required,
 880      * determine the number of {@code char}s to remove by calling
 881      * {@code Character.charCount(thisSequence.codePointAt(index))},
 882      * where {@code thisSequence} is this sequence.
 883      *
 884      * @param       index  Index of {@code char} to remove
 885      * @return      This object.
 886      * @throws      StringIndexOutOfBoundsException  if the {@code index}
 887      *              is negative or greater than or equal to
 888      *              {@code length()}.
 889      */
 890     public AbstractStringBuilder deleteCharAt(int index) {
 891         checkIndex(index, count);
 892         shift(index + 1, -1);

 893         count--;
 894         return this;
 895     }
 896 
 897     /**
 898      * Replaces the characters in a substring of this sequence
 899      * with characters in the specified {@code String}. The substring
 900      * begins at the specified {@code start} and extends to the character
 901      * at index {@code end - 1} or to the end of the
 902      * sequence if no such character exists. First the
 903      * characters in the substring are removed and then the specified
 904      * {@code String} is inserted at {@code start}. (This
 905      * sequence will be lengthened to accommodate the
 906      * specified String if necessary.)
 907      *
 908      * @param      start    The beginning index, inclusive.
 909      * @param      end      The ending index, exclusive.
 910      * @param      str   String that will replace previous contents.
 911      * @return     This object.
 912      * @throws     StringIndexOutOfBoundsException  if {@code start}
 913      *             is negative, greater than {@code length()}, or
 914      *             greater than {@code end}.
 915      */
 916     public AbstractStringBuilder replace(int start, int end, String str) {
 917         if (end > count) {







 918             end = count;
 919         }
 920         checkRangeSIOOBE(start, end, count);
 921         int len = str.length();
 922         int newCount = count + len - (end - start);
 923         ensureCapacityInternal(newCount);
 924         shift(end, newCount - count);


 925         count = newCount;
 926         putStringAt(start, str);
 927         return this;
 928     }
 929 
 930     /**
 931      * Returns a new {@code String} that contains a subsequence of
 932      * characters currently contained in this character sequence. The
 933      * substring begins at the specified index and extends to the end of
 934      * this sequence.
 935      *
 936      * @param      start    The beginning index, inclusive.
 937      * @return     The new string.
 938      * @throws     StringIndexOutOfBoundsException  if {@code start} is
 939      *             less than zero, or greater than the length of this object.
 940      */
 941     public String substring(int start) {
 942         return substring(start, count);
 943     }
 944 
 945     /**
 946      * Returns a new character sequence that is a subsequence of this sequence.


 971     @Override
 972     public CharSequence subSequence(int start, int end) {
 973         return substring(start, end);
 974     }
 975 
 976     /**
 977      * Returns a new {@code String} that contains a subsequence of
 978      * characters currently contained in this sequence. The
 979      * substring begins at the specified {@code start} and
 980      * extends to the character at index {@code end - 1}.
 981      *
 982      * @param      start    The beginning index, inclusive.
 983      * @param      end      The ending index, exclusive.
 984      * @return     The new string.
 985      * @throws     StringIndexOutOfBoundsException  if {@code start}
 986      *             or {@code end} are negative or greater than
 987      *             {@code length()}, or {@code start} is
 988      *             greater than {@code end}.
 989      */
 990     public String substring(int start, int end) {
 991         checkRangeSIOOBE(start, end, count);
 992         if (isLatin1()) {
 993             return StringLatin1.newString(value, start, end - start);
 994         }
 995         return StringUTF16.newStringSB(value, start, end - start);
 996     }
 997 
 998     private void shift(int offset, int n) {
 999         System.arraycopy(value, offset << coder,
1000                          value, (offset + n) << coder, (count - offset) << coder);
1001     }
1002 
1003     /**
1004      * Inserts the string representation of a subarray of the {@code str}
1005      * array argument into this sequence. The subarray begins at the
1006      * specified {@code offset} and extends {@code len} {@code char}s.
1007      * The characters of the subarray are inserted into this sequence at
1008      * the position indicated by {@code index}. The length of this
1009      * sequence increases by {@code len} {@code char}s.
1010      *
1011      * @param      index    position at which to insert subarray.
1012      * @param      str       A {@code char} array.
1013      * @param      offset   the index of the first {@code char} in subarray to
1014      *             be inserted.
1015      * @param      len      the number of {@code char}s in the subarray to
1016      *             be inserted.
1017      * @return     This object
1018      * @throws     StringIndexOutOfBoundsException  if {@code index}
1019      *             is negative or greater than {@code length()}, or
1020      *             {@code offset} or {@code len} are negative, or
1021      *             {@code (offset+len)} is greater than
1022      *             {@code str.length}.
1023      */
1024     public AbstractStringBuilder insert(int index, char[] str, int offset,
1025                                         int len)
1026     {
1027         checkOffset(index, count);
1028         checkRangeSIOOBE(offset, offset + len, str.length);




1029         ensureCapacityInternal(count + len);
1030         shift(index, len);

1031         count += len;
1032         putCharsAt(index, str, offset, offset + len);
1033         return this;
1034     }
1035 
1036     /**
1037      * Inserts the string representation of the {@code Object}
1038      * argument into this character sequence.
1039      * <p>
1040      * The overall effect is exactly as if the second argument were
1041      * converted to a string by the method {@link String#valueOf(Object)},
1042      * and the characters of that string were then
1043      * {@link #insert(int,String) inserted} into this character
1044      * sequence at the indicated offset.
1045      * <p>
1046      * The {@code offset} argument must be greater than or equal to
1047      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1048      * of this sequence.
1049      *
1050      * @param      offset   the offset.
1051      * @param      obj      an {@code Object}.
1052      * @return     a reference to this object.


1071      * <ul>
1072      * <li>the character at index <i>k</i> in the old character sequence, if
1073      * <i>k</i> is less than {@code offset}
1074      * <li>the character at index <i>k</i>{@code -offset} in the
1075      * argument {@code str}, if <i>k</i> is not less than
1076      * {@code offset} but is less than {@code offset+str.length()}
1077      * <li>the character at index <i>k</i>{@code -str.length()} in the
1078      * old character sequence, if <i>k</i> is not less than
1079      * {@code offset+str.length()}
1080      * </ul><p>
1081      * The {@code offset} argument must be greater than or equal to
1082      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1083      * of this sequence.
1084      *
1085      * @param      offset   the offset.
1086      * @param      str      a string.
1087      * @return     a reference to this object.
1088      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1089      */
1090     public AbstractStringBuilder insert(int offset, String str) {
1091         checkOffset(offset, count);
1092         if (str == null) {

1093             str = "null";
1094         }
1095         int len = str.length();
1096         ensureCapacityInternal(count + len);
1097         shift(offset, len);

1098         count += len;
1099         putStringAt(offset, str);
1100         return this;
1101     }
1102 
1103     /**
1104      * Inserts the string representation of the {@code char} array
1105      * argument into this sequence.
1106      * <p>
1107      * The characters of the array argument are inserted into the
1108      * contents of this sequence at the position indicated by
1109      * {@code offset}. The length of this sequence increases by
1110      * the length of the argument.
1111      * <p>
1112      * The overall effect is exactly as if the second argument were
1113      * converted to a string by the method {@link String#valueOf(char[])},
1114      * and the characters of that string were then
1115      * {@link #insert(int,String) inserted} into this character
1116      * sequence at the indicated offset.
1117      * <p>
1118      * The {@code offset} argument must be greater than or equal to
1119      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1120      * of this sequence.
1121      *
1122      * @param      offset   the offset.
1123      * @param      str      a character array.
1124      * @return     a reference to this object.
1125      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1126      */
1127     public AbstractStringBuilder insert(int offset, char[] str) {
1128         checkOffset(offset, count);

1129         int len = str.length;
1130         ensureCapacityInternal(count + len);
1131         shift(offset, len);

1132         count += len;
1133         putCharsAt(offset, str, 0, len);
1134         return this;
1135     }
1136 
1137     /**
1138      * Inserts the specified {@code CharSequence} into this sequence.
1139      * <p>
1140      * The characters of the {@code CharSequence} argument are inserted,
1141      * in order, into this sequence at the indicated offset, moving up
1142      * any characters originally above that position and increasing the length
1143      * of this sequence by the length of the argument s.
1144      * <p>
1145      * The result of this method is exactly the same as if it were an
1146      * invocation of this object's
1147      * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length())
1148      * method.
1149      *
1150      * <p>If {@code s} is {@code null}, then the four characters
1151      * {@code "null"} are inserted into this sequence.
1152      *
1153      * @param      dstOffset   the offset.
1154      * @param      s the sequence to be inserted
1155      * @return     a reference to this object.
1156      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1157      */
1158     public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
1159         if (s == null) {
1160             s = "null";
1161         }
1162         if (s instanceof String) {
1163             return this.insert(dstOffset, (String)s);
1164         }
1165         return this.insert(dstOffset, s, 0, s.length());
1166     }
1167 
1168     /**
1169      * Inserts a subsequence of the specified {@code CharSequence} into
1170      * this sequence.
1171      * <p>
1172      * The subsequence of the argument {@code s} specified by
1173      * {@code start} and {@code end} are inserted,
1174      * in order, into this sequence at the specified destination offset, moving
1175      * up any characters originally above that position. The length of this
1176      * sequence is increased by {@code end - start}.
1177      * <p>
1178      * The character at index <i>k</i> in this sequence becomes equal to:
1179      * <ul>
1180      * <li>the character at index <i>k</i> in this sequence, if
1181      * <i>k</i> is less than {@code dstOffset}
1182      * <li>the character at index <i>k</i>{@code +start-dstOffset} in
1183      * the argument {@code s}, if <i>k</i> is greater than or equal to
1184      * {@code dstOffset} but is less than {@code dstOffset+end-start}


1193      * {@code end}.
1194      * <p>The end argument must be greater than or equal to
1195      * {@code start}, and less than or equal to the length of s.
1196      *
1197      * <p>If {@code s} is {@code null}, then this method inserts
1198      * characters as if the s parameter was a sequence containing the four
1199      * characters {@code "null"}.
1200      *
1201      * @param      dstOffset   the offset in this sequence.
1202      * @param      s       the sequence to be inserted.
1203      * @param      start   the starting index of the subsequence to be inserted.
1204      * @param      end     the end index of the subsequence to be inserted.
1205      * @return     a reference to this object.
1206      * @throws     IndexOutOfBoundsException  if {@code dstOffset}
1207      *             is negative or greater than {@code this.length()}, or
1208      *              {@code start} or {@code end} are negative, or
1209      *              {@code start} is greater than {@code end} or
1210      *              {@code end} is greater than {@code s.length()}
1211      */
1212     public AbstractStringBuilder insert(int dstOffset, CharSequence s,
1213                                         int start, int end)
1214     {
1215         if (s == null) {
1216             s = "null";
1217         }
1218         checkOffset(dstOffset, count);
1219         checkRange(start, end, s.length());



1220         int len = end - start;
1221         ensureCapacityInternal(count + len);
1222         shift(dstOffset, len);



1223         count += len;
1224         putCharsAt(dstOffset, s, start, end);
1225         return this;
1226     }
1227 
1228     /**
1229      * Inserts the string representation of the {@code boolean}
1230      * argument into this sequence.
1231      * <p>
1232      * The overall effect is exactly as if the second argument were
1233      * converted to a string by the method {@link String#valueOf(boolean)},
1234      * and the characters of that string were then
1235      * {@link #insert(int,String) inserted} into this character
1236      * sequence at the indicated offset.
1237      * <p>
1238      * The {@code offset} argument must be greater than or equal to
1239      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1240      * of this sequence.
1241      *
1242      * @param      offset   the offset.
1243      * @param      b        a {@code boolean}.
1244      * @return     a reference to this object.


1251     /**
1252      * Inserts the string representation of the {@code char}
1253      * argument into this sequence.
1254      * <p>
1255      * The overall effect is exactly as if the second argument were
1256      * converted to a string by the method {@link String#valueOf(char)},
1257      * and the character in that string were then
1258      * {@link #insert(int,String) inserted} into this character
1259      * sequence at the indicated offset.
1260      * <p>
1261      * The {@code offset} argument must be greater than or equal to
1262      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1263      * of this sequence.
1264      *
1265      * @param      offset   the offset.
1266      * @param      c        a {@code char}.
1267      * @return     a reference to this object.
1268      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1269      */
1270     public AbstractStringBuilder insert(int offset, char c) {
1271         checkOffset(offset, count);
1272         ensureCapacityInternal(count + 1);
1273         shift(offset, 1);

1274         count += 1;
1275         if (isLatin1() && StringLatin1.canEncode(c)) {
1276             value[offset] = (byte)c;
1277         } else {
1278             if (isLatin1()) {
1279                 inflate();
1280             }
1281             StringUTF16.putCharSB(value, offset, c);
1282         }
1283         return this;
1284     }
1285 
1286     /**
1287      * Inserts the string representation of the second {@code int}
1288      * argument into this sequence.
1289      * <p>
1290      * The overall effect is exactly as if the second argument were
1291      * converted to a string by the method {@link String#valueOf(int)},
1292      * and the characters of that string were then
1293      * {@link #insert(int,String) inserted} into this character
1294      * sequence at the indicated offset.
1295      * <p>
1296      * The {@code offset} argument must be greater than or equal to
1297      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1298      * of this sequence.
1299      *
1300      * @param      offset   the offset.
1301      * @param      i        an {@code int}.
1302      * @return     a reference to this object.


1394     }
1395 
1396     /**
1397      * Returns the index within this string of the first occurrence of the
1398      * specified substring, starting at the specified index.
1399      *
1400      * <p>The returned index is the smallest value {@code k} for which:
1401      * <pre>{@code
1402      *     k >= Math.min(fromIndex, this.length()) &&
1403      *                   this.toString().startsWith(str, k)
1404      * }</pre>
1405      * If no such value of {@code k} exists, then {@code -1} is returned.
1406      *
1407      * @param   str         the substring to search for.
1408      * @param   fromIndex   the index from which to start the search.
1409      * @return  the index of the first occurrence of the specified substring,
1410      *          starting at the specified index,
1411      *          or {@code -1} if there is no such occurrence.
1412      */
1413     public int indexOf(String str, int fromIndex) {
1414         return String.indexOf(value, coder, count, str, fromIndex);
1415     }
1416 
1417     /**
1418      * Returns the index within this string of the last occurrence of the
1419      * specified substring.  The last occurrence of the empty string "" is
1420      * considered to occur at the index value {@code this.length()}.
1421      *
1422      * <p>The returned index is the largest value {@code k} for which:
1423      * <pre>{@code
1424      * this.toString().startsWith(str, k)
1425      * }</pre>
1426      * If no such value of {@code k} exists, then {@code -1} is returned.
1427      *
1428      * @param   str   the substring to search for.
1429      * @return  the index of the last occurrence of the specified substring,
1430      *          or {@code -1} if there is no such occurrence.
1431      */
1432     public int lastIndexOf(String str) {
1433         return lastIndexOf(str, count);
1434     }
1435 
1436     /**
1437      * Returns the index within this string of the last occurrence of the
1438      * specified substring, searching backward starting at the specified index.
1439      *
1440      * <p>The returned index is the largest value {@code k} for which:
1441      * <pre>{@code
1442      *     k <= Math.min(fromIndex, this.length()) &&
1443      *                   this.toString().startsWith(str, k)
1444      * }</pre>
1445      * If no such value of {@code k} exists, then {@code -1} is returned.
1446      *
1447      * @param   str         the substring to search for.
1448      * @param   fromIndex   the index to start the search from.
1449      * @return  the index of the last occurrence of the specified substring,
1450      *          searching backward from the specified index,
1451      *          or {@code -1} if there is no such occurrence.
1452      */
1453     public int lastIndexOf(String str, int fromIndex) {
1454         return String.lastIndexOf(value, coder, count, str, fromIndex);
1455     }
1456 
1457     /**
1458      * Causes this character sequence to be replaced by the reverse of
1459      * the sequence. If there are any surrogate pairs included in the
1460      * sequence, these are treated as single characters for the
1461      * reverse operation. Thus, the order of the high-low surrogates
1462      * is never reversed.
1463      *
1464      * Let <i>n</i> be the character length of this character sequence
1465      * (not the length in {@code char} values) just prior to
1466      * execution of the {@code reverse} method. Then the
1467      * character at index <i>k</i> in the new character sequence is
1468      * equal to the character at index <i>n-k-1</i> in the old
1469      * character sequence.
1470      *
1471      * <p>Note that the reverse operation may result in producing
1472      * surrogate pairs that were unpaired low-surrogates and
1473      * high-surrogates before the operation. For example, reversing
1474      * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
1475      * a valid surrogate pair.
1476      *
1477      * @return  a reference to this object.
1478      */
1479     public AbstractStringBuilder reverse() {
1480         byte[] val = this.value;
1481         int count = this.count;
1482         int coder = this.coder;
1483         int n = count - 1;
1484         if (COMPACT_STRINGS && coder == LATIN1) {
1485             for (int j = (n-1) >> 1; j >= 0; j--) {
1486                 int k = n - j;
1487                 byte cj = val[j];
1488                 val[j] = val[k];
1489                 val[k] = cj;
1490             }
1491         } else {
1492             checkOffset(count, val.length >> 1);
1493             boolean hasSurrogates = false;
1494             for (int j = (n-1) >> 1; j >= 0; j--) {
1495                 int k = n - j;
1496                 char cj = StringUTF16.getChar(val, j);
1497                 char ck = StringUTF16.getChar(val, k);
1498                 StringUTF16.putChar(val, j, ck);
1499                 StringUTF16.putChar(val, k, cj);
1500                 if (Character.isSurrogate(cj) ||
1501                     Character.isSurrogate(ck)) {
1502                     hasSurrogates = true;
1503                 }
1504             }
1505             if (hasSurrogates) {
1506                 reverseAllValidSurrogatePairs(val, count);
1507             }
1508         }
1509         return this;
1510     }
1511 
1512     /** Outlined helper method for reverse() */
1513     private void reverseAllValidSurrogatePairs(byte[] val, int count) {
1514         for (int i = 0; i < count - 1; i++) {
1515             char c2 = StringUTF16.getChar(val, i);
1516             if (Character.isLowSurrogate(c2)) {
1517                 char c1 = StringUTF16.getChar(val, i + 1);
1518                 if (Character.isHighSurrogate(c1)) {
1519                     StringUTF16.putChar(val, i++, c1);
1520                     StringUTF16.putChar(val, i, c2);
1521                 }
1522             }
1523         }
1524     }
1525 
1526     /**
1527      * Returns a string representing the data in this sequence.
1528      * A new {@code String} object is allocated and initialized to
1529      * contain the character sequence currently represented by this
1530      * object. This {@code String} is then returned. Subsequent
1531      * changes to this sequence do not affect the contents of the
1532      * {@code String}.
1533      *
1534      * @return  a string representation of this sequence of characters.
1535      */
1536     @Override
1537     public abstract String toString();
1538 
1539     /**
1540      * {@inheritDoc}
1541      * @since 1.9
1542      */
1543     @Override
1544     public IntStream chars() {
1545         byte[] val = this.value; int count = this.count; byte coder = this.coder;
1546         checkOffset(count, val.length >> coder);
1547         // Reuse String-based spliterator. This requires a supplier to
1548         // capture the value and count when the terminal operation is executed
1549         return StreamSupport.intStream(
1550                 () -> coder == LATIN1 ? new StringLatin1.CharsSpliterator(val, 0, count, 0)
1551                                       : new StringUTF16.CharsSpliterator(val, 0, count, 0),
1552                 Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED,
1553                 false);
1554     }
1555 
1556     /**
1557      * {@inheritDoc}
1558      * @since 1.9
1559      */
1560     @Override
1561     public IntStream codePoints() {
1562         byte[] val = this.value; int count = this.count; byte coder = this.coder;
1563         checkOffset(count, val.length >> coder);
1564         // Reuse String-based spliterator. This requires a supplier to
1565         // capture the value and count when the terminal operation is executed
1566         return StreamSupport.intStream(
1567                 () -> coder == LATIN1 ? new StringLatin1.CharsSpliterator(val, 0, count, 0)
1568                                       : new StringUTF16.CodePointsSpliterator(val, 0, count, 0),
1569                 Spliterator.ORDERED,
1570                 false);
1571     }
1572 
1573     /**
1574      * Needed by {@code String} for the contentEquals method.
1575      */
1576     final byte[] getValue() {
1577         return value;
1578     }
1579 
1580     /*
1581      * Invoker guarantees it is in UTF16 (inflate itself for asb), if two
1582      * coders are different and the dstBegin has enough space
1583      *
1584      * @param dstBegin  the char index, not offset of byte[]
1585      * @param coder     the coder of dst[]
1586      */
1587     protected void getBytes(byte dst[], int dstBegin, byte coder) {
1588         if (this.coder == coder) {
1589             System.arraycopy(value, 0, dst, dstBegin << coder, count << coder);
1590         } else {        // this.coder == LATIN && coder == UTF16
1591             StringLatin1.inflateSB(value, dst, dstBegin, count);
1592         }
1593     }
1594 
1595     /* for readObject() */
1596     protected void initBytes(char[] value, int off, int len) {
1597         if (String.COMPACT_STRINGS) {
1598             this.value = StringUTF16.compress(value, off, len);
1599             if (this.value != null) {
1600                 this.coder = LATIN1;
1601                 return;
1602             }
1603         }
1604         this.coder = UTF16;
1605         this.value = StringUTF16.toBytes(value, off, len);
1606     }
1607 
1608     final byte getCoder() {
1609         return COMPACT_STRINGS ? coder : UTF16;
1610     }
1611 
1612     final boolean isLatin1() {
1613         return COMPACT_STRINGS && coder == LATIN1;
1614     }
1615 
1616     private final void putCharsAt(int index, char[] s, int off, int end) {
1617         if (isLatin1()) {
1618             byte[] val = this.value;
1619             for (int i = off, j = index; i < end; i++) {
1620                 char c = s[i];
1621                 if (StringLatin1.canEncode(c)) {
1622                     val[j++] = (byte)c;
1623                 } else {
1624                     inflate();
1625                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1626                     return;
1627                 }
1628             }
1629         } else {
1630             StringUTF16.putCharsSB(this.value, index, s, off, end);
1631         }
1632     }
1633 
1634     private final void putCharsAt(int index, CharSequence s, int off, int end) {
1635         if (isLatin1()) {
1636             byte[] val = this.value;
1637             for (int i = off, j = index; i < end; i++) {
1638                 char c = s.charAt(i);
1639                 if (StringLatin1.canEncode(c)) {
1640                     val[j++] = (byte)c;
1641                 } else {
1642                     inflate();
1643                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1644                     return;
1645                 }
1646             }
1647         } else {
1648             StringUTF16.putCharsSB(this.value, index, s, off, end);
1649         }
1650     }
1651 
1652     private final void putStringAt(int index, String str) {
1653         if (getCoder() != str.coder()) {
1654             inflate();
1655         }
1656         byte[] val = this.value;
1657         byte coder = this.coder;
1658         checkOffset(index + str.length(), val.length >> coder);
1659         str.getBytes(val, index, coder);
1660     }
1661 
1662     private final void appendChars(char[] s, int off, int end) {
1663         if (isLatin1()) {
1664             byte[] val = this.value;
1665             for (int i = off, j = count; i < end; i++) {
1666                 char c = s[i];
1667                 if (StringLatin1.canEncode(c)) {
1668                     val[j++] = (byte)c;
1669                 } else {
1670                     count = j;
1671                     inflate();
1672                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1673                     count += end - i;
1674                     return;
1675                 }
1676             }
1677         } else {
1678             StringUTF16.putCharsSB(this.value, count, s, off, end);
1679         }
1680         count += end - off;
1681     }
1682 
1683     private final void appendChars(CharSequence s, int off, int end) {
1684         if (isLatin1()) {
1685             byte[] val = this.value;
1686             for (int i = off, j = count; i < end; i++) {
1687                 char c = s.charAt(i);
1688                 if (StringLatin1.canEncode(c)) {
1689                     val[j++] = (byte)c;
1690                 } else {
1691                     count = j;
1692                     inflate();
1693                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1694                     count += end - i;
1695                     return;
1696                 }
1697             }
1698         } else {
1699             StringUTF16.putCharsSB(this.value, count, s, off, end);
1700         }
1701         count += end - off;
1702     }
1703 
1704     /* IndexOutOfBoundsException, if out of bounds */
1705     private static void checkRange(int start, int end, int len) {
1706         if (start < 0 || start > end || end > len) {
1707             throw new IndexOutOfBoundsException(
1708                 "start " + start + ", end " + end + ", length " + len);
1709         }
1710     }
1711 
1712     /* StringIndexOutOfBoundsException, if out of bounds */
1713     private static void checkRangeSIOOBE(int start, int end, int len) {
1714         if (start < 0 || start > end || end > len) {
1715             throw new StringIndexOutOfBoundsException(
1716                 "start " + start + ", end " + end + ", length " + len);
1717         }
1718     }
1719 }