1 package org.apache.thrift.transport; 2 3 import java.nio.BufferOverflowException; 4 import java.nio.BufferUnderflowException; 5 import java.nio.ByteBuffer; 6 import org.apache.thrift.TConfiguration; 7 8 /** ByteBuffer-backed implementation of TTransport. */ 9 public final class TByteBuffer extends TEndpointTransport { 10 private final ByteBuffer byteBuffer; 11 12 /** 13 * Creates a new TByteBuffer wrapping a given NIO ByteBuffer. 14 * 15 * @param byteBuffer the NIO ByteBuffer to wrap. 16 * @throws TTransportException on error. 17 */ TByteBuffer(ByteBuffer byteBuffer)18 public TByteBuffer(ByteBuffer byteBuffer) throws TTransportException { 19 super(new TConfiguration()); 20 this.byteBuffer = byteBuffer; 21 updateKnownMessageSize(byteBuffer.capacity()); 22 } 23 24 @Override isOpen()25 public boolean isOpen() { 26 return true; 27 } 28 29 @Override open()30 public void open() {} 31 32 @Override close()33 public void close() {} 34 35 @Override read(byte[] buf, int off, int len)36 public int read(byte[] buf, int off, int len) throws TTransportException { 37 // 38 checkReadBytesAvailable(len); 39 40 final int n = Math.min(byteBuffer.remaining(), len); 41 if (n > 0) { 42 try { 43 byteBuffer.get(buf, off, n); 44 } catch (BufferUnderflowException e) { 45 throw new TTransportException("Unexpected end of input buffer", e); 46 } 47 } 48 return n; 49 } 50 51 @Override write(byte[] buf, int off, int len)52 public void write(byte[] buf, int off, int len) throws TTransportException { 53 try { 54 byteBuffer.put(buf, off, len); 55 } catch (BufferOverflowException e) { 56 throw new TTransportException("Not enough room in output buffer", e); 57 } 58 } 59 60 /** 61 * Gets the underlying NIO ByteBuffer. 62 * 63 * @return the underlying NIO ByteBuffer. 64 */ getByteBuffer()65 public ByteBuffer getByteBuffer() { 66 return byteBuffer; 67 } 68 69 /** 70 * Convenience method to call clear() on the underlying NIO ByteBuffer. 71 * 72 * @return this instance. 73 */ clear()74 public TByteBuffer clear() { 75 byteBuffer.clear(); 76 return this; 77 } 78 79 /** 80 * Convenience method to call flip() on the underlying NIO ByteBuffer. 81 * 82 * @return this instance. 83 */ flip()84 public TByteBuffer flip() { 85 byteBuffer.flip(); 86 return this; 87 } 88 89 /** 90 * Convenience method to convert the underlying NIO ByteBuffer to a plain old byte array. 91 * 92 * @return the byte array backing the underlying NIO ByteBuffer. 93 */ toByteArray()94 public byte[] toByteArray() { 95 final byte[] data = new byte[byteBuffer.remaining()]; 96 byteBuffer.slice().get(data); 97 return data; 98 } 99 } 100