/** * Returns the total number of {@link ByteBuffer}s used including the one that might be used for * writing at the moment. * * @return Returns the total number of {@link ByteBuffer}s used including the one that might be * used for writing at the moment. */ public int getBuffersCount() { int count = byteBuffers.size(); ByteBuffer byteBuffer = super.getByteBuffer(); if (null != byteBuffer) { count++; } return count; }
/** * Returns the total writing size including the size that is currently available in the * ByteBuffer that is currently used for write. * * @return Returns the total writing size including the size that is currently available in the * ByteBuffer that is currently used for write. */ public long getTotalWriteSize() { long size = totalWriteSize; ByteBuffer byteBuffer = super.getByteBuffer(); if (null != byteBuffer) { size += byteBuffer.position(); } return size; }
/** This method produces a lot of garbage. Use it wisely! */ public static int calculateObjectSize(Object object, int bufferSize) { Kryo kryo = new Kryo(); ByteBufferOutputStream bbos = new ByteBufferOutputStream(bufferSize); Output output = new Output(bbos, bufferSize); kryo.writeClassAndObject(output, object); output.flush(); output.close(); return bbos.getByteBuffer().position(); }
/** * Flushes the stream by taking the current {@link ByteBuffer} using for writing. Buffer is flip * and put to the list of cached buffers. If the takeNewBuffer is <code>true</code> then a new * buffer will be placed and ready for write. * * @param takeNewBuffer * If the new buffers should be placed the super {@link OutputStream}. * @exception IOException * if an I/O error occurs. */ public void flush(boolean takeNewBuffer) throws IOException { ByteBuffer fullBuffer = super.getByteBuffer(); fullBuffer.flip(); byteBuffers.add(fullBuffer); totalWriteSize += fullBuffer.limit() - fullBuffer.position(); if (takeNewBuffer) { ByteBuffer byteBuffer = byteBufferProvider.acquireByteBuffer(); byteBuffer.clear(); super.setByteBuffer(byteBuffer); } else { super.setByteBuffer(null); } }
/** * Releases all buffers in the stream. */ private void releaseAllBuffers() { for (ByteBuffer byteBuffer : byteBuffers) { byteBufferProvider.releaseByteBuffer(byteBuffer); } byteBuffers.clear(); ByteBuffer currentBuffer = super.getByteBuffer(); if (null != currentBuffer) { byteBufferProvider.releaseByteBuffer(currentBuffer); super.setByteBuffer(null); } } }
/** * {@inheritDoc} */ @Override public void write(byte[] b, int off, int len) throws IOException { int remaining = super.getByteBuffer().remaining(); if (remaining >= len) { super.write(b, off, len); } else { super.write(b, off, remaining); this.flush(); this.write(b, off + remaining, len - remaining); } }