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