/** * Read a PeerAddress from a Netty buffer. I did not want to include ChannelBuffer in the class * PeerAddress * * @param buffer The Netty buffer * @return A PeerAddress created from the buffer (deserialized) */ private static PeerAddress readPeerAddress(final ChannelBuffer buffer) { if (buffer.readableBytes() < 21) return null; Number160 id = readID(buffer); // peek int type = buffer.getUnsignedByte(buffer.readerIndex()); // now we know the length int len = PeerAddress.expectedSocketLength(type); if (buffer.readableBytes() < len) return null; PeerAddress peerAddress = new PeerAddress(id, buffer.array(), buffer.arrayOffset() + buffer.readerIndex()); buffer.skipBytes(len); return peerAddress; }
/** * Decodes bytes from a channel buffer * * @param ctx a channel handler context * @param channel a channel * @param msg a message * @return a byte array */ @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof ChannelBuffer)) { return msg; } ChannelBuffer buf = (ChannelBuffer) msg; byte[] array; if (buf.hasArray()) { if (buf.arrayOffset() == 0 && buf.readableBytes() == buf.capacity()) { array = buf.array(); } else { array = new byte[buf.readableBytes()]; buf.getBytes(0, array); } } else { array = new byte[buf.readableBytes()]; buf.getBytes(0, array); } return array; }
@Override public int arrayOffset() { return buffer.arrayOffset(); }