KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > antlr > ANTLRStringBuffer


1 package antlr;
2
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/RIGHTS.html
6  *
7  * $Id: //depot/code/org.antlr/main/main/antlr/ANTLRStringBuffer.java#5 $
8  */

9
10 // Implementation of a StringBuffer-like object that does not have the
11
// unfortunate side-effect of creating Strings with very large buffers.
12

13 public class ANTLRStringBuffer {
14     protected char[] buffer = null;
15     protected int length = 0; // length and also where to store next char
16

17
18     public ANTLRStringBuffer() {
19         buffer = new char[50];
20     }
21
22     public ANTLRStringBuffer(int n) {
23         buffer = new char[n];
24     }
25
26     public final void append(char c) {
27         // This would normally be an "ensureCapacity" method, but inlined
28
// here for speed.
29
if (length >= buffer.length) {
30             // Compute a new length that is at least double old length
31
int newSize = buffer.length;
32             while (length >= newSize) {
33                 newSize *= 2;
34             }
35             // Allocate new array and copy buffer
36
char[] newBuffer = new char[newSize];
37             for (int i = 0; i < length; i++) {
38                 newBuffer[i] = buffer[i];
39             }
40             buffer = newBuffer;
41         }
42         buffer[length] = c;
43         length++;
44     }
45
46     public final void append(String JavaDoc s) {
47         for (int i = 0; i < s.length(); i++) {
48             append(s.charAt(i));
49         }
50     }
51
52     public final char charAt(int index) {
53         return buffer[index];
54     }
55
56     final public char[] getBuffer() {
57         return buffer;
58     }
59
60     public final int length() {
61         return length;
62     }
63
64     public final void setCharAt(int index, char ch) {
65         buffer[index] = ch;
66     }
67
68     public final void setLength(int newLength) {
69         if (newLength < length) {
70             length = newLength;
71         }
72         else {
73             while (newLength > length) {
74                 append('\0');
75             }
76         }
77     }
78
79     public final String JavaDoc toString() {
80         return new String JavaDoc(buffer, 0, length);
81     }
82 }
83
Popular Tags