1 /*
   2  * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import sun.misc.FloatingDecimal;
  29 import java.util.Arrays;
  30 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     }
 802 
 803     /**
 804      * Appends the string representation of the {@code double}
 805      * argument to this sequence.
 806      * <p>
 807      * The overall effect is exactly as if the argument were converted
 808      * to a string by the method {@link String#valueOf(double)},
 809      * and the characters of that string were then
 810      * {@link #append(String) appended} to this character sequence.
 811      *
 812      * @param   d   a {@code double}.
 813      * @return  a reference to this object.
 814      */
 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.
 947      *
 948      * <p> An invocation of this method of the form
 949      *
 950      * <pre>{@code
 951      * sb.subSequence(begin,&nbsp;end)}</pre>
 952      *
 953      * behaves in exactly the same way as the invocation
 954      *
 955      * <pre>{@code
 956      * sb.substring(begin,&nbsp;end)}</pre>
 957      *
 958      * This method is provided so that this class can
 959      * implement the {@link CharSequence} interface.
 960      *
 961      * @param      start   the start index, inclusive.
 962      * @param      end     the end index, exclusive.
 963      * @return     the specified subsequence.
 964      *
 965      * @throws  IndexOutOfBoundsException
 966      *          if {@code start} or {@code end} are negative,
 967      *          if {@code end} is greater than {@code length()},
 968      *          or if {@code start} is greater than {@code end}
 969      * @spec JSR-51
 970      */
 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.
1053      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1054      */
1055     public AbstractStringBuilder insert(int offset, Object obj) {
1056         return insert(offset, String.valueOf(obj));
1057     }
1058 
1059     /**
1060      * Inserts the string into this character sequence.
1061      * <p>
1062      * The characters of the {@code String} argument are inserted, in
1063      * order, into this sequence at the indicated offset, moving up any
1064      * characters originally above that position and increasing the length
1065      * of this sequence by the length of the argument. If
1066      * {@code str} is {@code null}, then the four characters
1067      * {@code "null"} are inserted into this sequence.
1068      * <p>
1069      * The character at index <i>k</i> in the new character sequence is
1070      * equal to:
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}
1185      * <li>the character at index <i>k</i>{@code -(end-start)} in this
1186      * sequence, if <i>k</i> is greater than or equal to
1187      * {@code dstOffset+end-start}
1188      * </ul><p>
1189      * The {@code dstOffset} argument must be greater than or equal to
1190      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1191      * of this sequence.
1192      * <p>The start argument must be nonnegative, and not greater than
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.
1245      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1246      */
1247     public AbstractStringBuilder insert(int offset, boolean b) {
1248         return insert(offset, String.valueOf(b));
1249     }
1250 
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.
1303      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1304      */
1305     public AbstractStringBuilder insert(int offset, int i) {
1306         return insert(offset, String.valueOf(i));
1307     }
1308 
1309     /**
1310      * Inserts the string representation of the {@code long}
1311      * argument into this sequence.
1312      * <p>
1313      * The overall effect is exactly as if the second argument were
1314      * converted to a string by the method {@link String#valueOf(long)},
1315      * and the characters of that string were then
1316      * {@link #insert(int,String) inserted} into this character
1317      * sequence at the indicated offset.
1318      * <p>
1319      * The {@code offset} argument must be greater than or equal to
1320      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1321      * of this sequence.
1322      *
1323      * @param      offset   the offset.
1324      * @param      l        a {@code long}.
1325      * @return     a reference to this object.
1326      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1327      */
1328     public AbstractStringBuilder insert(int offset, long l) {
1329         return insert(offset, String.valueOf(l));
1330     }
1331 
1332     /**
1333      * Inserts the string representation of the {@code float}
1334      * argument into this sequence.
1335      * <p>
1336      * The overall effect is exactly as if the second argument were
1337      * converted to a string by the method {@link String#valueOf(float)},
1338      * and the characters of that string were then
1339      * {@link #insert(int,String) inserted} into this character
1340      * sequence at the indicated offset.
1341      * <p>
1342      * The {@code offset} argument must be greater than or equal to
1343      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1344      * of this sequence.
1345      *
1346      * @param      offset   the offset.
1347      * @param      f        a {@code float}.
1348      * @return     a reference to this object.
1349      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1350      */
1351     public AbstractStringBuilder insert(int offset, float f) {
1352         return insert(offset, String.valueOf(f));
1353     }
1354 
1355     /**
1356      * Inserts the string representation of the {@code double}
1357      * argument into this sequence.
1358      * <p>
1359      * The overall effect is exactly as if the second argument were
1360      * converted to a string by the method {@link String#valueOf(double)},
1361      * and the characters of that string were then
1362      * {@link #insert(int,String) inserted} into this character
1363      * sequence at the indicated offset.
1364      * <p>
1365      * The {@code offset} argument must be greater than or equal to
1366      * {@code 0}, and less than or equal to the {@linkplain #length() length}
1367      * of this sequence.
1368      *
1369      * @param      offset   the offset.
1370      * @param      d        a {@code double}.
1371      * @return     a reference to this object.
1372      * @throws     StringIndexOutOfBoundsException  if the offset is invalid.
1373      */
1374     public AbstractStringBuilder insert(int offset, double d) {
1375         return insert(offset, String.valueOf(d));
1376     }
1377 
1378     /**
1379      * Returns the index within this string of the first occurrence of the
1380      * specified substring.
1381      *
1382      * <p>The returned index is the smallest value {@code k} for which:
1383      * <pre>{@code
1384      * this.toString().startsWith(str, k)
1385      * }</pre>
1386      * If no such value of {@code k} exists, then {@code -1} is returned.
1387      *
1388      * @param   str   the substring to search for.
1389      * @return  the index of the first occurrence of the specified substring,
1390      *          or {@code -1} if there is no such occurrence.
1391      */
1392     public int indexOf(String str) {
1393         return indexOf(str, 0);
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 }