Created
December 14, 2015 02:21
-
-
Save ochinchina/16faa0fd4a1d57f9e312 to your computer and use it in GitHub Desktop.
netty ByteBuf to InputStream adapter
This file contains hidden or 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
import java.io.IOException; | |
import java.io.InputStream; | |
import io.netty.buffer.ByteBuf; | |
public class ByteBufInputStream extends InputStream { | |
private ByteBuf buf = null; | |
private int len = 0; | |
public ByteBufInputStream( ByteBuf buf, int len ) { | |
this.buf = buf; | |
this.len = len; | |
} | |
@Override | |
public int available() throws IOException { | |
return this.len; | |
} | |
@Override | |
public void close() throws IOException { | |
} | |
@Override | |
public void mark(int readlimit) { | |
throw new RuntimeException( "not supported"); | |
} | |
@Override | |
public boolean markSupported() { | |
return false; | |
} | |
@Override | |
public int read() throws IOException { | |
ensureBytesAvailable( 1 ); | |
this.len --; | |
return this.buf.readByte(); | |
} | |
@Override | |
public int read(byte[] b) throws IOException { | |
return read( b, 0, b.length ); | |
} | |
@Override | |
public int read(byte[] b, int offset, int len) throws IOException { | |
ensureBytesAvailable( len ); | |
this.len -= len; | |
this.buf.readBytes(b, offset, len ); | |
return len; | |
} | |
@Override | |
public void reset() throws IOException { | |
throw new RuntimeException( "not supported"); | |
} | |
@Override | |
public long skip(long n) throws IOException { | |
ensureBytesAvailable( (int)n ); | |
len -= n; | |
return n; | |
} | |
private void ensureBytesAvailable( int n ) throws IOException { | |
if( n > this.len ) throw new IOException( "available bytes is less than " + n ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment