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