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