Skip to content

Instantly share code, notes, and snippets.

@ncruces
Last active May 21, 2018 02:02
Show Gist options
  • Save ncruces/0e6e625899645f5a88e4d7444d696130 to your computer and use it in GitHub Desktop.
Save ncruces/0e6e625899645f5a88e4d7444d696130 to your computer and use it in GitHub Desktop.
ByteBuffer backed SeekableByteChannel
package io.github.ncruces.utils;
import java.nio.ByteBuffer;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.SeekableByteChannel;
import static java.lang.Math.min;
public final class ByteBufferChannel implements SeekableByteChannel {
private final ByteBuffer buf;
public ByteBufferChannel(ByteBuffer buffer) {
if (buffer == null) throw new NullPointerException();
buf = buffer;
}
@Override
public synchronized int read(ByteBuffer dst) {
if (buf.remaining() == 0) return -1;
int count = min(dst.remaining(), buf.remaining());
if (count > 0) {
ByteBuffer tmp = buf.slice();
tmp.limit(count);
dst.put(tmp);
buf.position(buf.position() + count);
}
return count;
}
@Override
public synchronized int write(ByteBuffer src) {
if (buf.isReadOnly()) throw new NonWritableChannelException();
int count = min(src.remaining(), buf.remaining());
if (count > 0) {
ByteBuffer tmp = src.slice();
tmp.limit(count);
buf.put(tmp);
src.position(src.position() + count);
}
return count;
}
@Override
public synchronized long position() {
return buf.position();
}
@Override
public synchronized ByteBufferChannel position(long newPosition) {
if ((newPosition | Integer.MAX_VALUE - newPosition) < 0) throw new IllegalArgumentException();
buf.position((int)newPosition);
return this;
}
@Override
public synchronized long size() { return buf.limit(); }
@Override
public synchronized ByteBufferChannel truncate(long size) {
if ((size | Integer.MAX_VALUE - size) < 0) throw new IllegalArgumentException();
int limit = buf.limit();
if (limit > size) buf.limit((int)size);
return this;
}
@Override
public boolean isOpen() { return true; }
@Override
public void close() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment