1 18 package org.apache.beehive.netui.util.internal; 19 20 import java.io.Serializable ; 21 22 23 26 public final class InternalStringBuilder 27 implements Serializable 28 { 29 private char _buffer[]; 30 private int _length = 0; 31 private boolean _shared; 32 33 static final long serialVersionUID = 1; 34 35 public InternalStringBuilder() 36 { 37 this( 16 ); 38 } 39 40 public InternalStringBuilder( int length ) 41 { 42 _buffer = new char[length]; 43 _shared = false; 44 } 45 46 public InternalStringBuilder( String str ) 47 { 48 this( str.length() + 16 ); 49 append( str ); 50 } 51 52 public int length() 53 { 54 return _length; 55 } 56 57 private final void copyWhenShared() 58 { 59 if ( _shared ) 60 { 61 char newValue[] = new char[_buffer.length]; 62 System.arraycopy( _buffer, 0, newValue, 0, _length ); 63 _buffer = newValue; 64 _shared = false; 65 } 66 } 67 68 public void ensureCapacity( int minCapacity ) 69 { 70 int maxCapacity = _buffer.length; 71 72 if ( minCapacity > maxCapacity ) 73 { 74 int newCapacity = ( maxCapacity + 1 ) * 2; 75 if ( minCapacity > newCapacity ) newCapacity = minCapacity; 76 char newValue[] = new char[newCapacity]; 77 System.arraycopy( _buffer, 0, newValue, 0, _length ); 78 _buffer = newValue; 79 _shared = false; 80 } 81 } 82 83 public void setLength( int length ) 84 { 85 if ( length < 0 ) throw new StringIndexOutOfBoundsException ( length ); 86 ensureCapacity( length ); 87 88 if ( _length < length ) 89 { 90 copyWhenShared(); 91 while ( _length < length ) 92 { 93 _buffer[_length++] = '\0'; 94 } 95 } 96 _length = length; 97 } 98 99 public char charAt( int index ) 100 { 101 if ( index < 0 || index >= _length ) throw new StringIndexOutOfBoundsException ( index ); 102 return _buffer[index]; 103 } 104 105 public InternalStringBuilder append( Object obj ) 106 { 107 return append( String.valueOf( obj ) ); 108 } 109 110 public InternalStringBuilder append( String str ) 111 { 112 if ( str == null ) str = String.valueOf( str ); 113 int len = str.length(); 114 ensureCapacity( _length + len ); 115 copyWhenShared(); 116 str.getChars( 0, len, _buffer, _length ); 117 _length += len; 118 return this; 119 } 120 121 public InternalStringBuilder append( char c ) 122 { 123 ensureCapacity( _length + 1 ); 124 copyWhenShared(); 125 _buffer[_length++] = c; 126 return this; 127 } 128 129 public InternalStringBuilder append( int i ) 130 { 131 return append( String.valueOf( i ) ); 132 } 133 134 public String toString() 135 { 136 _shared = true; 137 return new String ( _buffer, 0, _length ); 138 } 139 140 public InternalStringBuilder deleteCharAt( int index ) 141 { 142 if ( index < 0 || index >= _length ) throw new StringIndexOutOfBoundsException ( index ); 143 System.arraycopy( _buffer, index + 1, _buffer, index, _length - index - 1 ); 144 _length--; 145 return this; 146 } 147 } 148 | Popular Tags |