1 /*
   2  * Copyright (c) 1994, 2013, 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 java.util.Arrays;
  29 import jdk.internal.HotSpotIntrinsicCandidate;
  30 
  31 /**
  32  * A thread-safe, mutable sequence of characters.
  33  * A string buffer is like a {@link String}, but can be modified. At any
  34  * point in time it contains some particular sequence of characters, but
  35  * the length and content of the sequence can be changed through certain
  36  * method calls.
  37  * <p>
  38  * String buffers are safe for use by multiple threads. The methods
  39  * are synchronized where necessary so that all the operations on any
  40  * particular instance behave as if they occur in some serial order
  41  * that is consistent with the order of the method calls made by each of
  42  * the individual threads involved.
  43  * <p>
  44  * The principal operations on a {@code StringBuffer} are the
  45  * {@code append} and {@code insert} methods, which are
  46  * overloaded so as to accept data of any type. Each effectively
  47  * converts a given datum to a string and then appends or inserts the
  48  * characters of that string to the string buffer. The
  49  * {@code append} method always adds these characters at the end
  50  * of the buffer; the {@code insert} method adds the characters at
  51  * a specified point.
  52  * <p>
  53  * For example, if {@code z} refers to a string buffer object
  54  * whose current contents are {@code "start"}, then
  55  * the method call {@code z.append("le")} would cause the string
  56  * buffer to contain {@code "startle"}, whereas
  57  * {@code z.insert(4, "le")} would alter the string buffer to
  58  * contain {@code "starlet"}.
  59  * <p>
  60  * In general, if sb refers to an instance of a {@code StringBuffer},
  61  * then {@code sb.append(x)} has the same effect as
  62  * {@code sb.insert(sb.length(), x)}.
  63  * <p>
  64  * Whenever an operation occurs involving a source sequence (such as
  65  * appending or inserting from a source sequence), this class synchronizes
  66  * only on the string buffer performing the operation, not on the source.
  67  * Note that while {@code StringBuffer} is designed to be safe to use
  68  * concurrently from multiple threads, if the constructor or the
  69  * {@code append} or {@code insert} operation is passed a source sequence
  70  * that is shared across threads, the calling code must ensure
  71  * that the operation has a consistent and unchanging view of the source
  72  * sequence for the duration of the operation.
  73  * This could be satisfied by the caller holding a lock during the
  74  * operation's call, by using an immutable source sequence, or by not
  75  * sharing the source sequence across threads.
  76  * <p>
  77  * Every string buffer has a capacity. As long as the length of the
  78  * character sequence contained in the string buffer does not exceed
  79  * the capacity, it is not necessary to allocate a new internal
  80  * buffer array. If the internal buffer overflows, it is
  81  * automatically made larger.
  82  * <p>
  83  * Unless otherwise noted, passing a {@code null} argument to a constructor
  84  * or method in this class will cause a {@link NullPointerException} to be
  85  * thrown.
  86  * <p>
  87  * As of  release JDK 5, this class has been supplemented with an equivalent
  88  * class designed for use by a single thread, {@link StringBuilder}.  The
  89  * {@code StringBuilder} class should generally be used in preference to
  90  * this one, as it supports all of the same operations but it is faster, as
  91  * it performs no synchronization.
  92  *
  93  * @author      Arthur van Hoff
  94  * @see     java.lang.StringBuilder
  95  * @see     java.lang.String
  96  * @since   1.0
  97  */
  98  public final class StringBuffer
  99     extends AbstractStringBuilder
 100     implements java.io.Serializable, CharSequence
 101 {
 102 
 103     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 104     static final long serialVersionUID = 3388685877147921107L;
 105 
 106     /**
 107      * Constructs a string buffer with no characters in it and an
 108      * initial capacity of 16 characters.
 109      */
 110     @HotSpotIntrinsicCandidate
 111     public StringBuffer() {
 112         super(16);
 113     }
 114 
 115     /**
 116      * Constructs a string buffer with no characters in it and
 117      * the specified initial capacity.
 118      *
 119      * @param      capacity  the initial capacity.
 120      * @exception  NegativeArraySizeException  if the {@code capacity}
 121      *               argument is less than {@code 0}.
 122      */
 123     @HotSpotIntrinsicCandidate
 124     public StringBuffer(int capacity) {
 125         super(capacity);
 126     }
 127 
 128     /**
 129      * Constructs a string buffer initialized to the contents of the
 130      * specified string. The initial capacity of the string buffer is
 131      * {@code 16} plus the length of the string argument.
 132      *
 133      * @param   str   the initial contents of the buffer.
 134      */
 135     @HotSpotIntrinsicCandidate
 136     public StringBuffer(String str) {
 137         super(str.length() + 16);
 138         append(str);
 139     }
 140 
 141     /**
 142      * Constructs a string buffer that contains the same characters
 143      * as the specified {@code CharSequence}. The initial capacity of
 144      * the string buffer is {@code 16} plus the length of the
 145      * {@code CharSequence} argument.
 146      * <p>
 147      * If the length of the specified {@code CharSequence} is
 148      * less than or equal to zero, then an empty buffer of capacity
 149      * {@code 16} is returned.
 150      *
 151      * @param      seq   the sequence to copy.
 152      * @since 1.5
 153      */
 154     public StringBuffer(CharSequence seq) {
 155         this(seq.length() + 16);
 156         append(seq);
 157     }
 158 
 159     @Override
 160     public synchronized int length() {
 161         return count;
 162     }
 163 
 164     @Override
 165     public synchronized int capacity() {
 166         return super.capacity();
 167     }
 168 
 169 
 170     @Override
 171     public synchronized void ensureCapacity(int minimumCapacity) {
 172         super.ensureCapacity(minimumCapacity);
 173     }
 174 
 175     /**
 176      * @since      1.5
 177      */
 178     @Override
 179     public synchronized void trimToSize() {
 180         super.trimToSize();
 181     }
 182 
 183     /**
 184      * @throws IndexOutOfBoundsException {@inheritDoc}
 185      * @see        #length()
 186      */
 187     @Override
 188     public synchronized void setLength(int newLength) {
 189         super.setLength(newLength);
 190     }
 191 
 192     /**
 193      * @throws IndexOutOfBoundsException {@inheritDoc}
 194      * @see        #length()
 195      */
 196     @Override
 197     public synchronized char charAt(int index) {
 198         return super.charAt(index);
 199     }
 200 
 201     /**
 202      * @throws IndexOutOfBoundsException {@inheritDoc}
 203      * @since      1.5
 204      */
 205     @Override
 206     public synchronized int codePointAt(int index) {
 207         return super.codePointAt(index);
 208     }
 209 
 210     /**
 211      * @throws IndexOutOfBoundsException {@inheritDoc}
 212      * @since     1.5
 213      */
 214     @Override
 215     public synchronized int codePointBefore(int index) {
 216         return super.codePointBefore(index);
 217     }
 218 
 219     /**
 220      * @throws IndexOutOfBoundsException {@inheritDoc}
 221      * @since     1.5
 222      */
 223     @Override
 224     public synchronized int codePointCount(int beginIndex, int endIndex) {
 225         return super.codePointCount(beginIndex, endIndex);
 226     }
 227 
 228     /**
 229      * @throws IndexOutOfBoundsException {@inheritDoc}
 230      * @since     1.5
 231      */
 232     @Override
 233     public synchronized int offsetByCodePoints(int index, int codePointOffset) {
 234         return super.offsetByCodePoints(index, codePointOffset);
 235     }
 236 
 237     /**
 238      * @throws IndexOutOfBoundsException {@inheritDoc}
 239      */
 240     @Override
 241     public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
 242                                       int dstBegin)
 243     {
 244         super.getChars(srcBegin, srcEnd, dst, dstBegin);
 245     }
 246 
 247     /**
 248      * @throws IndexOutOfBoundsException {@inheritDoc}
 249      * @see        #length()
 250      */
 251     @Override
 252     public synchronized void setCharAt(int index, char ch) {
 253         super.setCharAt(index, ch);
 254     }
 255 
 256     @Override
 257     public synchronized StringBuffer append(Object obj) {
 258         super.append(String.valueOf(obj));
 259         return this;
 260     }
 261 
 262     @Override
 263     @HotSpotIntrinsicCandidate
 264     public synchronized StringBuffer append(String str) {
 265         super.append(str);
 266         return this;
 267     }
 268 
 269     /**
 270      * Appends the specified {@code StringBuffer} to this sequence.
 271      * <p>
 272      * The characters of the {@code StringBuffer} argument are appended,
 273      * in order, to the contents of this {@code StringBuffer}, increasing the
 274      * length of this {@code StringBuffer} by the length of the argument.
 275      * If {@code sb} is {@code null}, then the four characters
 276      * {@code "null"} are appended to this {@code StringBuffer}.
 277      * <p>
 278      * Let <i>n</i> be the length of the old character sequence, the one
 279      * contained in the {@code StringBuffer} just prior to execution of the
 280      * {@code append} method. Then the character at index <i>k</i> in
 281      * the new character sequence is equal to the character at index <i>k</i>
 282      * in the old character sequence, if <i>k</i> is less than <i>n</i>;
 283      * otherwise, it is equal to the character at index <i>k-n</i> in the
 284      * argument {@code sb}.
 285      * <p>
 286      * This method synchronizes on {@code this}, the destination
 287      * object, but does not synchronize on the source ({@code sb}).
 288      *
 289      * @param   sb   the {@code StringBuffer} to append.
 290      * @return  a reference to this object.
 291      * @since 1.4
 292      */
 293     public synchronized StringBuffer append(StringBuffer sb) {
 294         super.append(sb);
 295         return this;
 296     }
 297 
 298     /**
 299      * @since 1.8
 300      */
 301     @Override
 302     synchronized StringBuffer append(AbstractStringBuilder asb) {
 303         super.append(asb);
 304         return this;
 305     }
 306 
 307     /**
 308      * Appends the specified {@code CharSequence} to this
 309      * sequence.
 310      * <p>
 311      * The characters of the {@code CharSequence} argument are appended,
 312      * in order, increasing the length of this sequence by the length of the
 313      * argument.
 314      *
 315      * <p>The result of this method is exactly the same as if it were an
 316      * invocation of this.append(s, 0, s.length());
 317      *
 318      * <p>This method synchronizes on {@code this}, the destination
 319      * object, but does not synchronize on the source ({@code s}).
 320      *
 321      * <p>If {@code s} is {@code null}, then the four characters
 322      * {@code "null"} are appended.
 323      *
 324      * @param   s the {@code CharSequence} to append.
 325      * @return  a reference to this object.
 326      * @since 1.5
 327      */
 328     @Override
 329     public synchronized StringBuffer append(CharSequence s) {
 330         super.append(s);
 331         return this;
 332     }
 333 
 334     /**
 335      * @throws IndexOutOfBoundsException {@inheritDoc}
 336      * @since      1.5
 337      */
 338     @Override
 339     public synchronized StringBuffer append(CharSequence s, int start, int end)
 340     {
 341         super.append(s, start, end);
 342         return this;
 343     }
 344 
 345     @Override
 346     public synchronized StringBuffer append(char[] str) {
 347         super.append(str);
 348         return this;
 349     }
 350 
 351     /**
 352      * @throws IndexOutOfBoundsException {@inheritDoc}
 353      */
 354     @Override
 355     public synchronized StringBuffer append(char[] str, int offset, int len) {
 356         super.append(str, offset, len);
 357         return this;
 358     }
 359 
 360     @Override
 361     public synchronized StringBuffer append(boolean b) {
 362         super.append(b);
 363         return this;
 364     }
 365 
 366     @Override
 367     @HotSpotIntrinsicCandidate
 368     public synchronized StringBuffer append(char c) {
 369         super.append(c);
 370         return this;
 371     }
 372 
 373     @Override
 374     @HotSpotIntrinsicCandidate
 375     public synchronized StringBuffer append(int i) {
 376         super.append(i);
 377         return this;
 378     }
 379 
 380     /**
 381      * @since 1.5
 382      */
 383     @Override
 384     public synchronized StringBuffer appendCodePoint(int codePoint) {
 385         super.appendCodePoint(codePoint);
 386         return this;
 387     }
 388 
 389     @Override
 390     public synchronized StringBuffer append(long lng) {
 391         super.append(lng);
 392         return this;
 393     }
 394 
 395     @Override
 396     public synchronized StringBuffer append(float f) {
 397         super.append(f);
 398         return this;
 399     }
 400 
 401     @Override
 402     public synchronized StringBuffer append(double d) {
 403         super.append(d);
 404         return this;
 405     }
 406 
 407     /**
 408      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 409      * @since      1.2
 410      */
 411     @Override
 412     public synchronized StringBuffer delete(int start, int end) {
 413         super.delete(start, end);
 414         return this;
 415     }
 416 
 417     /**
 418      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 419      * @since      1.2
 420      */
 421     @Override
 422     public synchronized StringBuffer deleteCharAt(int index) {
 423         super.deleteCharAt(index);
 424         return this;
 425     }
 426 
 427     /**
 428      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 429      * @since      1.2
 430      */
 431     @Override
 432     public synchronized StringBuffer replace(int start, int end, String str) {
 433         super.replace(start, end, str);
 434         return this;
 435     }
 436 
 437     /**
 438      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 439      * @since      1.2
 440      */
 441     @Override
 442     public synchronized String substring(int start) {
 443         return substring(start, count);
 444     }
 445 
 446     /**
 447      * @throws IndexOutOfBoundsException {@inheritDoc}
 448      * @since      1.4
 449      */
 450     @Override
 451     public synchronized CharSequence subSequence(int start, int end) {
 452         return super.substring(start, end);
 453     }
 454 
 455     /**
 456      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 457      * @since      1.2
 458      */
 459     @Override
 460     public synchronized String substring(int start, int end) {
 461         return super.substring(start, end);
 462     }
 463 
 464     /**
 465      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 466      * @since      1.2
 467      */
 468     @Override
 469     public synchronized StringBuffer insert(int index, char[] str, int offset,
 470                                             int len)
 471     {
 472         super.insert(index, str, offset, len);
 473         return this;
 474     }
 475 
 476     /**
 477      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 478      */
 479     @Override
 480     public synchronized StringBuffer insert(int offset, Object obj) {
 481         super.insert(offset, String.valueOf(obj));
 482         return this;
 483     }
 484 
 485     /**
 486      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 487      */
 488     @Override
 489     public synchronized StringBuffer insert(int offset, String str) {
 490         super.insert(offset, str);
 491         return this;
 492     }
 493 
 494     /**
 495      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 496      */
 497     @Override
 498     public synchronized StringBuffer insert(int offset, char[] str) {
 499         super.insert(offset, str);
 500         return this;
 501     }
 502 
 503     /**
 504      * @throws IndexOutOfBoundsException {@inheritDoc}
 505      * @since      1.5
 506      */
 507     @Override
 508     public StringBuffer insert(int dstOffset, CharSequence s) {
 509         // Note, synchronization achieved via invocations of other StringBuffer methods
 510         // after narrowing of s to specific type
 511         super.insert(dstOffset, s);
 512         return this;
 513     }
 514 
 515     /**
 516      * @throws IndexOutOfBoundsException {@inheritDoc}
 517      * @since      1.5
 518      */
 519     @Override
 520     public synchronized StringBuffer insert(int dstOffset, CharSequence s,
 521             int start, int end)
 522     {
 523         super.insert(dstOffset, s, start, end);
 524         return this;
 525     }
 526 
 527     /**
 528      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 529      */
 530     @Override
 531     public  StringBuffer insert(int offset, boolean b) {
 532         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 533         // after conversion of b to String by super class method
 534         super.insert(offset, b);
 535         return this;
 536     }
 537 
 538     /**
 539      * @throws IndexOutOfBoundsException {@inheritDoc}
 540      */
 541     @Override
 542     public synchronized StringBuffer insert(int offset, char c) {
 543         super.insert(offset, c);
 544         return this;
 545     }
 546 
 547     /**
 548      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 549      */
 550     @Override
 551     public StringBuffer insert(int offset, int i) {
 552         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 553         // after conversion of i to String by super class method
 554         super.insert(offset, i);
 555         return this;
 556     }
 557 
 558     /**
 559      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 560      */
 561     @Override
 562     public StringBuffer insert(int offset, long l) {
 563         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 564         // after conversion of l to String by super class method
 565         super.insert(offset, l);
 566         return this;
 567     }
 568 
 569     /**
 570      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 571      */
 572     @Override
 573     public StringBuffer insert(int offset, float f) {
 574         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 575         // after conversion of f to String by super class method
 576         super.insert(offset, f);
 577         return this;
 578     }
 579 
 580     /**
 581      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 582      */
 583     @Override
 584     public StringBuffer insert(int offset, double d) {
 585         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 586         // after conversion of d to String by super class method
 587         super.insert(offset, d);
 588         return this;
 589     }
 590 
 591     /**
 592      * @since      1.4
 593      */
 594     @Override
 595     public int indexOf(String str) {
 596         // Note, synchronization achieved via invocations of other StringBuffer methods
 597         return super.indexOf(str);
 598     }
 599 
 600     /**
 601      * @since      1.4
 602      */
 603     @Override
 604     public synchronized int indexOf(String str, int fromIndex) {
 605         return super.indexOf(str, fromIndex);
 606     }
 607 
 608     /**
 609      * @since      1.4
 610      */
 611     @Override
 612     public int lastIndexOf(String str) {
 613         // Note, synchronization achieved via invocations of other StringBuffer methods
 614         return lastIndexOf(str, count);
 615     }
 616 
 617     /**
 618      * @since      1.4
 619      */
 620     @Override
 621     public synchronized int lastIndexOf(String str, int fromIndex) {
 622         return super.lastIndexOf(str, fromIndex);
 623     }
 624 
 625     /**
 626      * @since   1.0.2
 627      */
 628     @Override
 629     public synchronized StringBuffer reverse() {
 630         super.reverse();
 631         return this;
 632     }
 633 
 634     @Override
 635     @HotSpotIntrinsicCandidate
 636     public synchronized String toString() {
 637         final byte[] value = this.value;
 638         if (isLatin1()) {
 639             if ((count << coder) < value.length) {
 640                 return StringLatin1.newString(value, 0, count);
 641             }
 642             shared = true;
 643             return new String(value, String.LATIN1);
 644         }
 645         return StringUTF16.newString(value, 0, count);
 646     }
 647 
 648     /**
 649      * Serializable fields for StringBuffer.
 650      *
 651      * @serialField value  char[]
 652      *              The backing character array of this StringBuffer.
 653      * @serialField count int
 654      *              The number of characters in this StringBuffer.
 655      * @serialField shared  boolean
 656      *              A flag indicating whether the backing array is shared.
 657      *              The value is ignored upon deserialization.
 658      */
 659     private static final java.io.ObjectStreamField[] serialPersistentFields =
 660     {
 661         new java.io.ObjectStreamField("value", char[].class),
 662         new java.io.ObjectStreamField("count", Integer.TYPE),
 663         new java.io.ObjectStreamField("shared", Boolean.TYPE),
 664     };
 665 
 666     /**
 667      * readObject is called to restore the state of the StringBuffer from
 668      * a stream.
 669      */
 670     private synchronized void writeObject(java.io.ObjectOutputStream s)
 671         throws java.io.IOException {
 672         java.io.ObjectOutputStream.PutField fields = s.putFields();
 673         char[] val = new char[capacity()];
 674         if (isLatin1()) {
 675             StringLatin1.getChars(value, 0, count, val, 0);
 676         } else {
 677             StringUTF16.getChars(value, 0, count, val, 0);
 678         }
 679         fields.put("value", val);
 680         fields.put("count", count);
 681         fields.put("shared", false);
 682         s.writeFields();
 683     }
 684 
 685     /**
 686      * readObject is called to restore the state of the StringBuffer from
 687      * a stream.
 688      */
 689     private void readObject(java.io.ObjectInputStream s)
 690         throws java.io.IOException, ClassNotFoundException {
 691         java.io.ObjectInputStream.GetField fields = s.readFields();
 692         char[] val = (char[])fields.get("value", null);
 693         initBytes(val, 0, val.length);
 694         count = fields.get("count", 0);
 695         shared = false;
 696     }
 697 
 698     synchronized void getBytes(byte dst[], int dstBegin, byte coder) {
 699         super.getBytes(dst, dstBegin, coder);
 700     }
 701 }