1 50 package org.apache.avalon.excalibur.collections; 51 52 60 public final class FixedSizeBuffer implements Buffer 61 { 62 private final Object [] m_elements; 63 private int m_start = 0; 64 private int m_end = 0; 65 private boolean m_full = false; 66 67 public FixedSizeBuffer( int size ) 68 { 69 m_elements = new Object [ size ]; 70 } 71 72 public FixedSizeBuffer() 73 { 74 this( 32 ); 75 } 76 77 public final int size() 78 { 79 int size = 0; 80 81 if( m_end < m_start ) 82 { 83 size = m_elements.length - m_start + m_end; 84 } 85 else if( m_end == m_start ) 86 { 87 size = ( m_full ? m_elements.length : 0 ); 88 } 89 else 90 { 91 size = m_end - m_start; 92 } 93 94 return size; 95 } 96 97 public final boolean isEmpty() 98 { 99 return size() == 0; 100 } 101 102 public final void add( Object element ) 103 { 104 if( null == element ) 105 { 106 throw new NullPointerException ( "Attempted to add null object to buffer" ); 107 } 108 109 if( m_full ) 110 { 111 throw new BufferOverflowException( "The buffer cannot hold more than " 112 + m_elements.length + " objects." ); 113 } 114 115 m_elements[ m_end++ ] = element; 116 117 if( m_end >= m_elements.length ) 118 { 119 m_end = 0; 120 } 121 122 if( m_end == m_start ) 123 { 124 m_full = true; 125 } 126 } 127 128 public final Object remove() 129 { 130 if( isEmpty() ) 131 { 132 throw new BufferUnderflowException( "The buffer is already empty" ); 133 } 134 135 Object element = m_elements[ m_start ]; 136 137 if( null != element ) 138 { 139 m_elements[ m_start++ ] = null; 140 141 if( m_start >= m_elements.length ) 142 { 143 m_start = 0; 144 } 145 146 m_full = false; 147 } 148 149 return element; 150 } 151 } 152 | Popular Tags |