bt.protocol.handler.BitfieldHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bt-core Show documentation
Show all versions of bt-core Show documentation
BitTorrent Client Library (Core)
package bt.protocol.handler;
import bt.protocol.Bitfield;
import bt.protocol.DecodingContext;
import bt.protocol.EncodingContext;
import java.nio.ByteBuffer;
public final class BitfieldHandler extends UniqueMessageHandler {
public BitfieldHandler() {
super(Bitfield.class);
}
@Override
public int doDecode(DecodingContext context, ByteBuffer buffer) {
return decodeBitfield(context, buffer, buffer.remaining());
}
@Override
public boolean doEncode(EncodingContext context, Bitfield message, ByteBuffer buffer) {
if (buffer.remaining() < message.getBitfield().length) {
return false;
}
buffer.put(message.getBitfield());
return true;
}
// bitfield:
private static int decodeBitfield(DecodingContext context, ByteBuffer buffer, int length) {
int consumed = 0;
if (buffer.remaining() >= length) {
byte[] bitfield = new byte[length];
buffer.get(bitfield);
context.setMessage(new Bitfield(bitfield));
consumed = length;
}
return consumed;
}
}