VisibleByteArrayOutputStream extends OutputStream { public byte[] toByteArrayNoCopy() { if (count == buf.length) { return buf; } return Arrays.copyOf(buf, count); } VisibleByteArrayOutputStream();  VisibleByteArrayOutputStream(int size); @Override void write(int b); @Override void write(byte b[], int off, int len); @Override void write(byte b[]); void writeTo(OutputStream out); void reset(); byte[] xxhash64(); byte[] toByteArray(); byte[] toByteArrayNoCopy(); int size(); byte[] getBuffer(); ByteBuffer toByteBuffer(); String toString(Charset charset); @Override void close();  }
@Test public void testToByteArrayNoCopy() throws Exception { byte[] content = "foo".getBytes(StandardCharsets.UTF_8); byte[] content2 = "fooa".getBytes(StandardCharsets.UTF_8); try (VisibleByteArrayOutputStream oo = new VisibleByteArrayOutputStream(3)) { oo.write(content); assertArrayEquals(content, oo.toByteArray()); assertNotSame(content, oo.toByteArray()); assertSame(oo.getBuffer(), oo.toByteArrayNoCopy()); oo.write('a'); assertArrayEquals(content2, oo.toByteArray()); assertNotSame(content, oo.toByteArray()); assertNotSame(oo.getBuffer(), oo.toByteArrayNoCopy()); } }