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