KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > persistence > antlr > ANTLRStringBuffer


1 package persistence.antlr;
2
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/license.html
6  *
7  */

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

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

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