Created
March 18, 2016 14:26
-
-
Save zhoulifu/7f5a9dd0cb6b3136e748 to your computer and use it in GitHub Desktop.
ByteArrayBuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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