1 21 22 package org.armedbear.j; 23 24 public final class ByteBuffer 25 { 26 private byte[] buffer; 27 private int used; 28 private final static int DEFAULT_CAPACITY = 16; 29 30 public ByteBuffer() 31 { 32 buffer = new byte[DEFAULT_CAPACITY]; 33 } 34 35 public ByteBuffer(int length) throws NegativeArraySizeException 36 { 37 if (length < 0) 38 throw new NegativeArraySizeException (); 39 buffer = new byte[length]; 40 } 41 42 public int length() 43 { 44 return used; 45 } 46 47 public int capacity() 48 { 49 return buffer.length; 50 } 51 52 public void ensureCapacity(int minimumCapacity) 53 { 54 if (minimumCapacity <= 0 || buffer.length >= minimumCapacity) 55 return; 56 int newCapacity = buffer.length * 2 + 2; 57 if (newCapacity < minimumCapacity) 58 newCapacity = minimumCapacity; 59 byte newBuffer[] = new byte[newCapacity]; 60 System.arraycopy(buffer, 0, newBuffer, 0, used); 61 buffer = newBuffer; 62 } 63 64 public void append(byte[] bytes) 65 { 66 if (used + bytes.length > buffer.length) 67 ensureCapacity(used + bytes.length); 68 System.arraycopy(bytes, 0, buffer, used, bytes.length); 69 used += bytes.length; 70 } 71 72 public void append(byte b) 73 { 74 if (used + 1 > buffer.length) 75 ensureCapacity(used + 1); 76 buffer[used++] = b; 77 } 78 79 public void setLength(int newLength) throws IndexOutOfBoundsException 80 { 81 if (newLength < 0) 82 throw new ArrayIndexOutOfBoundsException (newLength); 83 ensureCapacity(newLength); 84 used = newLength; 85 } 86 87 public byte[] getBytes() 88 { 89 return buffer; 90 } 91 } 92 | Popular Tags |