OSDN Git Service

libjava/ChangeLog:
[pf3gnuchains/gcc-fork.git] / libjava / classpath / java / lang / AbstractStringBuffer.java
1 /* AbstractStringBuffer.java -- Growable strings
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008
3    Free Software Foundation, Inc.
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING.  If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library.  Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module.  An independent module is a module which is not derived from
34 or based on this library.  If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so.  If you do not wish to do so, delete this
37 exception statement from your version. */
38
39 package java.lang;
40
41 import java.io.Serializable;
42
43 /**
44  * This class is based on gnu.classpath.ClasspathStringBuffer but
45  * is package-private to java.lang so it can be used as the basis
46  * for StringBuffer and StringBuilder.
47  * If you modify this, please consider also modifying that code.
48  */
49 abstract class AbstractStringBuffer
50   implements Serializable, CharSequence, Appendable
51 {
52
53   /**
54    * Index of next available character (and thus the size of the current
55    * string contents).  Note that this has permissions set this way so that
56    * String can get the value.
57    *
58    * @serial the number of characters in the buffer
59    */
60   int count;
61
62   /**
63    * The buffer.  Note that this has permissions set this way so that String
64    * can get the value.
65    *
66    * @serial the buffer
67    */
68   char[] value;
69
70   /**
71    * The default capacity of a buffer.
72    */
73   private static final int DEFAULT_CAPACITY = 16;
74
75   /**
76    * Create a new AbstractStringBuffer with default capacity 16.
77    */
78   AbstractStringBuffer()
79   {
80     this(DEFAULT_CAPACITY);
81   }
82
83   /**
84    * Create an empty <code>StringBuffer</code> with the specified initial
85    * capacity.
86    *
87    * @param capacity the initial capacity
88    * @throws NegativeArraySizeException if capacity is negative
89    */
90   AbstractStringBuffer(int capacity)
91   {
92     value = new char[capacity];
93   }
94
95   /**
96    * Create a new <code>StringBuffer</code> with the characters in the
97    * specified <code>String</code>. Initial capacity will be the size of the
98    * String plus 16.
99    *
100    * @param str the <code>String</code> to convert
101    * @throws NullPointerException if str is null
102    */
103   AbstractStringBuffer(String str)
104   {
105     count = str.count;
106     value = new char[count + DEFAULT_CAPACITY];
107     str.getChars(0, count, value, 0);
108   }
109
110   /**
111    * Create a new <code>StringBuffer</code> with the characters in the
112    * specified <code>CharSequence</code>. Initial capacity will be the
113    * length of the sequence plus 16; if the sequence reports a length
114    * less than or equal to 0, then the initial capacity will be 16.
115    *
116    * @param seq the initializing <code>CharSequence</code>
117    * @throws NullPointerException if str is null
118    * @since 1.5
119    */
120   AbstractStringBuffer(CharSequence seq)
121   {
122     int len = seq.length();
123     count = len <= 0 ? 0 : len;
124     value = new char[count + DEFAULT_CAPACITY];
125     for (int i = 0; i < len; ++i)
126       value[i] = seq.charAt(i);
127   }
128
129   /**
130    * Increase the capacity of this <code>StringBuffer</code>. This will
131    * ensure that an expensive growing operation will not occur until
132    * <code>minimumCapacity</code> is reached. The buffer is grown to the
133    * larger of <code>minimumCapacity</code> and
134    * <code>capacity() * 2 + 2</code>, if it is not already large enough.
135    *
136    * @param minimumCapacity the new capacity
137    * @see #capacity()
138    */
139   public void ensureCapacity(int minimumCapacity)
140   {
141     ensureCapacity_unsynchronized(minimumCapacity);
142   }
143
144   /**
145    * Set the length of this StringBuffer. If the new length is greater than
146    * the current length, all the new characters are set to '\0'. If the new
147    * length is less than the current length, the first <code>newLength</code>
148    * characters of the old array will be preserved, and the remaining
149    * characters are truncated.
150    *
151    * @param newLength the new length
152    * @throws IndexOutOfBoundsException if the new length is negative
153    *         (while unspecified, this is a StringIndexOutOfBoundsException)
154    * @see #length()
155    */
156   public void setLength(int newLength)
157   {
158     if (newLength < 0)
159       throw new StringIndexOutOfBoundsException(newLength);
160
161     int valueLength = value.length;
162
163     /* Always call ensureCapacity_unsynchronized in order to preserve
164        copy-on-write semantics.  */
165     ensureCapacity_unsynchronized(newLength);
166
167     if (newLength < valueLength)
168       {
169         /* If the StringBuffer's value just grew, then we know that
170            value is newly allocated and the region between count and
171            newLength is filled with '\0'.  */
172         count = newLength;
173       }
174     else
175       {
176         /* The StringBuffer's value doesn't need to grow.  However,
177            we should clear out any cruft that may exist.  */
178         while (count < newLength)
179           value[count++] = '\0';
180       }
181   }
182
183   /**
184    * Get the character at the specified index.
185    *
186    * @param index the index of the character to get, starting at 0
187    * @return the character at the specified index
188    * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
189    *         (while unspecified, this is a StringIndexOutOfBoundsException)
190    */
191   public char charAt(int index)
192   {
193     if (index < 0 || index >= count)
194       throw new StringIndexOutOfBoundsException(index);
195     return value[index];
196   }
197
198   /**
199    * Get the code point at the specified index.  This is like #charAt(int),
200    * but if the character is the start of a surrogate pair, and the
201    * following character completes the pair, then the corresponding
202    * supplementary code point is returned.
203    * @param index the index of the codepoint to get, starting at 0
204    * @return the codepoint at the specified index
205    * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
206    * @since 1.5
207    */
208   public int codePointAt(int index)
209   {
210     return Character.codePointAt(value, index, count);
211   }
212
213   /**
214    * Get the code point before the specified index.  This is like
215    * #codePointAt(int), but checks the characters at <code>index-1</code> and
216    * <code>index-2</code> to see if they form a supplementary code point.
217    * @param index the index just past the codepoint to get, starting at 0
218    * @return the codepoint at the specified index
219    * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
220    * @since 1.5
221    */
222   public int codePointBefore(int index)
223   {
224     // Character.codePointBefore() doesn't perform this check.  We
225     // could use the CharSequence overload, but this is just as easy.
226     if (index >= count)
227       throw new IndexOutOfBoundsException();
228     return Character.codePointBefore(value, index, 1);
229   }
230
231   /**
232    * Get the specified array of characters. <code>srcOffset - srcEnd</code>
233    * characters will be copied into the array you pass in.
234    *
235    * @param srcOffset the index to start copying from (inclusive)
236    * @param srcEnd the index to stop copying from (exclusive)
237    * @param dst the array to copy into
238    * @param dstOffset the index to start copying into
239    * @throws NullPointerException if dst is null
240    * @throws IndexOutOfBoundsException if any source or target indices are
241    *         out of range (while unspecified, source problems cause a
242    *         StringIndexOutOfBoundsException, and dest problems cause an
243    *         ArrayIndexOutOfBoundsException)
244    * @see System#arraycopy(Object, int, Object, int, int)
245    */
246   public void getChars(int srcOffset, int srcEnd,
247                        char[] dst, int dstOffset)
248   {
249     if (srcOffset < 0 || srcEnd > count || srcEnd < srcOffset)
250       throw new StringIndexOutOfBoundsException();
251     VMSystem.arraycopy(value, srcOffset, dst, dstOffset, srcEnd - srcOffset);
252   }
253
254   /**
255    * Set the character at the specified index.
256    *
257    * @param index the index of the character to set starting at 0
258    * @param ch the value to set that character to
259    * @throws IndexOutOfBoundsException if index is negative or &gt;= length()
260    *         (while unspecified, this is a StringIndexOutOfBoundsException)
261    */
262   public void setCharAt(int index, char ch)
263   {
264     if (index < 0 || index >= count)
265       throw new StringIndexOutOfBoundsException(index);
266     // Call ensureCapacity to enforce copy-on-write.
267     ensureCapacity_unsynchronized(count);
268     value[index] = ch;
269   }
270
271   /**
272    * Append the <code>String</code> value of the argument to this
273    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
274    * to <code>String</code>.
275    *
276    * @param obj the <code>Object</code> to convert and append
277    * @return this <code>StringBuffer</code>
278    * @see String#valueOf(Object)
279    * @see #append(String)
280    */
281   public AbstractStringBuffer append(Object obj)
282   {
283     return append(String.valueOf(obj));
284   }
285
286   /**
287    * Append the <code>String</code> to this <code>StringBuffer</code>. If
288    * str is null, the String "null" is appended.
289    *
290    * @param str the <code>String</code> to append
291    * @return this <code>StringBuffer</code>
292    */
293   public AbstractStringBuffer append(String str)
294   {
295     if (str == null)
296       str = "null";
297     int len = str.count;
298     ensureCapacity_unsynchronized(count + len);
299     str.getChars(0, len, value, count);
300     count += len;
301     return this;
302   }
303
304   /**
305    * Append the <code>StringBuilder</code> value of the argument to this
306    * <code>StringBuilder</code>. This behaves the same as
307    * <code>append((Object) stringBuffer)</code>, except it is more efficient.
308    *
309    * @param stringBuffer the <code>StringBuilder</code> to convert and append
310    * @return this <code>StringBuilder</code>
311    * @see #append(Object)
312    */
313   public AbstractStringBuffer append(StringBuffer stringBuffer)
314   {
315     if (stringBuffer == null)
316       return append("null");
317     synchronized (stringBuffer)
318       {
319         int len = stringBuffer.count;
320         ensureCapacity(count + len);
321         VMSystem.arraycopy(stringBuffer.value, 0, value, count, len);
322         count += len;
323       }
324     return this;
325   }
326
327   /**
328    * Append the <code>char</code> array to this <code>StringBuffer</code>.
329    * This is similar (but more efficient) than
330    * <code>append(new String(data))</code>, except in the case of null.
331    *
332    * @param data the <code>char[]</code> to append
333    * @return this <code>StringBuffer</code>
334    * @throws NullPointerException if <code>str</code> is <code>null</code>
335    * @see #append(char[], int, int)
336    */
337   public AbstractStringBuffer append(char[] data)
338   {
339     return append(data, 0, data.length);
340   }
341
342   /**
343    * Append part of the <code>char</code> array to this
344    * <code>StringBuffer</code>. This is similar (but more efficient) than
345    * <code>append(new String(data, offset, count))</code>, except in the case
346    * of null.
347    *
348    * @param data the <code>char[]</code> to append
349    * @param offset the start location in <code>str</code>
350    * @param count the number of characters to get from <code>str</code>
351    * @return this <code>StringBuffer</code>
352    * @throws NullPointerException if <code>str</code> is <code>null</code>
353    * @throws IndexOutOfBoundsException if offset or count is out of range
354    *         (while unspecified, this is a StringIndexOutOfBoundsException)
355    */
356   public AbstractStringBuffer append(char[] data, int offset, int count)
357   {
358     if (offset < 0 || count < 0 || offset > data.length - count)
359       throw new StringIndexOutOfBoundsException();
360     ensureCapacity_unsynchronized(this.count + count);
361     VMSystem.arraycopy(data, offset, value, this.count, count);
362     this.count += count;
363     return this;
364   }
365
366   /**
367    * Append the <code>String</code> value of the argument to this
368    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
369    * to <code>String</code>.
370    *
371    * @param bool the <code>boolean</code> to convert and append
372    * @return this <code>StringBuffer</code>
373    * @see String#valueOf(boolean)
374    */
375   public AbstractStringBuffer append(boolean bool)
376   {
377     return append(bool ? "true" : "false");
378   }
379
380   /**
381    * Append the <code>char</code> to this <code>StringBuffer</code>.
382    *
383    * @param ch the <code>char</code> to append
384    * @return this <code>StringBuffer</code>
385    */
386   public AbstractStringBuffer append(char ch)
387   {
388     ensureCapacity_unsynchronized(count + 1);
389     value[count++] = ch;
390     return this;
391   }
392
393   /**
394    * Append the characters in the <code>CharSequence</code> to this
395    * buffer.
396    *
397    * @param seq the <code>CharSequence</code> providing the characters
398    * @return this <code>StringBuffer</code>
399    * @since 1.5
400    */
401   public AbstractStringBuffer append(CharSequence seq)
402   {
403     return append(seq, 0, seq.length());
404   }
405
406   /**
407    * Append some characters from the <code>CharSequence</code> to this
408    * buffer.  If the argument is null, the <code>seq</code> is assumed
409    * to be equal to the string <code>"null"</code>.
410    *
411    * @param seq the <code>CharSequence</code> providing the characters
412    * @param start the starting index
413    * @param end one past the final index
414    * @return this <code>StringBuffer</code>
415    * @since 1.5
416    */
417   public AbstractStringBuffer append(CharSequence seq, int start, int end)
418   {
419     if (seq == null)
420       seq = "null";
421     if (end - start > 0)
422       {
423         ensureCapacity_unsynchronized(count + end - start);
424         for (; start < end; ++start)
425           value[count++] = seq.charAt(start);
426       }
427     return this;
428   }
429
430   /**
431    * Append the <code>String</code> value of the argument to this
432    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
433    * to <code>String</code>.
434    *
435    * @param inum the <code>int</code> to convert and append
436    * @return this <code>StringBuffer</code>
437    * @see String#valueOf(int)
438    */
439   // This is native in libgcj, for efficiency.
440   public AbstractStringBuffer append(int inum)
441   {
442     return append(String.valueOf(inum));
443   }
444
445   /**
446    * Append the <code>String</code> value of the argument to this
447    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
448    * to <code>String</code>.
449    *
450    * @param lnum the <code>long</code> to convert and append
451    * @return this <code>StringBuffer</code>
452    * @see String#valueOf(long)
453    */
454   public AbstractStringBuffer append(long lnum)
455   {
456     return append(Long.toString(lnum, 10));
457   }
458
459   /**
460    * Append the <code>String</code> value of the argument to this
461    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
462    * to <code>String</code>.
463    *
464    * @param fnum the <code>float</code> to convert and append
465    * @return this <code>StringBuffer</code>
466    * @see String#valueOf(float)
467    */
468   public AbstractStringBuffer append(float fnum)
469   {
470     return append(Float.toString(fnum));
471   }
472
473   /**
474    * Append the <code>String</code> value of the argument to this
475    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
476    * to <code>String</code>.
477    *
478    * @param dnum the <code>double</code> to convert and append
479    * @return this <code>StringBuffer</code>
480    * @see String#valueOf(double)
481    */
482   public AbstractStringBuffer append(double dnum)
483   {
484     return append(Double.toString(dnum));
485   }
486
487   /**
488    * Append the code point to this <code>StringBuffer</code>.
489    * This is like #append(char), but will append two characters
490    * if a supplementary code point is given.
491    *
492    * @param code the code point to append
493    * @return this <code>StringBuffer</code>
494    * @see Character#toChars(int, char[], int)
495    * @since 1.5
496    */
497   public AbstractStringBuffer appendCodePoint(int code)
498   {
499     int len = Character.charCount(code);
500     ensureCapacity_unsynchronized(count + len);
501     Character.toChars(code, value, count);
502     count += len;
503     return this;
504   }
505
506   /**
507    * Delete characters from this <code>StringBuffer</code>.
508    * <code>delete(10, 12)</code> will delete 10 and 11, but not 12. It is
509    * harmless for end to be larger than length().
510    *
511    * @param start the first character to delete
512    * @param end the index after the last character to delete
513    * @return this <code>StringBuffer</code>
514    * @throws StringIndexOutOfBoundsException if start or end are out of bounds
515    * @since 1.2
516    */
517   public AbstractStringBuffer delete(int start, int end)
518   {
519     if (start < 0 || start > count || start > end)
520       throw new StringIndexOutOfBoundsException(start);
521     if (end > count)
522       end = count;
523     ensureCapacity_unsynchronized(count);
524     if (count - end != 0)
525       VMSystem.arraycopy(value, end, value, start, count - end);
526     count -= end - start;
527     return this;
528   }
529
530   /**
531    * Delete a character from this <code>StringBuffer</code>.
532    *
533    * @param index the index of the character to delete
534    * @return this <code>StringBuffer</code>
535    * @throws StringIndexOutOfBoundsException if index is out of bounds
536    * @since 1.2
537    */
538   public AbstractStringBuffer deleteCharAt(int index)
539   {
540     return delete(index, index + 1);
541   }
542
543   /**
544    * Replace characters between index <code>start</code> (inclusive) and
545    * <code>end</code> (exclusive) with <code>str</code>. If <code>end</code>
546    * is larger than the size of this StringBuffer, all characters after
547    * <code>start</code> are replaced.
548    *
549    * @param start the beginning index of characters to delete (inclusive)
550    * @param end the ending index of characters to delete (exclusive)
551    * @param str the new <code>String</code> to insert
552    * @return this <code>StringBuffer</code>
553    * @throws StringIndexOutOfBoundsException if start or end are out of bounds
554    * @throws NullPointerException if str is null
555    * @since 1.2
556    */
557   public AbstractStringBuffer replace(int start, int end, String str)
558   {
559     if (start < 0 || start > count || start > end)
560       throw new StringIndexOutOfBoundsException(start);
561
562     int len = str.count;
563     // Calculate the difference in 'count' after the replace.
564     int delta = len - (end > count ? count : end) + start;
565     ensureCapacity_unsynchronized(count + delta);
566
567     if (delta != 0 && end < count)
568       VMSystem.arraycopy(value, end, value, end + delta, count - end);
569
570     str.getChars(0, len, value, start);
571     count += delta;
572     return this;
573   }
574
575   /**
576    * Insert a subarray of the <code>char[]</code> argument into this
577    * <code>StringBuffer</code>.
578    *
579    * @param offset the place to insert in this buffer
580    * @param str the <code>char[]</code> to insert
581    * @param str_offset the index in <code>str</code> to start inserting from
582    * @param len the number of characters to insert
583    * @return this <code>StringBuffer</code>
584    * @throws NullPointerException if <code>str</code> is <code>null</code>
585    * @throws StringIndexOutOfBoundsException if any index is out of bounds
586    * @since 1.2
587    */
588   public AbstractStringBuffer insert(int offset, char[] str, int str_offset, int len)
589   {
590     if (offset < 0 || offset > count || len < 0
591         || str_offset < 0 || str_offset > str.length - len)
592       throw new StringIndexOutOfBoundsException();
593     ensureCapacity_unsynchronized(count + len);
594     VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
595     VMSystem.arraycopy(str, str_offset, value, offset, len);
596     count += len;
597     return this;
598   }
599
600   /**
601    * Insert the <code>String</code> value of the argument into this
602    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
603    * to <code>String</code>.
604    *
605    * @param offset the place to insert in this buffer
606    * @param obj the <code>Object</code> to convert and insert
607    * @return this <code>StringBuffer</code>
608    * @exception StringIndexOutOfBoundsException if offset is out of bounds
609    * @see String#valueOf(Object)
610    */
611   public AbstractStringBuffer insert(int offset, Object obj)
612   {
613     return insert(offset, obj == null ? "null" : obj.toString());
614   }
615
616   /**
617    * Insert the <code>String</code> argument into this
618    * <code>StringBuffer</code>. If str is null, the String "null" is used
619    * instead.
620    *
621    * @param offset the place to insert in this buffer
622    * @param str the <code>String</code> to insert
623    * @return this <code>StringBuffer</code>
624    * @throws StringIndexOutOfBoundsException if offset is out of bounds
625    */
626   public AbstractStringBuffer insert(int offset, String str)
627   {
628     if (offset < 0 || offset > count)
629       throw new StringIndexOutOfBoundsException(offset);
630     if (str == null)
631       str = "null";
632     int len = str.count;
633     ensureCapacity_unsynchronized(count + len);
634     VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
635     str.getChars(0, len, value, offset);
636     count += len;
637     return this;
638   }
639
640   /**
641    * Insert the <code>CharSequence</code> argument into this
642    * <code>StringBuffer</code>.  If the sequence is null, the String
643    * "null" is used instead.
644    *
645    * @param offset the place to insert in this buffer
646    * @param sequence the <code>CharSequence</code> to insert
647    * @return this <code>StringBuffer</code>
648    * @throws IndexOutOfBoundsException if offset is out of bounds
649    * @since 1.5
650    */
651   public AbstractStringBuffer insert(int offset, CharSequence sequence)
652   {
653     if (sequence == null)
654       sequence = "null";
655     return insert(offset, sequence, 0, sequence.length());
656   }
657
658   /**
659    * Insert a subsequence of the <code>CharSequence</code> argument into this
660    * <code>StringBuffer</code>.  If the sequence is null, the String
661    * "null" is used instead.
662    *
663    * @param offset the place to insert in this buffer
664    * @param sequence the <code>CharSequence</code> to insert
665    * @param start the starting index of the subsequence
666    * @param end one past the ending index of the subsequence
667    * @return this <code>StringBuffer</code>
668    * @throws IndexOutOfBoundsException if offset, start,
669    * or end are out of bounds
670    * @since 1.5
671    */
672   public AbstractStringBuffer insert(int offset, CharSequence sequence, int start, int end)
673   {
674     if (sequence == null)
675       sequence = "null";
676     if (start < 0 || end < 0 || start > end || end > sequence.length())
677       throw new IndexOutOfBoundsException();
678     int len = end - start;
679     ensureCapacity_unsynchronized(count + len);
680     VMSystem.arraycopy(value, offset, value, offset + len, count - offset);
681     for (int i = start; i < end; ++i)
682       value[offset++] = sequence.charAt(i);
683     count += len;
684     return this;
685   }
686
687   /**
688    * Insert the <code>char[]</code> argument into this
689    * <code>StringBuffer</code>.
690    *
691    * @param offset the place to insert in this buffer
692    * @param data the <code>char[]</code> to insert
693    * @return this <code>StringBuffer</code>
694    * @throws NullPointerException if <code>data</code> is <code>null</code>
695    * @throws StringIndexOutOfBoundsException if offset is out of bounds
696    * @see #insert(int, char[], int, int)
697    */
698   public AbstractStringBuffer insert(int offset, char[] data)
699   {
700     return insert(offset, data, 0, data.length);
701   }
702
703   /**
704    * Insert the <code>String</code> value of the argument into this
705    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
706    * to <code>String</code>.
707    *
708    * @param offset the place to insert in this buffer
709    * @param bool the <code>boolean</code> to convert and insert
710    * @return this <code>StringBuffer</code>
711    * @throws StringIndexOutOfBoundsException if offset is out of bounds
712    * @see String#valueOf(boolean)
713    */
714   public AbstractStringBuffer insert(int offset, boolean bool)
715   {
716     return insert(offset, bool ? "true" : "false");
717   }
718
719   /**
720    * Insert the <code>char</code> argument into this <code>StringBuffer</code>.
721    *
722    * @param offset the place to insert in this buffer
723    * @param ch the <code>char</code> to insert
724    * @return this <code>StringBuffer</code>
725    * @throws StringIndexOutOfBoundsException if offset is out of bounds
726    */
727   public AbstractStringBuffer insert(int offset, char ch)
728   {
729     if (offset < 0 || offset > count)
730       throw new StringIndexOutOfBoundsException(offset);
731     ensureCapacity_unsynchronized(count + 1);
732     VMSystem.arraycopy(value, offset, value, offset + 1, count - offset);
733     value[offset] = ch;
734     count++;
735     return this;
736   }
737
738   /**
739    * Insert the <code>String</code> value of the argument into this
740    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
741    * to <code>String</code>.
742    *
743    * @param offset the place to insert in this buffer
744    * @param inum the <code>int</code> to convert and insert
745    * @return this <code>StringBuffer</code>
746    * @throws StringIndexOutOfBoundsException if offset is out of bounds
747    * @see String#valueOf(int)
748    */
749   public AbstractStringBuffer insert(int offset, int inum)
750   {
751     return insert(offset, String.valueOf(inum));
752   }
753
754   /**
755    * Insert the <code>String</code> value of the argument into this
756    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
757    * to <code>String</code>.
758    *
759    * @param offset the place to insert in this buffer
760    * @param lnum the <code>long</code> to convert and insert
761    * @return this <code>StringBuffer</code>
762    * @throws StringIndexOutOfBoundsException if offset is out of bounds
763    * @see String#valueOf(long)
764    */
765   public AbstractStringBuffer insert(int offset, long lnum)
766   {
767     return insert(offset, Long.toString(lnum, 10));
768   }
769
770   /**
771    * Insert the <code>String</code> value of the argument into this
772    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
773    * to <code>String</code>.
774    *
775    * @param offset the place to insert in this buffer
776    * @param fnum the <code>float</code> to convert and insert
777    * @return this <code>StringBuffer</code>
778    * @throws StringIndexOutOfBoundsException if offset is out of bounds
779    * @see String#valueOf(float)
780    */
781   public AbstractStringBuffer insert(int offset, float fnum)
782   {
783     return insert(offset, Float.toString(fnum));
784   }
785
786   /**
787    * Insert the <code>String</code> value of the argument into this
788    * <code>StringBuffer</code>. Uses <code>String.valueOf()</code> to convert
789    * to <code>String</code>.
790    *
791    * @param offset the place to insert in this buffer
792    * @param dnum the <code>double</code> to convert and insert
793    * @return this <code>StringBuffer</code>
794    * @throws StringIndexOutOfBoundsException if offset is out of bounds
795    * @see String#valueOf(double)
796    */
797   public AbstractStringBuffer insert(int offset, double dnum)
798   {
799     return insert(offset, Double.toString(dnum));
800   }
801
802   /**
803    * Finds the first instance of a substring in this StringBuilder.
804    *
805    * @param str String to find
806    * @return location (base 0) of the String, or -1 if not found
807    * @throws NullPointerException if str is null
808    * @see #indexOf(String, int)
809    */
810   public int indexOf(String str)
811   {
812     return indexOf(str, 0);
813   }
814
815   /**
816    * Finds the first instance of a String in this StringBuffer, starting at
817    * a given index.  If starting index is less than 0, the search starts at
818    * the beginning of this String.  If the starting index is greater than the
819    * length of this String, or the substring is not found, -1 is returned.
820    *
821    * @param str String to find
822    * @param fromIndex index to start the search
823    * @return location (base 0) of the String, or -1 if not found
824    * @throws NullPointerException if str is null
825    * @since 1.4
826    */
827   public int indexOf(String str, int fromIndex)
828   {
829     if (fromIndex < 0)
830       fromIndex = 0;
831     int limit = count - str.count;
832     for ( ; fromIndex <= limit; fromIndex++)
833       if (regionMatches(fromIndex, str))
834         return fromIndex;
835     return -1;
836   }
837
838   /**
839    * Finds the last instance of a substring in this StringBuffer.
840    *
841    * @param str String to find
842    * @return location (base 0) of the String, or -1 if not found
843    * @throws NullPointerException if str is null
844    * @see #lastIndexOf(String, int)
845    * @since 1.4
846    */
847   public int lastIndexOf(String str)
848   {
849     return lastIndexOf(str, count - str.count);
850   }
851
852   /**
853    * Finds the last instance of a String in this StringBuffer, starting at a
854    * given index.  If starting index is greater than the maximum valid index,
855    * then the search begins at the end of this String.  If the starting index
856    * is less than zero, or the substring is not found, -1 is returned.
857    *
858    * @param str String to find
859    * @param fromIndex index to start the search
860    * @return location (base 0) of the String, or -1 if not found
861    * @throws NullPointerException if str is null
862    * @since 1.4
863    */
864   public int lastIndexOf(String str, int fromIndex)
865   {
866     fromIndex = Math.min(fromIndex, count - str.count);
867     for ( ; fromIndex >= 0; fromIndex--)
868       if (regionMatches(fromIndex, str))
869         return fromIndex;
870     return -1;
871   }
872
873   /**
874    * Reverse the characters in this StringBuffer. The same sequence of
875    * characters exists, but in the reverse index ordering.
876    *
877    * @return this <code>StringBuffer</code>
878    */
879   public AbstractStringBuffer reverse()
880   {
881     // Call ensureCapacity to enforce copy-on-write.
882     ensureCapacity_unsynchronized(count);
883     for (int i = count >> 1, j = count - i; --i >= 0; ++j)
884       {
885         char c = value[i];
886         value[i] = value[j];
887         value[j] = c;
888       }
889     return this;
890   }
891
892   /**
893    * This may reduce the amount of memory used by the StringBuffer,
894    * by resizing the internal array to remove unused space.  However,
895    * this method is not required to resize, so this behavior cannot
896    * be relied upon.
897    * @since 1.5
898    */
899   public void trimToSize()
900   {
901     int wouldSave = value.length - count;
902     // Some random heuristics: if we save less than 20 characters, who
903     // cares.
904     if (wouldSave < 20)
905       return;
906     // If we save more than 200 characters, shrink.
907     // If we save more than 1/4 of the buffer, shrink.
908     if (wouldSave > 200 || wouldSave * 4 > value.length)
909       {
910         char[] newValue = new char[count];
911         VMSystem.arraycopy(value, 0, newValue, 0, count);
912         value = newValue;
913       }
914   }
915
916   /**
917    * Return the number of code points between two indices in the
918    * <code>StringBuffer</code>.  An unpaired surrogate counts as a
919    * code point for this purpose.  Characters outside the indicated
920    * range are not examined, even if the range ends in the middle of a
921    * surrogate pair.
922    *
923    * @param start the starting index
924    * @param end one past the ending index
925    * @return the number of code points
926    * @since 1.5
927    */
928   public int codePointCount(int start, int end)
929   {
930     if (start < 0 || end >= count || start > end)
931       throw new StringIndexOutOfBoundsException();
932
933     int count = 0;
934     while (start < end)
935       {
936         char base = value[start];
937         if (base < Character.MIN_HIGH_SURROGATE
938             || base > Character.MAX_HIGH_SURROGATE
939             || start == end
940             || start == count
941             || value[start + 1] < Character.MIN_LOW_SURROGATE
942             || value[start + 1] > Character.MAX_LOW_SURROGATE)
943           {
944             // Nothing.
945           }
946         else
947           {
948             // Surrogate pair.
949             ++start;
950           }
951         ++start;
952         ++count;
953       }
954     return count;
955   }
956
957   /**
958    * Starting at the given index, this counts forward by the indicated
959    * number of code points, and then returns the resulting index.  An
960    * unpaired surrogate counts as a single code point for this
961    * purpose.
962    *
963    * @param start the starting index
964    * @param codePoints the number of code points
965    * @return the resulting index
966    * @since 1.5
967    */
968   public int offsetByCodePoints(int start, int codePoints)
969   {
970     while (codePoints > 0)
971       {
972         char base = value[start];
973         if (base < Character.MIN_HIGH_SURROGATE
974             || base > Character.MAX_HIGH_SURROGATE
975             || start == count
976             || value[start + 1] < Character.MIN_LOW_SURROGATE
977             || value[start + 1] > Character.MAX_LOW_SURROGATE)
978           {
979             // Nothing.
980           }
981         else
982           {
983             // Surrogate pair.
984             ++start;
985           }
986         ++start;
987         --codePoints;
988       }
989     return start;
990   }
991
992   /**
993    * Increase the capacity of this <code>StringBuilder</code>. This will
994    * ensure that an expensive growing operation will not occur until
995    * <code>minimumCapacity</code> is reached. The buffer is grown to the
996    * larger of <code>minimumCapacity</code> and
997    * <code>capacity() * 2 + 2</code>, if it is not already large enough.
998    *
999    * @param minimumCapacity the new capacity
1000    * @see #capacity()
1001    */
1002   void ensureCapacity_unsynchronized(int minimumCapacity)
1003   {
1004     if (minimumCapacity > value.length)
1005       {
1006         int max = value.length * 2 + 2;
1007         minimumCapacity = (minimumCapacity < max ? max : minimumCapacity);
1008         char[] nb = new char[minimumCapacity];
1009         VMSystem.arraycopy(value, 0, nb, 0, count);
1010         value = nb;
1011       }
1012   }
1013
1014   /**
1015    * Predicate which determines if a substring of this matches another String
1016    * starting at a specified offset for each String and continuing for a
1017    * specified length. This is more efficient than creating a String to call
1018    * indexOf on.
1019    *
1020    * @param toffset index to start comparison at for this String
1021    * @param other non-null String to compare to region of this
1022    * @return true if regions match, false otherwise
1023    * @see #indexOf(String, int)
1024    * @see #lastIndexOf(String, int)
1025    * @see String#regionMatches(boolean, int, String, int, int)
1026    */
1027   private boolean regionMatches(int toffset, String other)
1028   {
1029     int len = other.count;
1030     int index = other.offset;
1031     while (--len >= 0)
1032       if (value[toffset++] != other.value[index++])
1033         return false;
1034     return true;
1035   }
1036
1037 }