1 /*
   2  * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import jdk.internal.math.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     private static final byte[] EMPTYVALUE = new byte[0];
  73 
  74     /**
  75      * This no-arg constructor is necessary for serialization of subclasses.
  76      */
  77     AbstractStringBuilder() {
  78         value = EMPTYVALUE;
  79     }
  80 
  81     /**
  82      * Creates an AbstractStringBuilder of the specified capacity.
  83      */
  84     AbstractStringBuilder(int capacity) {
  85         if (COMPACT_STRINGS) {
  86             value = new byte[capacity];
  87             coder = LATIN1;
  88         } else {
  89             value = StringUTF16.newBytesFor(capacity);
  90             coder = UTF16;
  91         }
  92     }
  93 
  94     /**
  95      * Creates an AbstractStringBuilder with the specified coder and with
  96      * the initial capacity equal to the smaller of (length + addition)
  97      * and Integer.MAX_VALUE.
  98      */
  99     AbstractStringBuilder(byte coder, int length, int addition) {
 100         if (length < 0) {
 101             throw new NegativeArraySizeException("Negative length: " + length);
 102         }
 103         this.coder = coder;
 104         int capacity = (length < Integer.MAX_VALUE - addition)
 105                 ? length + addition : Integer.MAX_VALUE;
 106         value = (coder == LATIN1)
 107                 ? new byte[capacity] : StringUTF16.newBytesFor(capacity);
 108     }
 109 
 110     /**
 111      * Compares the objects of two AbstractStringBuilder implementations lexicographically.
 112      *
 113      * @since 11
 114      */
 115     int compareTo(AbstractStringBuilder another) {
 116         if (this == another) {
 117             return 0;
 118         }
 119 
 120         byte val1[] = value;
 121         byte val2[] = another.value;
 122         int count1 = this.count;
 123         int count2 = another.count;
 124 
 125         if (coder == another.coder) {
 126             return isLatin1() ? StringLatin1.compareTo(val1, val2, count1, count2)
 127                               : StringUTF16.compareTo(val1, val2, count1, count2);
 128         }
 129         return isLatin1() ? StringLatin1.compareToUTF16(val1, val2, count1, count2)
 130                           : StringUTF16.compareToLatin1(val1, val2, count1, count2);
 131     }
 132 
 133     /**
 134      * Returns the length (character count).
 135      *
 136      * @return  the length of the sequence of characters currently
 137      *          represented by this object
 138      */
 139     @Override
 140     public int length() {
 141         return count;
 142     }
 143 
 144     /**
 145      * Returns the current capacity. The capacity is the amount of storage
 146      * available for newly inserted characters, beyond which an allocation
 147      * will occur.
 148      *
 149      * @return  the current capacity
 150      */
 151     public int capacity() {
 152         return value.length >> coder;
 153     }
 154 
 155     /**
 156      * Ensures that the capacity is at least equal to the specified minimum.
 157      * If the current capacity is less than the argument, then a new internal
 158      * array is allocated with greater capacity. The new capacity is the
 159      * larger of:
 160      * <ul>
 161      * <li>The {@code minimumCapacity} argument.
 162      * <li>Twice the old capacity, plus {@code 2}.
 163      * </ul>
 164      * If the {@code minimumCapacity} argument is nonpositive, this
 165      * method takes no action and simply returns.
 166      * Note that subsequent operations on this object can reduce the
 167      * actual capacity below that requested here.
 168      *
 169      * @param   minimumCapacity   the minimum desired capacity.
 170      */
 171     public void ensureCapacity(int minimumCapacity) {
 172         if (minimumCapacity > 0) {
 173             ensureCapacityInternal(minimumCapacity);
 174         }
 175     }
 176 
 177     /**
 178      * For positive values of {@code minimumCapacity}, this method
 179      * behaves like {@code ensureCapacity}, however it is never
 180      * synchronized.
 181      * If {@code minimumCapacity} is non positive due to numeric
 182      * overflow, this method throws {@code OutOfMemoryError}.
 183      */
 184     private void ensureCapacityInternal(int minimumCapacity) {
 185         // overflow-conscious code
 186         int oldCapacity = value.length >> coder;
 187         if (minimumCapacity - oldCapacity > 0) {
 188             value = Arrays.copyOf(value,
 189                     newCapacity(minimumCapacity) << coder);
 190         }
 191     }
 192 
 193     /**
 194      * The maximum size of array to allocate (unless necessary).
 195      * Some VMs reserve some header words in an array.
 196      * Attempts to allocate larger arrays may result in
 197      * OutOfMemoryError: Requested array size exceeds VM limit
 198      */
 199     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 200 
 201     /**
 202      * Returns a capacity at least as large as the given minimum capacity.
 203      * Returns the current capacity increased by the same amount + 2 if
 204      * that suffices.
 205      * Will not return a capacity greater than
 206      * {@code (MAX_ARRAY_SIZE >> coder)} unless the given minimum capacity
 207      * is greater than that.
 208      *
 209      * @param  minCapacity the desired minimum capacity
 210      * @throws OutOfMemoryError if minCapacity is less than zero or
 211      *         greater than (Integer.MAX_VALUE >> coder)
 212      */
 213     private int newCapacity(int minCapacity) {
 214         // overflow-conscious code
 215         int oldCapacity = value.length >> coder;
 216         int newCapacity = (oldCapacity << 1) + 2;
 217         if (newCapacity - minCapacity < 0) {
 218             newCapacity = minCapacity;
 219         }
 220         int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
 221         return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
 222             ? hugeCapacity(minCapacity)
 223             : newCapacity;
 224     }
 225 
 226     private int hugeCapacity(int minCapacity) {
 227         int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
 228         int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
 229         if (UNSAFE_BOUND - minCapacity < 0) { // overflow
 230             throw new OutOfMemoryError();
 231         }
 232         return (minCapacity > SAFE_BOUND)
 233             ? minCapacity : SAFE_BOUND;
 234     }
 235 
 236     /**
 237      * If the coder is "isLatin1", this inflates the internal 8-bit storage
 238      * to 16-bit <hi=0, low> pair storage.
 239      */
 240     private void inflate() {
 241         if (!isLatin1()) {
 242             return;
 243         }
 244         byte[] buf = StringUTF16.newBytesFor(value.length);
 245         StringLatin1.inflate(value, 0, buf, 0, count);
 246         this.value = buf;
 247         this.coder = UTF16;
 248     }
 249 
 250     /**
 251      * Attempts to reduce storage used for the character sequence.
 252      * If the buffer is larger than necessary to hold its current sequence of
 253      * characters, then it may be resized to become more space efficient.
 254      * Calling this method may, but is not required to, affect the value
 255      * returned by a subsequent call to the {@link #capacity()} method.
 256      */
 257     public void trimToSize() {
 258         int length = count << coder;
 259         if (length < value.length) {
 260             value = Arrays.copyOf(value, length);
 261         }
 262     }
 263 
 264     /**
 265      * Sets the length of the character sequence.
 266      * The sequence is changed to a new character sequence
 267      * whose length is specified by the argument. For every nonnegative
 268      * index <i>k</i> less than {@code newLength}, the character at
 269      * index <i>k</i> in the new character sequence is the same as the
 270      * character at index <i>k</i> in the old sequence if <i>k</i> is less
 271      * than the length of the old character sequence; otherwise, it is the
 272      * null character {@code '\u005Cu0000'}.
 273      *
 274      * In other words, if the {@code newLength} argument is less than
 275      * the current length, the length is changed to the specified length.
 276      * <p>
 277      * If the {@code newLength} argument is greater than or equal
 278      * to the current length, sufficient null characters
 279      * ({@code '\u005Cu0000'}) are appended so that
 280      * length becomes the {@code newLength} argument.
 281      * <p>
 282      * The {@code newLength} argument must be greater than or equal
 283      * to {@code 0}.
 284      *
 285      * @param      newLength   the new length
 286      * @throws     IndexOutOfBoundsException  if the
 287      *               {@code newLength} argument is negative.
 288      */
 289     public void setLength(int newLength) {
 290         if (newLength < 0) {
 291             throw new StringIndexOutOfBoundsException(newLength);
 292         }
 293         ensureCapacityInternal(newLength);
 294         if (count < newLength) {
 295             if (isLatin1()) {
 296                 StringLatin1.fillNull(value, count, newLength);
 297             } else {
 298                 StringUTF16.fillNull(value, count, newLength);
 299             }
 300         }
 301         count = newLength;
 302     }
 303 
 304     /**
 305      * Returns the {@code char} value in this sequence at the specified index.
 306      * The first {@code char} value is at index {@code 0}, the next at index
 307      * {@code 1}, and so on, as in array indexing.
 308      * <p>
 309      * The index argument must be greater than or equal to
 310      * {@code 0}, and less than the length of this sequence.
 311      *
 312      * <p>If the {@code char} value specified by the index is a
 313      * <a href="Character.html#unicode">surrogate</a>, the surrogate
 314      * value is returned.
 315      *
 316      * @param      index   the index of the desired {@code char} value.
 317      * @return     the {@code char} value at the specified index.
 318      * @throws     IndexOutOfBoundsException  if {@code index} is
 319      *             negative or greater than or equal to {@code length()}.
 320      */
 321     @Override
 322     public char charAt(int index) {
 323         checkIndex(index, count);
 324         if (isLatin1()) {
 325             return (char)(value[index] & 0xff);
 326         }
 327         return StringUTF16.charAt(value, index);
 328     }
 329 
 330     /**
 331      * Returns the character (Unicode code point) at the specified
 332      * index. The index refers to {@code char} values
 333      * (Unicode code units) and ranges from {@code 0} to
 334      * {@link #length()}{@code  - 1}.
 335      *
 336      * <p> If the {@code char} value specified at the given index
 337      * is in the high-surrogate range, the following index is less
 338      * than the length of this sequence, and the
 339      * {@code char} value at the following index is in the
 340      * low-surrogate range, then the supplementary code point
 341      * corresponding to this surrogate pair is returned. Otherwise,
 342      * the {@code char} value at the given index is returned.
 343      *
 344      * @param      index the index to the {@code char} values
 345      * @return     the code point value of the character at the
 346      *             {@code index}
 347      * @throws     IndexOutOfBoundsException  if the {@code index}
 348      *             argument is negative or not less than the length of this
 349      *             sequence.
 350      */
 351     public int codePointAt(int index) {
 352         int count = this.count;
 353         byte[] value = this.value;
 354         checkIndex(index, count);
 355         if (isLatin1()) {
 356             return value[index] & 0xff;
 357         }
 358         return StringUTF16.codePointAtSB(value, index, count);
 359     }
 360 
 361     /**
 362      * Returns the character (Unicode code point) before the specified
 363      * index. The index refers to {@code char} values
 364      * (Unicode code units) and ranges from {@code 1} to {@link
 365      * #length()}.
 366      *
 367      * <p> If the {@code char} value at {@code (index - 1)}
 368      * is in the low-surrogate range, {@code (index - 2)} is not
 369      * negative, and the {@code char} value at {@code (index -
 370      * 2)} is in the high-surrogate range, then the
 371      * supplementary code point value of the surrogate pair is
 372      * returned. If the {@code char} value at {@code index -
 373      * 1} is an unpaired low-surrogate or a high-surrogate, the
 374      * surrogate value is returned.
 375      *
 376      * @param     index the index following the code point that should be returned
 377      * @return    the Unicode code point value before the given index.
 378      * @throws    IndexOutOfBoundsException if the {@code index}
 379      *            argument is less than 1 or greater than the length
 380      *            of this sequence.
 381      */
 382     public int codePointBefore(int index) {
 383         int i = index - 1;
 384         if (i < 0 || i >= count) {
 385             throw new StringIndexOutOfBoundsException(index);
 386         }
 387         if (isLatin1()) {
 388             return value[i] & 0xff;
 389         }
 390         return StringUTF16.codePointBeforeSB(value, index);
 391     }
 392 
 393     /**
 394      * Returns the number of Unicode code points in the specified text
 395      * range of this sequence. The text range begins at the specified
 396      * {@code beginIndex} and extends to the {@code char} at
 397      * index {@code endIndex - 1}. Thus the length (in
 398      * {@code char}s) of the text range is
 399      * {@code endIndex-beginIndex}. Unpaired surrogates within
 400      * this sequence count as one code point each.
 401      *
 402      * @param beginIndex the index to the first {@code char} of
 403      * the text range.
 404      * @param endIndex the index after the last {@code char} of
 405      * the text range.
 406      * @return the number of Unicode code points in the specified text
 407      * range
 408      * @throws    IndexOutOfBoundsException if the
 409      * {@code beginIndex} is negative, or {@code endIndex}
 410      * is larger than the length of this sequence, or
 411      * {@code beginIndex} is larger than {@code endIndex}.
 412      */
 413     public int codePointCount(int beginIndex, int endIndex) {
 414         if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
 415             throw new IndexOutOfBoundsException();
 416         }
 417         if (isLatin1()) {
 418             return endIndex - beginIndex;
 419         }
 420         return StringUTF16.codePointCountSB(value, beginIndex, endIndex);
 421     }
 422 
 423     /**
 424      * Returns the index within this sequence that is offset from the
 425      * given {@code index} by {@code codePointOffset} code
 426      * points. Unpaired surrogates within the text range given by
 427      * {@code index} and {@code codePointOffset} count as
 428      * one code point each.
 429      *
 430      * @param index the index to be offset
 431      * @param codePointOffset the offset in code points
 432      * @return the index within this sequence
 433      * @throws    IndexOutOfBoundsException if {@code index}
 434      *   is negative or larger then the length of this sequence,
 435      *   or if {@code codePointOffset} is positive and the subsequence
 436      *   starting with {@code index} has fewer than
 437      *   {@code codePointOffset} code points,
 438      *   or if {@code codePointOffset} is negative and the subsequence
 439      *   before {@code index} has fewer than the absolute value of
 440      *   {@code codePointOffset} code points.
 441      */
 442     public int offsetByCodePoints(int index, int codePointOffset) {
 443         if (index < 0 || index > count) {
 444             throw new IndexOutOfBoundsException();
 445         }
 446         return Character.offsetByCodePoints(this,
 447                                             index, codePointOffset);
 448     }
 449 
 450     /**
 451      * Characters are copied from this sequence into the
 452      * destination character array {@code dst}. The first character to
 453      * be copied is at index {@code srcBegin}; the last character to
 454      * be copied is at index {@code srcEnd-1}. The total number of
 455      * characters to be copied is {@code srcEnd-srcBegin}. The
 456      * characters are copied into the subarray of {@code dst} starting
 457      * at index {@code dstBegin} and ending at index:
 458      * <pre>{@code
 459      * dstbegin + (srcEnd-srcBegin) - 1
 460      * }</pre>
 461      *
 462      * @param      srcBegin   start copying at this offset.
 463      * @param      srcEnd     stop copying at this offset.
 464      * @param      dst        the array to copy the data into.
 465      * @param      dstBegin   offset into {@code dst}.
 466      * @throws     IndexOutOfBoundsException  if any of the following is true:
 467      *             <ul>
 468      *             <li>{@code srcBegin} is negative
 469      *             <li>{@code dstBegin} is negative
 470      *             <li>the {@code srcBegin} argument is greater than
 471      *             the {@code srcEnd} argument.
 472      *             <li>{@code srcEnd} is greater than
 473      *             {@code this.length()}.
 474      *             <li>{@code dstBegin+srcEnd-srcBegin} is greater than
 475      *             {@code dst.length}
 476      *             </ul>
 477      */
 478     public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
 479     {
 480         checkRangeSIOOBE(srcBegin, srcEnd, count);  // compatible to old version
 481         int n = srcEnd - srcBegin;
 482         checkRange(dstBegin, dstBegin + n, dst.length);
 483         if (isLatin1()) {
 484             StringLatin1.getChars(value, srcBegin, srcEnd, dst, dstBegin);
 485         } else {
 486             StringUTF16.getChars(value, srcBegin, srcEnd, dst, dstBegin);
 487         }
 488     }
 489 
 490     /**
 491      * The character at the specified index is set to {@code ch}. This
 492      * sequence is altered to represent a new character sequence that is
 493      * identical to the old character sequence, except that it contains the
 494      * character {@code ch} at position {@code index}.
 495      * <p>
 496      * The index argument must be greater than or equal to
 497      * {@code 0}, and less than the length of this sequence.
 498      *
 499      * @param      index   the index of the character to modify.
 500      * @param      ch      the new character.
 501      * @throws     IndexOutOfBoundsException  if {@code index} is
 502      *             negative or greater than or equal to {@code length()}.
 503      */
 504     public void setCharAt(int index, char ch) {
 505         checkIndex(index, count);
 506         if (isLatin1() && StringLatin1.canEncode(ch)) {
 507             value[index] = (byte)ch;
 508         } else {
 509             if (isLatin1()) {
 510                 inflate();
 511             }
 512             StringUTF16.putCharSB(value, index, ch);
 513         }
 514     }
 515 
 516     /**
 517      * Appends the string representation of the {@code Object} argument.
 518      * <p>
 519      * The overall effect is exactly as if the argument were converted
 520      * to a string by the method {@link String#valueOf(Object)},
 521      * and the characters of that string were then
 522      * {@link #append(String) appended} to this character sequence.
 523      *
 524      * @param   obj   an {@code Object}.
 525      * @return  a reference to this object.
 526      */
 527     public AbstractStringBuilder append(Object obj) {
 528         return append(String.valueOf(obj));
 529     }
 530 
 531     /**
 532      * Appends the specified string to this character sequence.
 533      * <p>
 534      * The characters of the {@code String} argument are appended, in
 535      * order, increasing the length of this sequence by the length of the
 536      * argument. If {@code str} is {@code null}, then the four
 537      * characters {@code "null"} are appended.
 538      * <p>
 539      * Let <i>n</i> be the length of this character sequence just prior to
 540      * execution of the {@code append} method. Then the character at
 541      * index <i>k</i> in the new character sequence is equal to the character
 542      * at index <i>k</i> in the old character sequence, if <i>k</i> is less
 543      * than <i>n</i>; otherwise, it is equal to the character at index
 544      * <i>k-n</i> in the argument {@code str}.
 545      *
 546      * @param   str   a string.
 547      * @return  a reference to this object.
 548      */
 549     public AbstractStringBuilder append(String str) {
 550         if (str == null) {
 551             return appendNull();
 552         }
 553         int len = str.length();
 554         ensureCapacityInternal(count + len);
 555         putStringAt(count, str);
 556         count += len;
 557         return this;
 558     }
 559 
 560     // Documentation in subclasses because of synchro difference
 561     public AbstractStringBuilder append(StringBuffer sb) {
 562         return this.append((AbstractStringBuilder)sb);
 563     }
 564 
 565     /**
 566      * @since 1.8
 567      */
 568     AbstractStringBuilder append(AbstractStringBuilder asb) {
 569         if (asb == null) {
 570             return appendNull();
 571         }
 572         int len = asb.length();
 573         ensureCapacityInternal(count + len);
 574         if (getCoder() != asb.getCoder()) {
 575             inflate();
 576         }
 577         asb.getBytes(value, count, coder);
 578         count += len;
 579         return this;
 580     }
 581 
 582     // Documentation in subclasses because of synchro difference
 583     @Override
 584     public AbstractStringBuilder append(CharSequence s) {
 585         if (s == null) {
 586             return appendNull();
 587         }
 588         if (s instanceof String) {
 589             return this.append((String)s);
 590         }
 591         if (s instanceof AbstractStringBuilder) {
 592             return this.append((AbstractStringBuilder)s);
 593         }
 594         return this.append(s, 0, s.length());
 595     }
 596 
 597     private AbstractStringBuilder appendNull() {
 598         ensureCapacityInternal(count + 4);
 599         int count = this.count;
 600         byte[] val = this.value;
 601         if (isLatin1()) {
 602             val[count++] = 'n';
 603             val[count++] = 'u';
 604             val[count++] = 'l';
 605             val[count++] = 'l';
 606         } else {
 607             count = StringUTF16.putCharsAt(val, count, 'n', 'u', 'l', 'l');
 608         }
 609         this.count = count;
 610         return this;
 611     }
 612 
 613     /**
 614      * Appends a subsequence of the specified {@code CharSequence} to this
 615      * sequence.
 616      * <p>
 617      * Characters of the argument {@code s}, starting at
 618      * index {@code start}, are appended, in order, to the contents of
 619      * this sequence up to the (exclusive) index {@code end}. The length
 620      * of this sequence is increased by the value of {@code end - start}.
 621      * <p>
 622      * Let <i>n</i> be the length of this character sequence just prior to
 623      * execution of the {@code append} method. Then the character at
 624      * index <i>k</i> in this character sequence becomes equal to the
 625      * character at index <i>k</i> in this sequence, if <i>k</i> is less than
 626      * <i>n</i>; otherwise, it is equal to the character at index
 627      * <i>k+start-n</i> in the argument {@code s}.
 628      * <p>
 629      * If {@code s} is {@code null}, then this method appends
 630      * characters as if the s parameter was a sequence containing the four
 631      * characters {@code "null"}.
 632      *
 633      * @param   s the sequence to append.
 634      * @param   start   the starting index of the subsequence to be appended.
 635      * @param   end     the end index of the subsequence to be appended.
 636      * @return  a reference to this object.
 637      * @throws     IndexOutOfBoundsException if
 638      *             {@code start} is negative, or
 639      *             {@code start} is greater than {@code end} or
 640      *             {@code end} is greater than {@code s.length()}
 641      */
 642     @Override
 643     public AbstractStringBuilder append(CharSequence s, int start, int end) {
 644         if (s == null) {
 645             s = "null";
 646         }
 647         checkRange(start, end, s.length());
 648         int len = end - start;
 649         ensureCapacityInternal(count + len);
 650         appendChars(s, start, end);
 651         return this;
 652     }
 653 
 654     /**
 655      * Appends the string representation of the {@code char} array
 656      * argument to this sequence.
 657      * <p>
 658      * The characters of the array argument are appended, in order, to
 659      * the contents of this sequence. The length of this sequence
 660      * increases by the length of the argument.
 661      * <p>
 662      * The overall effect is exactly as if the argument were converted
 663      * to a string by the method {@link String#valueOf(char[])},
 664      * and the characters of that string were then
 665      * {@link #append(String) appended} to this character sequence.
 666      *
 667      * @param   str   the characters to be appended.
 668      * @return  a reference to this object.
 669      */
 670     public AbstractStringBuilder append(char[] str) {
 671         int len = str.length;
 672         ensureCapacityInternal(count + len);
 673         appendChars(str, 0, len);
 674         return this;
 675     }
 676 
 677     /**
 678      * Appends the string representation of a subarray of the
 679      * {@code char} array argument to this sequence.
 680      * <p>
 681      * Characters of the {@code char} array {@code str}, starting at
 682      * index {@code offset}, are appended, in order, to the contents
 683      * of this sequence. The length of this sequence increases
 684      * by the value of {@code len}.
 685      * <p>
 686      * The overall effect is exactly as if the arguments were converted
 687      * to a string by the method {@link String#valueOf(char[],int,int)},
 688      * and the characters of that string were then
 689      * {@link #append(String) appended} to this character sequence.
 690      *
 691      * @param   str      the characters to be appended.
 692      * @param   offset   the index of the first {@code char} to append.
 693      * @param   len      the number of {@code char}s to append.
 694      * @return  a reference to this object.
 695      * @throws IndexOutOfBoundsException
 696      *         if {@code offset < 0} or {@code len < 0}
 697      *         or {@code offset+len > str.length}
 698      */
 699     public AbstractStringBuilder append(char str[], int offset, int len) {
 700         int end = offset + len;
 701         checkRange(offset, end, str.length);
 702         ensureCapacityInternal(count + len);
 703         appendChars(str, offset, end);
 704         return this;
 705     }
 706 
 707     /**
 708      * Appends the string representation of the {@code boolean}
 709      * argument to the sequence.
 710      * <p>
 711      * The overall effect is exactly as if the argument were converted
 712      * to a string by the method {@link String#valueOf(boolean)},
 713      * and the characters of that string were then
 714      * {@link #append(String) appended} to this character sequence.
 715      *
 716      * @param   b   a {@code boolean}.
 717      * @return  a reference to this object.
 718      */
 719     public AbstractStringBuilder append(boolean b) {
 720         ensureCapacityInternal(count + (b ? 4 : 5));
 721         int count = this.count;
 722         byte[] val = this.value;
 723         if (isLatin1()) {
 724             if (b) {
 725                 val[count++] = 't';
 726                 val[count++] = 'r';
 727                 val[count++] = 'u';
 728                 val[count++] = 'e';
 729             } else {
 730                 val[count++] = 'f';
 731                 val[count++] = 'a';
 732                 val[count++] = 'l';
 733                 val[count++] = 's';
 734                 val[count++] = 'e';
 735             }
 736         } else {
 737             if (b) {
 738                 count = StringUTF16.putCharsAt(val, count, 't', 'r', 'u', 'e');
 739             } else {
 740                 count = StringUTF16.putCharsAt(val, count, 'f', 'a', 'l', 's', 'e');
 741             }
 742         }
 743         this.count = count;
 744         return this;
 745     }
 746 
 747     /**
 748      * Appends the string representation of the {@code char}
 749      * argument to this sequence.
 750      * <p>
 751      * The argument is appended to the contents of this sequence.
 752      * The length of this sequence increases by {@code 1}.
 753      * <p>
 754      * The overall effect is exactly as if the argument were converted
 755      * to a string by the method {@link String#valueOf(char)},
 756      * and the character in that string were then
 757      * {@link #append(String) appended} to this character sequence.
 758      *
 759      * @param   c   a {@code char}.
 760      * @return  a reference to this object.
 761      */
 762     @Override
 763     public AbstractStringBuilder append(char c) {
 764         ensureCapacityInternal(count + 1);
 765         if (isLatin1() && StringLatin1.canEncode(c)) {
 766             value[count++] = (byte)c;
 767         } else {
 768             if (isLatin1()) {
 769                 inflate();
 770             }
 771             StringUTF16.putCharSB(value, count++, c);
 772         }
 773         return this;
 774     }
 775 
 776     /**
 777      * Appends the string representation of the {@code int}
 778      * argument to this sequence.
 779      * <p>
 780      * The overall effect is exactly as if the argument were converted
 781      * to a string by the method {@link String#valueOf(int)},
 782      * and the characters of that string were then
 783      * {@link #append(String) appended} to this character sequence.
 784      *
 785      * @param   i   an {@code int}.
 786      * @return  a reference to this object.
 787      */
 788     public AbstractStringBuilder append(int i) {
 789         int count = this.count;
 790         int spaceNeeded = count + Integer.stringSize(i);
 791         ensureCapacityInternal(spaceNeeded);
 792         if (isLatin1()) {
 793             Integer.getChars(i, spaceNeeded, value);
 794         } else {
 795             StringUTF16.getChars(i, count, spaceNeeded, value);
 796         }
 797         this.count = spaceNeeded;
 798         return this;
 799     }
 800 
 801     /**
 802      * Appends the string representation of the {@code long}
 803      * argument to this sequence.
 804      * <p>
 805      * The overall effect is exactly as if the argument were converted
 806      * to a string by the method {@link String#valueOf(long)},
 807      * and the characters of that string were then
 808      * {@link #append(String) appended} to this character sequence.
 809      *
 810      * @param   l   a {@code long}.
 811      * @return  a reference to this object.
 812      */
 813     public AbstractStringBuilder append(long l) {
 814         int count = this.count;
 815         int spaceNeeded = count + Long.stringSize(l);
 816         ensureCapacityInternal(spaceNeeded);
 817         if (isLatin1()) {
 818             Long.getChars(l, spaceNeeded, value);
 819         } else {
 820             StringUTF16.getChars(l, count, spaceNeeded, value);
 821         }
 822         this.count = spaceNeeded;
 823         return this;
 824     }
 825 
 826     /**
 827      * Appends the string representation of the {@code float}
 828      * argument to this sequence.
 829      * <p>
 830      * The overall effect is exactly as if the argument were converted
 831      * to a string by the method {@link String#valueOf(float)},
 832      * and the characters of that string were then
 833      * {@link #append(String) appended} to this character sequence.
 834      *
 835      * @param   f   a {@code float}.
 836      * @return  a reference to this object.
 837      */
 838     public AbstractStringBuilder append(float f) {
 839         FloatingDecimal.appendTo(f,this);
 840         return this;
 841     }
 842 
 843     /**
 844      * Appends the string representation of the {@code double}
 845      * argument to this sequence.
 846      * <p>
 847      * The overall effect is exactly as if the argument were converted
 848      * to a string by the method {@link String#valueOf(double)},
 849      * and the characters of that string were then
 850      * {@link #append(String) appended} to this character sequence.
 851      *
 852      * @param   d   a {@code double}.
 853      * @return  a reference to this object.
 854      */
 855     public AbstractStringBuilder append(double d) {
 856         FloatingDecimal.appendTo(d,this);
 857         return this;
 858     }
 859 
 860     /**
 861      * Removes the characters in a substring of this sequence.
 862      * The substring begins at the specified {@code start} and extends to
 863      * the character at index {@code end - 1} or to the end of the
 864      * sequence if no such character exists. If
 865      * {@code start} is equal to {@code end}, no changes are made.
 866      *
 867      * @param      start  The beginning index, inclusive.
 868      * @param      end    The ending index, exclusive.
 869      * @return     This object.
 870      * @throws     StringIndexOutOfBoundsException  if {@code start}
 871      *             is negative, greater than {@code length()}, or
 872      *             greater than {@code end}.
 873      */
 874     public AbstractStringBuilder delete(int start, int end) {
 875         int count = this.count;
 876         if (end > count) {
 877             end = count;
 878         }
 879         checkRangeSIOOBE(start, end, count);
 880         int len = end - start;
 881         if (len > 0) {
 882             shift(end, -len);
 883             this.count = count - len;
 884         }
 885         return this;
 886     }
 887 
 888     /**
 889      * Appends the string representation of the {@code codePoint}
 890      * argument to this sequence.
 891      *
 892      * <p> The argument is appended to the contents of this sequence.
 893      * The length of this sequence increases by
 894      * {@link Character#charCount(int) Character.charCount(codePoint)}.
 895      *
 896      * <p> The overall effect is exactly as if the argument were
 897      * converted to a {@code char} array by the method
 898      * {@link Character#toChars(int)} and the character in that array
 899      * were then {@link #append(char[]) appended} to this character
 900      * sequence.
 901      *
 902      * @param   codePoint   a Unicode code point
 903      * @return  a reference to this object.
 904      * @throws    IllegalArgumentException if the specified
 905      * {@code codePoint} isn't a valid Unicode code point
 906      */
 907     public AbstractStringBuilder appendCodePoint(int codePoint) {
 908         if (Character.isBmpCodePoint(codePoint)) {
 909             return append((char)codePoint);
 910         }
 911         return append(Character.toChars(codePoint));
 912     }
 913 
 914     /**
 915      * Removes the {@code char} at the specified position in this
 916      * sequence. This sequence is shortened by one {@code char}.
 917      *
 918      * <p>Note: If the character at the given index is a supplementary
 919      * character, this method does not remove the entire character. If
 920      * correct handling of supplementary characters is required,
 921      * determine the number of {@code char}s to remove by calling
 922      * {@code Character.charCount(thisSequence.codePointAt(index))},
 923      * where {@code thisSequence} is this sequence.
 924      *
 925      * @param       index  Index of {@code char} to remove
 926      * @return      This object.
 927      * @throws      StringIndexOutOfBoundsException  if the {@code index}
 928      *              is negative or greater than or equal to
 929      *              {@code length()}.
 930      */
 931     public AbstractStringBuilder deleteCharAt(int index) {
 932         checkIndex(index, count);
 933         shift(index + 1, -1);
 934         count--;
 935         return this;
 936     }
 937 
 938     /**
 939      * Replaces the characters in a substring of this sequence
 940      * with characters in the specified {@code String}. The substring
 941      * begins at the specified {@code start} and extends to the character
 942      * at index {@code end - 1} or to the end of the
 943      * sequence if no such character exists. First the
 944      * characters in the substring are removed and then the specified
 945      * {@code String} is inserted at {@code start}. (This
 946      * sequence will be lengthened to accommodate the
 947      * specified String if necessary.)
 948      *
 949      * @param      start    The beginning index, inclusive.
 950      * @param      end      The ending index, exclusive.
 951      * @param      str   String that will replace previous contents.
 952      * @return     This object.
 953      * @throws     StringIndexOutOfBoundsException  if {@code start}
 954      *             is negative, greater than {@code length()}, or
 955      *             greater than {@code end}.
 956      */
 957     public AbstractStringBuilder replace(int start, int end, String str) {
 958         int count = this.count;
 959         if (end > count) {
 960             end = count;
 961         }
 962         checkRangeSIOOBE(start, end, count);
 963         int len = str.length();
 964         int newCount = count + len - (end - start);
 965         ensureCapacityInternal(newCount);
 966         shift(end, newCount - count);
 967         this.count = newCount;
 968         putStringAt(start, str);
 969         return this;
 970     }
 971 
 972     /**
 973      * Returns a new {@code String} that contains a subsequence of
 974      * characters currently contained in this character sequence. The
 975      * substring begins at the specified index and extends to the end of
 976      * this sequence.
 977      *
 978      * @param      start    The beginning index, inclusive.
 979      * @return     The new string.
 980      * @throws     StringIndexOutOfBoundsException  if {@code start} is
 981      *             less than zero, or greater than the length of this object.
 982      */
 983     public String substring(int start) {
 984         return substring(start, count);
 985     }
 986 
 987     /**
 988      * Returns a new character sequence that is a subsequence of this sequence.
 989      *
 990      * <p> An invocation of this method of the form
 991      *
 992      * <pre>{@code
 993      * sb.subSequence(begin,&nbsp;end)}</pre>
 994      *
 995      * behaves in exactly the same way as the invocation
 996      *
 997      * <pre>{@code
 998      * sb.substring(begin,&nbsp;end)}</pre>
 999      *
1000      * This method is provided so that this class can
1001      * implement the {@link CharSequence} interface.
1002      *
1003      * @param      start   the start index, inclusive.
1004      * @param      end     the end index, exclusive.
1005      * @return     the specified subsequence.
1006      *
1007      * @throws  IndexOutOfBoundsException
1008      *          if {@code start} or {@code end} are negative,
1009      *          if {@code end} is greater than {@code length()},
1010      *          or if {@code start} is greater than {@code end}
1011      * @spec JSR-51
1012      */
1013     @Override
1014     public CharSequence subSequence(int start, int end) {
1015         return substring(start, end);
1016     }
1017 
1018     /**
1019      * Returns a new {@code String} that contains a subsequence of
1020      * characters currently contained in this sequence. The
1021      * substring begins at the specified {@code start} and
1022      * extends to the character at index {@code end - 1}.
1023      *
1024      * @param      start    The beginning index, inclusive.
1025      * @param      end      The ending index, exclusive.
1026      * @return     The new string.
1027      * @throws     StringIndexOutOfBoundsException  if {@code start}
1028      *             or {@code end} are negative or greater than
1029      *             {@code length()}, or {@code start} is
1030      *             greater than {@code end}.
1031      */
1032     public String substring(int start, int end) {
1033         checkRangeSIOOBE(start, end, count);
1034         if (isLatin1()) {
1035             return StringLatin1.newString(value, start, end - start);
1036         }
1037         return StringUTF16.newString(value, start, end - start);
1038     }
1039 
1040     private void shift(int offset, int n) {
1041         System.arraycopy(value, offset << coder,
1042                          value, (offset + n) << coder, (count - offset) << coder);
1043     }
1044 
1045     /**
1046      * Inserts the string representation of a subarray of the {@code str}
1047      * array argument into this sequence. The subarray begins at the
1048      * specified {@code offset} and extends {@code len} {@code char}s.
1049      * The characters of the subarray are inserted into this sequence at
1050      * the position indicated by {@code index}. The length of this
1051      * sequence increases by {@code len} {@code char}s.
1052      *
1053      * @param      index    position at which to insert subarray.
1054      * @param      str       A {@code char} array.
1055      * @param      offset   the index of the first {@code char} in subarray to
1056      *             be inserted.
1057      * @param      len      the number of {@code char}s in the subarray to
1058      *             be inserted.
1059      * @return     This object
1060      * @throws     StringIndexOutOfBoundsException  if {@code index}
1061      *             is negative or greater than {@code length()}, or
1062      *             {@code offset} or {@code len} are negative, or
1063      *             {@code (offset+len)} is greater than
1064      *             {@code str.length}.
1065      */
1066     public AbstractStringBuilder insert(int index, char[] str, int offset,
1067                                         int len)
1068     {
1069         checkOffset(index, count);
1070         checkRangeSIOOBE(offset, offset + len, str.length);
1071         ensureCapacityInternal(count + len);
1072         shift(index, len);
1073         count += len;
1074         putCharsAt(index, str, offset, offset + len);
1075         return this;
1076     }
1077 
1078     /**
1079      * Inserts the string representation of the {@code Object}
1080      * argument into this character sequence.
1081      * <p>
1082      * The overall effect is exactly as if the second argument were
1083      * converted to a string by the method {@link String#valueOf(Object)},
1084      * and the characters of that string were then
1085      * {@link #insert(int,String) inserted} into this character
1086      * sequence at the indicated offset.
1087      * <p>
1088      * The {@code offset} argument must be greater than or equal to
1089      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1090      * of this sequence.
1091      *
1092      * @param      offset   the offset.
1093      * @param      obj      an {@code Object}.
1094      * @return     a reference to this object.
1095      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1096      */
1097     public AbstractStringBuilder insert(int offset, Object obj) {
1098         return insert(offset, String.valueOf(obj));
1099     }
1100 
1101     /**
1102      * Inserts the string into this character sequence.
1103      * <p>
1104      * The characters of the {@code String} argument are inserted, in
1105      * order, into this sequence at the indicated offset, moving up any
1106      * characters originally above that position and increasing the length
1107      * of this sequence by the length of the argument. If
1108      * {@code str} is {@code null}, then the four characters
1109      * {@code "null"} are inserted into this sequence.
1110      * <p>
1111      * The character at index <i>k</i> in the new character sequence is
1112      * equal to:
1113      * <ul>
1114      * <li>the character at index <i>k</i> in the old character sequence, if
1115      * <i>k</i> is less than {@code offset}
1116      * <li>the character at index <i>k</i>{@code -offset} in the
1117      * argument {@code str}, if <i>k</i> is not less than
1118      * {@code offset} but is less than {@code offset+str.length()}
1119      * <li>the character at index <i>k</i>{@code -str.length()} in the
1120      * old character sequence, if <i>k</i> is not less than
1121      * {@code offset+str.length()}
1122      * </ul><p>
1123      * The {@code offset} argument must be greater than or equal to
1124      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1125      * of this sequence.
1126      *
1127      * @param      offset   the offset.
1128      * @param      str      a string.
1129      * @return     a reference to this object.
1130      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1131      */
1132     public AbstractStringBuilder insert(int offset, String str) {
1133         checkOffset(offset, count);
1134         if (str == null) {
1135             str = "null";
1136         }
1137         int len = str.length();
1138         ensureCapacityInternal(count + len);
1139         shift(offset, len);
1140         count += len;
1141         putStringAt(offset, str);
1142         return this;
1143     }
1144 
1145     /**
1146      * Inserts the string representation of the {@code char} array
1147      * argument into this sequence.
1148      * <p>
1149      * The characters of the array argument are inserted into the
1150      * contents of this sequence at the position indicated by
1151      * {@code offset}. The length of this sequence increases by
1152      * the length of the argument.
1153      * <p>
1154      * The overall effect is exactly as if the second argument were
1155      * converted to a string by the method {@link String#valueOf(char[])},
1156      * and the characters of that string were then
1157      * {@link #insert(int,String) inserted} into this character
1158      * sequence at the indicated offset.
1159      * <p>
1160      * The {@code offset} argument must be greater than or equal to
1161      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1162      * of this sequence.
1163      *
1164      * @param      offset   the offset.
1165      * @param      str      a character array.
1166      * @return     a reference to this object.
1167      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1168      */
1169     public AbstractStringBuilder insert(int offset, char[] str) {
1170         checkOffset(offset, count);
1171         int len = str.length;
1172         ensureCapacityInternal(count + len);
1173         shift(offset, len);
1174         count += len;
1175         putCharsAt(offset, str, 0, len);
1176         return this;
1177     }
1178 
1179     /**
1180      * Inserts the specified {@code CharSequence} into this sequence.
1181      * <p>
1182      * The characters of the {@code CharSequence} argument are inserted,
1183      * in order, into this sequence at the indicated offset, moving up
1184      * any characters originally above that position and increasing the length
1185      * of this sequence by the length of the argument s.
1186      * <p>
1187      * The result of this method is exactly the same as if it were an
1188      * invocation of this object's
1189      * {@link #insert(int,CharSequence,int,int) insert}(dstOffset, s, 0, s.length())
1190      * method.
1191      *
1192      * <p>If {@code s} is {@code null}, then the four characters
1193      * {@code "null"} are inserted into this sequence.
1194      *
1195      * @param      dstOffset   the offset.
1196      * @param      s the sequence to be inserted
1197      * @return     a reference to this object.
1198      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1199      */
1200     public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
1201         if (s == null) {
1202             s = "null";
1203         }
1204         if (s instanceof String) {
1205             return this.insert(dstOffset, (String)s);
1206         }
1207         return this.insert(dstOffset, s, 0, s.length());
1208     }
1209 
1210     /**
1211      * Inserts a subsequence of the specified {@code CharSequence} into
1212      * this sequence.
1213      * <p>
1214      * The subsequence of the argument {@code s} specified by
1215      * {@code start} and {@code end} are inserted,
1216      * in order, into this sequence at the specified destination offset, moving
1217      * up any characters originally above that position. The length of this
1218      * sequence is increased by {@code end - start}.
1219      * <p>
1220      * The character at index <i>k</i> in this sequence becomes equal to:
1221      * <ul>
1222      * <li>the character at index <i>k</i> in this sequence, if
1223      * <i>k</i> is less than {@code dstOffset}
1224      * <li>the character at index <i>k</i>{@code +start-dstOffset} in
1225      * the argument {@code s}, if <i>k</i> is greater than or equal to
1226      * {@code dstOffset} but is less than {@code dstOffset+end-start}
1227      * <li>the character at index <i>k</i>{@code -(end-start)} in this
1228      * sequence, if <i>k</i> is greater than or equal to
1229      * {@code dstOffset+end-start}
1230      * </ul><p>
1231      * The {@code dstOffset} argument must be greater than or equal to
1232      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1233      * of this sequence.
1234      * <p>The start argument must be nonnegative, and not greater than
1235      * {@code end}.
1236      * <p>The end argument must be greater than or equal to
1237      * {@code start}, and less than or equal to the length of s.
1238      *
1239      * <p>If {@code s} is {@code null}, then this method inserts
1240      * characters as if the s parameter was a sequence containing the four
1241      * characters {@code "null"}.
1242      *
1243      * @param      dstOffset   the offset in this sequence.
1244      * @param      s       the sequence to be inserted.
1245      * @param      start   the starting index of the subsequence to be inserted.
1246      * @param      end     the end index of the subsequence to be inserted.
1247      * @return     a reference to this object.
1248      * @throws     IndexOutOfBoundsException  if {@code dstOffset}
1249      *             is negative or greater than {@code this.length()}, or
1250      *              {@code start} or {@code end} are negative, or
1251      *              {@code start} is greater than {@code end} or
1252      *              {@code end} is greater than {@code s.length()}
1253      */
1254     public AbstractStringBuilder insert(int dstOffset, CharSequence s,
1255                                         int start, int end)
1256     {
1257         if (s == null) {
1258             s = "null";
1259         }
1260         checkOffset(dstOffset, count);
1261         checkRange(start, end, s.length());
1262         int len = end - start;
1263         ensureCapacityInternal(count + len);
1264         shift(dstOffset, len);
1265         count += len;
1266         putCharsAt(dstOffset, s, start, end);
1267         return this;
1268     }
1269 
1270     /**
1271      * Inserts the string representation of the {@code boolean}
1272      * argument into this sequence.
1273      * <p>
1274      * The overall effect is exactly as if the second argument were
1275      * converted to a string by the method {@link String#valueOf(boolean)},
1276      * and the characters of that string were then
1277      * {@link #insert(int,String) inserted} into this character
1278      * sequence at the indicated offset.
1279      * <p>
1280      * The {@code offset} argument must be greater than or equal to
1281      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1282      * of this sequence.
1283      *
1284      * @param      offset   the offset.
1285      * @param      b        a {@code boolean}.
1286      * @return     a reference to this object.
1287      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1288      */
1289     public AbstractStringBuilder insert(int offset, boolean b) {
1290         return insert(offset, String.valueOf(b));
1291     }
1292 
1293     /**
1294      * Inserts the string representation of the {@code char}
1295      * argument into this sequence.
1296      * <p>
1297      * The overall effect is exactly as if the second argument were
1298      * converted to a string by the method {@link String#valueOf(char)},
1299      * and the character in that string were then
1300      * {@link #insert(int,String) inserted} into this character
1301      * sequence at the indicated offset.
1302      * <p>
1303      * The {@code offset} argument must be greater than or equal to
1304      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1305      * of this sequence.
1306      *
1307      * @param      offset   the offset.
1308      * @param      c        a {@code char}.
1309      * @return     a reference to this object.
1310      * @throws     IndexOutOfBoundsException  if the offset is invalid.
1311      */
1312     public AbstractStringBuilder insert(int offset, char c) {
1313         checkOffset(offset, count);
1314         ensureCapacityInternal(count + 1);
1315         shift(offset, 1);
1316         count += 1;
1317         if (isLatin1() && StringLatin1.canEncode(c)) {
1318             value[offset] = (byte)c;
1319         } else {
1320             if (isLatin1()) {
1321                 inflate();
1322             }
1323             StringUTF16.putCharSB(value, offset, c);
1324         }
1325         return this;
1326     }
1327 
1328     /**
1329      * Inserts the string representation of the second {@code int}
1330      * argument into this sequence.
1331      * <p>
1332      * The overall effect is exactly as if the second argument were
1333      * converted to a string by the method {@link String#valueOf(int)},
1334      * and the characters of that string were then
1335      * {@link #insert(int,String) inserted} into this character
1336      * sequence at the indicated offset.
1337      * <p>
1338      * The {@code offset} argument must be greater than or equal to
1339      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1340      * of this sequence.
1341      *
1342      * @param      offset   the offset.
1343      * @param      i        an {@code int}.
1344      * @return     a reference to this object.
1345      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1346      */
1347     public AbstractStringBuilder insert(int offset, int i) {
1348         return insert(offset, String.valueOf(i));
1349     }
1350 
1351     /**
1352      * Inserts the string representation of the {@code long}
1353      * argument into this sequence.
1354      * <p>
1355      * The overall effect is exactly as if the second argument were
1356      * converted to a string by the method {@link String#valueOf(long)},
1357      * and the characters of that string were then
1358      * {@link #insert(int,String) inserted} into this character
1359      * sequence at the indicated offset.
1360      * <p>
1361      * The {@code offset} argument must be greater than or equal to
1362      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1363      * of this sequence.
1364      *
1365      * @param      offset   the offset.
1366      * @param      l        a {@code long}.
1367      * @return     a reference to this object.
1368      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1369      */
1370     public AbstractStringBuilder insert(int offset, long l) {
1371         return insert(offset, String.valueOf(l));
1372     }
1373 
1374     /**
1375      * Inserts the string representation of the {@code float}
1376      * argument into this sequence.
1377      * <p>
1378      * The overall effect is exactly as if the second argument were
1379      * converted to a string by the method {@link String#valueOf(float)},
1380      * and the characters of that string were then
1381      * {@link #insert(int,String) inserted} into this character
1382      * sequence at the indicated offset.
1383      * <p>
1384      * The {@code offset} argument must be greater than or equal to
1385      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1386      * of this sequence.
1387      *
1388      * @param      offset   the offset.
1389      * @param      f        a {@code float}.
1390      * @return     a reference to this object.
1391      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1392      */
1393     public AbstractStringBuilder insert(int offset, float f) {
1394         return insert(offset, String.valueOf(f));
1395     }
1396 
1397     /**
1398      * Inserts the string representation of the {@code double}
1399      * argument into this sequence.
1400      * <p>
1401      * The overall effect is exactly as if the second argument were
1402      * converted to a string by the method {@link String#valueOf(double)},
1403      * and the characters of that string were then
1404      * {@link #insert(int,String) inserted} into this character
1405      * sequence at the indicated offset.
1406      * <p>
1407      * The {@code offset} argument must be greater than or equal to
1408      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1409      * of this sequence.
1410      *
1411      * @param      offset   the offset.
1412      * @param      d        a {@code double}.
1413      * @return     a reference to this object.
1414      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1415      */
1416     public AbstractStringBuilder insert(int offset, double d) {
1417         return insert(offset, String.valueOf(d));
1418     }
1419 
1420     /**
1421      * Returns the index within this string of the first occurrence of the
1422      * specified substring.
1423      *
1424      * <p>The returned index is the smallest value {@code k} for which:
1425      * <pre>{@code
1426      * this.toString().startsWith(str, k)
1427      * }</pre>
1428      * If no such value of {@code k} exists, then {@code -1} is returned.
1429      *
1430      * @param   str   the substring to search for.
1431      * @return  the index of the first occurrence of the specified substring,
1432      *          or {@code -1} if there is no such occurrence.
1433      */
1434     public int indexOf(String str) {
1435         return indexOf(str, 0);
1436     }
1437 
1438     /**
1439      * Returns the index within this string of the first occurrence of the
1440      * specified substring, starting at the specified index.
1441      *
1442      * <p>The returned index is the smallest value {@code k} for which:
1443      * <pre>{@code
1444      *     k >= Math.min(fromIndex, this.length()) &&
1445      *                   this.toString().startsWith(str, k)
1446      * }</pre>
1447      * If no such value of {@code k} exists, then {@code -1} is returned.
1448      *
1449      * @param   str         the substring to search for.
1450      * @param   fromIndex   the index from which to start the search.
1451      * @return  the index of the first occurrence of the specified substring,
1452      *          starting at the specified index,
1453      *          or {@code -1} if there is no such occurrence.
1454      */
1455     public int indexOf(String str, int fromIndex) {
1456         return String.indexOf(value, coder, count, str, fromIndex);
1457     }
1458 
1459     /**
1460      * Returns the index within this string of the last occurrence of the
1461      * specified substring.  The last occurrence of the empty string "" is
1462      * considered to occur at the index value {@code this.length()}.
1463      *
1464      * <p>The returned index is the largest value {@code k} for which:
1465      * <pre>{@code
1466      * this.toString().startsWith(str, k)
1467      * }</pre>
1468      * If no such value of {@code k} exists, then {@code -1} is returned.
1469      *
1470      * @param   str   the substring to search for.
1471      * @return  the index of the last occurrence of the specified substring,
1472      *          or {@code -1} if there is no such occurrence.
1473      */
1474     public int lastIndexOf(String str) {
1475         return lastIndexOf(str, count);
1476     }
1477 
1478     /**
1479      * Returns the index within this string of the last occurrence of the
1480      * specified substring, searching backward starting at the specified index.
1481      *
1482      * <p>The returned index is the largest value {@code k} for which:
1483      * <pre>{@code
1484      *     k <= Math.min(fromIndex, this.length()) &&
1485      *                   this.toString().startsWith(str, k)
1486      * }</pre>
1487      * If no such value of {@code k} exists, then {@code -1} is returned.
1488      *
1489      * @param   str         the substring to search for.
1490      * @param   fromIndex   the index to start the search from.
1491      * @return  the index of the last occurrence of the specified substring,
1492      *          searching backward from the specified index,
1493      *          or {@code -1} if there is no such occurrence.
1494      */
1495     public int lastIndexOf(String str, int fromIndex) {
1496         return String.lastIndexOf(value, coder, count, str, fromIndex);
1497     }
1498 
1499     /**
1500      * Causes this character sequence to be replaced by the reverse of
1501      * the sequence. If there are any surrogate pairs included in the
1502      * sequence, these are treated as single characters for the
1503      * reverse operation. Thus, the order of the high-low surrogates
1504      * is never reversed.
1505      *
1506      * Let <i>n</i> be the character length of this character sequence
1507      * (not the length in {@code char} values) just prior to
1508      * execution of the {@code reverse} method. Then the
1509      * character at index <i>k</i> in the new character sequence is
1510      * equal to the character at index <i>n-k-1</i> in the old
1511      * character sequence.
1512      *
1513      * <p>Note that the reverse operation may result in producing
1514      * surrogate pairs that were unpaired low-surrogates and
1515      * high-surrogates before the operation. For example, reversing
1516      * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
1517      * a valid surrogate pair.
1518      *
1519      * @return  a reference to this object.
1520      */
1521     public AbstractStringBuilder reverse() {
1522         byte[] val = this.value;
1523         int count = this.count;
1524         int coder = this.coder;
1525         int n = count - 1;
1526         if (COMPACT_STRINGS && coder == LATIN1) {
1527             for (int j = (n-1) >> 1; j >= 0; j--) {
1528                 int k = n - j;
1529                 byte cj = val[j];
1530                 val[j] = val[k];
1531                 val[k] = cj;
1532             }
1533         } else {
1534             StringUTF16.reverse(val, count);
1535         }
1536         return this;
1537     }
1538 
1539     /**
1540      * Returns a string representing the data in this sequence.
1541      * A new {@code String} object is allocated and initialized to
1542      * contain the character sequence currently represented by this
1543      * object. This {@code String} is then returned. Subsequent
1544      * changes to this sequence do not affect the contents of the
1545      * {@code String}.
1546      *
1547      * @return  a string representation of this sequence of characters.
1548      */
1549     @Override
1550     public abstract String toString();
1551 
1552     /**
1553      * {@inheritDoc}
1554      * @since 9
1555      */
1556     @Override
1557     public IntStream chars() {
1558         // Reuse String-based spliterator. This requires a supplier to
1559         // capture the value and count when the terminal operation is executed
1560         return StreamSupport.intStream(
1561                 () -> {
1562                     // The combined set of field reads are not atomic and thread
1563                     // safe but bounds checks will ensure no unsafe reads from
1564                     // the byte array
1565                     byte[] val = this.value;
1566                     int count = this.count;
1567                     byte coder = this.coder;
1568                     return coder == LATIN1
1569                            ? new StringLatin1.CharsSpliterator(val, 0, count, 0)
1570                            : new StringUTF16.CharsSpliterator(val, 0, count, 0);
1571                 },
1572                 Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED,
1573                 false);
1574     }
1575 
1576     /**
1577      * {@inheritDoc}
1578      * @since 9
1579      */
1580     @Override
1581     public IntStream codePoints() {
1582         // Reuse String-based spliterator. This requires a supplier to
1583         // capture the value and count when the terminal operation is executed
1584         return StreamSupport.intStream(
1585                 () -> {
1586                     // The combined set of field reads are not atomic and thread
1587                     // safe but bounds checks will ensure no unsafe reads from
1588                     // the byte array
1589                     byte[] val = this.value;
1590                     int count = this.count;
1591                     byte coder = this.coder;
1592                     return coder == LATIN1
1593                            ? new StringLatin1.CharsSpliterator(val, 0, count, 0)
1594                            : new StringUTF16.CodePointsSpliterator(val, 0, count, 0);
1595                 },
1596                 Spliterator.ORDERED,
1597                 false);
1598     }
1599 
1600     /**
1601      * Needed by {@code String} for the contentEquals method.
1602      */
1603     final byte[] getValue() {
1604         return value;
1605     }
1606 
1607     /*
1608      * Invoker guarantees it is in UTF16 (inflate itself for asb), if two
1609      * coders are different and the dstBegin has enough space
1610      *
1611      * @param dstBegin  the char index, not offset of byte[]
1612      * @param coder     the coder of dst[]
1613      */
1614     void getBytes(byte dst[], int dstBegin, byte coder) {
1615         if (this.coder == coder) {
1616             System.arraycopy(value, 0, dst, dstBegin << coder, count << coder);
1617         } else {        // this.coder == LATIN && coder == UTF16
1618             StringLatin1.inflate(value, 0, dst, dstBegin, count);
1619         }
1620     }
1621 
1622     /* for readObject() */
1623     void initBytes(char[] value, int off, int len) {
1624         if (String.COMPACT_STRINGS) {
1625             this.value = StringUTF16.compress(value, off, len);
1626             if (this.value != null) {
1627                 this.coder = LATIN1;
1628                 return;
1629             }
1630         }
1631         this.coder = UTF16;
1632         this.value = StringUTF16.toBytes(value, off, len);
1633     }
1634 
1635     final byte getCoder() {
1636         return COMPACT_STRINGS ? coder : UTF16;
1637     }
1638 
1639     final boolean isLatin1() {
1640         return COMPACT_STRINGS && coder == LATIN1;
1641     }
1642 
1643     private final void putCharsAt(int index, char[] s, int off, int end) {
1644         if (isLatin1()) {
1645             byte[] val = this.value;
1646             for (int i = off, j = index; i < end; i++) {
1647                 char c = s[i];
1648                 if (StringLatin1.canEncode(c)) {
1649                     val[j++] = (byte)c;
1650                 } else {
1651                     inflate();
1652                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1653                     return;
1654                 }
1655             }
1656         } else {
1657             StringUTF16.putCharsSB(this.value, index, s, off, end);
1658         }
1659     }
1660 
1661     private final void putCharsAt(int index, CharSequence s, int off, int end) {
1662         if (isLatin1()) {
1663             byte[] val = this.value;
1664             for (int i = off, j = index; i < end; i++) {
1665                 char c = s.charAt(i);
1666                 if (StringLatin1.canEncode(c)) {
1667                     val[j++] = (byte)c;
1668                 } else {
1669                     inflate();
1670                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1671                     return;
1672                 }
1673             }
1674         } else {
1675             StringUTF16.putCharsSB(this.value, index, s, off, end);
1676         }
1677     }
1678 
1679     private final void putStringAt(int index, String str) {
1680         if (getCoder() != str.coder()) {
1681             inflate();
1682         }
1683         str.getBytes(value, index, coder);
1684     }
1685 
1686     private final void appendChars(char[] s, int off, int end) {
1687         int count = this.count;
1688         if (isLatin1()) {
1689             byte[] val = this.value;
1690             for (int i = off, j = count; i < end; i++) {
1691                 char c = s[i];
1692                 if (StringLatin1.canEncode(c)) {
1693                     val[j++] = (byte)c;
1694                 } else {
1695                     this.count = count = j;
1696                     inflate();
1697                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1698                     this.count = count + end - i;
1699                     return;
1700                 }
1701             }
1702         } else {
1703             StringUTF16.putCharsSB(this.value, count, s, off, end);
1704         }
1705         this.count = count + end - off;
1706     }
1707 
1708     private final void appendChars(CharSequence s, int off, int end) {
1709         if (isLatin1()) {
1710             byte[] val = this.value;
1711             for (int i = off, j = count; i < end; i++) {
1712                 char c = s.charAt(i);
1713                 if (StringLatin1.canEncode(c)) {
1714                     val[j++] = (byte)c;
1715                 } else {
1716                     count = j;
1717                     inflate();
1718                     StringUTF16.putCharsSB(this.value, j, s, i, end);
1719                     count += end - i;
1720                     return;
1721                 }
1722             }
1723         } else {
1724             StringUTF16.putCharsSB(this.value, count, s, off, end);
1725         }
1726         count += end - off;
1727     }
1728 
1729     /* IndexOutOfBoundsException, if out of bounds */
1730     private static void checkRange(int start, int end, int len) {
1731         if (start < 0 || start > end || end > len) {
1732             throw new IndexOutOfBoundsException(
1733                 "start " + start + ", end " + end + ", length " + len);
1734         }
1735     }
1736 
1737     /* StringIndexOutOfBoundsException, if out of bounds */
1738     private static void checkRangeSIOOBE(int start, int end, int len) {
1739         if (start < 0 || start > end || end > len) {
1740             throw new StringIndexOutOfBoundsException(
1741                 "start " + start + ", end " + end + ", length " + len);
1742         }
1743     }
1744 
1745     /**
1746      * Determine the "coder" of the given CharSequence
1747      */
1748     static byte getCharSequenceCoder(CharSequence seq) {
1749         byte coder;
1750         if (seq instanceof String) {
1751             coder = ((String)seq).coder();
1752         } else if (seq instanceof AbstractStringBuilder) {
1753             coder = ((AbstractStringBuilder)seq).getCoder();
1754         } else if (COMPACT_STRINGS) {
1755             coder = LATIN1;
1756         } else {
1757             coder = UTF16;
1758         }
1759         return coder;
1760     }
1761 }