Util: New zero-copy BAOS

WIP, to be hooked in
This commit is contained in:
zzz
2020-11-02 12:12:20 +00:00
parent 057eca56d5
commit f69563da75
3 changed files with 64 additions and 1 deletions

View File

@ -0,0 +1,52 @@
package net.i2p.util;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
/**
* OutputStream to InputStream adapter.
* Zero-copy where possible. Unsynchronized.
* This is NOT a Pipe.
* Do NOT reset after writing.
*
* @since 0.9.48
*/
public class ByteArrayStream extends ByteArrayOutputStream {
public ByteArrayStream() {
super();
}
public ByteArrayStream(int size) {
super(size);
}
/**
* @throws IllegalStateException if previously written
*/
@Override
public void reset() {
if (count > 0)
throw new IllegalStateException();
}
/**
* Zero-copy only if the data fills the buffer.
* Use asInputStream() for guaranteed zero-copy.
*/
@Override
public byte[] toByteArray() {
if (count == buf.length)
return buf;
return Arrays.copyOfRange(buf, 0, count);
}
/**
* All data previously written. Zero-copy. Not a Pipe.
* Data written after this call will not appear.
*/
public ByteArrayInputStream asInputStream() {
return new ByteArrayInputStream(buf, 0, count);
}
}