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