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