All Downloads are FREE. Search and download functionalities are using the official Maven repository.

bt.protocol.handler.BitfieldHandler Maven / Gradle / Ivy

There is a newer version: 1.10
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy