Skip to content

Instantly share code, notes, and snippets.

@zhoulifu
Created March 18, 2016 14:26
Show Gist options
  • Save zhoulifu/7f5a9dd0cb6b3136e748 to your computer and use it in GitHub Desktop.
Save zhoulifu/7f5a9dd0cb6b3136e748 to your computer and use it in GitHub Desktop.
ByteArrayBuffer
public class ByteArrayBuffer {
private byte[] buffer;
private int len;
public ByteArrayBuffer() {
this(4096);
}
public ByteArrayBuffer(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity can not be negative");
}
this.buffer = new byte[capacity];
}
public void append(byte[] b, int off, int len) {
if (b == null) {
return;
}
if (off >= 0 && off <= b.length && len >= 0 && off + len >= 0 && off + len <= b.length) {
if (len != 0) {
int newLen = this.len + len;
if (newLen > this.buffer.length) {
this.expand(newLen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newLen;
}
} else {
throw new IndexOutOfBoundsException("off: " + off + " len: " + len + " b.length: " + b.length);
}
}
private void expand(int newLen) {
byte[] newBuffer = new byte[Math.max(this.buffer.length << 1, newLen)];
System.arraycopy(this.buffer, 0, newBuffer, 0, this.len);
this.buffer = newBuffer;
}
public byte[] toByteArray() {
byte[] b = new byte[this.len];
System.arraycopy(this.buffer, 0, b, 0, this.len);
return b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment