1 36 package org.columba.ristretto.io; 37 38 import org.columba.ristretto.concurrency.Mutex; 39 40 45 public class MemBuffer { 46 private final static int INCREMENT = 1024; 47 48 private byte[] buffer; 49 50 private int len; 51 52 private Mutex mutex; 53 54 57 public MemBuffer() { 58 this(INCREMENT); 59 } 60 61 66 public MemBuffer(int size) { 67 buffer = new byte[size]; 68 69 len = 0; 70 71 mutex = new Mutex(); 72 } 73 74 79 public void append(int value) { 80 mutex.lock(); 81 if( len == buffer.length) growBuffer(buffer.length + INCREMENT); 82 83 buffer[len++] = (byte) value; 84 mutex.release(); 85 } 86 87 94 public void append(byte[] array, int offset, int length) { 95 mutex.lock(); 96 int available = buffer.length - len; 97 if( length > available) growBuffer(buffer.length + ( length - available > INCREMENT ? length : INCREMENT)); 98 System.arraycopy(array, offset, buffer, len, length); 99 len += length; 100 mutex.release(); 101 } 102 103 108 public void append(byte[] array) { 109 append(array, 0, array.length); 110 } 111 112 118 public int get(int pos) { 119 if( pos > len ) throw new ArrayIndexOutOfBoundsException (pos); 120 121 return buffer[pos]; 122 } 123 124 132 public int get(int pos, byte[] array) { 133 return get(pos, array, 0, array.length); 134 } 135 136 146 public int get(int pos, byte[] array, int offset, int length) { 147 mutex.lock(); 148 int result = length > (len-pos) ? (len-pos) : length; 149 if( result < 0 ) { 150 mutex.release(); 151 throw new ArrayIndexOutOfBoundsException (pos); 152 } 153 154 System.arraycopy(buffer, pos, array, offset, result); 155 mutex.release(); 156 157 return result; 158 } 159 160 165 public int size() { 166 mutex.lock(); 167 int result = len; 168 mutex.release(); 169 return result; 170 } 171 172 177 private void growBuffer(int newSize) { 178 byte[] newBuffer = new byte[newSize]; 179 System.arraycopy(buffer,0,newBuffer,0,buffer.length); 180 buffer = newBuffer; 181 } 182 183 184 } 185 | Popular Tags |