1 50 package org.apache.avalon.excalibur.collections; 51 52 64 public final class VariableSizeBuffer implements Buffer 65 { 66 protected Object [] m_buffer; 67 protected int m_head; 68 protected int m_tail; 69 70 74 public VariableSizeBuffer( int size ) 75 { 76 m_buffer = new Object [ size + 1 ]; 77 m_head = 0; 78 m_tail = 0; 79 } 80 81 89 public VariableSizeBuffer() 90 { 91 this( 32 ); 92 } 93 94 97 public final boolean isEmpty() 98 { 99 return ( size() == 0 ); 100 } 101 102 105 public final int size() 106 { 107 int size = 0; 108 109 if( m_tail < m_head ) 110 { 111 size = m_buffer.length - m_head + m_tail; 112 } 113 else 114 { 115 size = m_tail - m_head; 116 } 117 118 return size; 119 } 120 121 124 public final void add( final Object o ) 125 { 126 if( null == o ) 127 { 128 throw new NullPointerException ( "Attempted to add null object to buffer" ); 129 } 130 131 if( size() + 1 >= m_buffer.length ) 132 { 133 Object [] tmp = new Object [ ( ( m_buffer.length - 1 ) * 2 ) + 1 ]; 134 135 int j = 0; 136 for( int i = m_head; i != m_tail; ) 137 { 138 tmp[ j ] = m_buffer[ i ]; 139 m_buffer[ i ] = null; 140 141 j++; 142 i++; 143 if( i == m_buffer.length ) 144 { 145 i = 0; 146 } 147 } 148 149 m_buffer = tmp; 150 m_head = 0; 151 m_tail = j; 152 } 153 154 m_buffer[ m_tail ] = o; 155 m_tail++; 156 if( m_tail >= m_buffer.length ) 157 { 158 m_tail = 0; 159 } 160 } 161 162 165 public Object remove() 166 { 167 if( isEmpty() ) 168 { 169 throw new BufferUnderflowException( "The buffer is already empty" ); 170 } 171 172 Object element = m_buffer[ m_head ]; 173 174 if( null != element ) 175 { 176 m_buffer[ m_head ] = null; 177 178 m_head++; 179 if( m_head >= m_buffer.length ) 180 { 181 m_head = 0; 182 } 183 } 184 185 return element; 186 } 187 } 188 189 | Popular Tags |