1 50 package org.apache.avalon.excalibur.collections; 51 52 59 public class CircularBuffer 60 { 61 protected Object [] m_buffer; 62 protected int m_bufferSize; 63 protected int m_contentSize; 64 protected int m_head; 65 protected int m_tail; 66 67 public CircularBuffer( int size ) 68 { 69 m_buffer = new Object [ size ]; 70 m_bufferSize = size; 71 m_contentSize = 0; 72 m_head = 0; 73 m_tail = 0; 74 } 75 76 public CircularBuffer() 77 { 78 this( 32 ); 79 } 80 81 public boolean isEmpty() 82 { 83 return ( m_contentSize == 0 ); 84 } 85 86 public int getContentSize() 87 { 88 return m_contentSize; 89 } 90 91 public int getBufferSize() 92 { 93 return m_bufferSize; 94 } 95 96 public void append( final Object o ) 97 { 98 if( m_contentSize >= m_bufferSize ) 99 { 100 int j = 0; 101 int i = m_tail; 102 Object [] tmp = new Object [ m_bufferSize * 2 ]; 103 104 while( m_contentSize > 0 ) 105 { 106 i++; 107 i %= m_bufferSize; 108 j++; 109 m_contentSize--; 110 tmp[ j ] = m_buffer[ i ]; 111 } 112 m_buffer = tmp; 113 m_tail = 0; 114 m_head = j; 115 m_contentSize = j; 116 m_bufferSize *= 2; 117 } 118 119 m_buffer[ m_head ] = o; 120 m_head++; 121 m_head %= m_bufferSize; 122 m_contentSize++; 123 } 124 125 public Object get() 126 { 127 if( m_contentSize <= 0 ) 128 { 129 return null; 130 } 131 132 Object o = m_buffer[ m_tail ]; 133 m_tail++; 134 m_tail %= m_bufferSize; 135 m_contentSize--; 136 return o; 137 } 138 } 139 140 | Popular Tags |