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