public static <V> ByteBuf writeObject(Transform<V, ByteBuf> converter, V object) { ByteBuf buffer = null; try { ByteBuf objectBuffer = converter.convert(object); int length = objectBuffer.readableBytes(); ByteBuf lengthBuffer = Unpooled.buffer(2); lengthBuffer.writeShort(length); buffer = Unpooled.wrappedBuffer(lengthBuffer, objectBuffer); } catch (Exception e) { LOG.error("Error occurred while writing object to buffer: {}", e); } return buffer; }
public static <T, V> V readObject(ByteBuf buffer, Transform<ByteBuf, V> decoder) { int length = 0; if (null != buffer && buffer.readableBytes() > 2) { length = buffer.readUnsignedShort(); } else { return null; } ByteBuf objBuffer = buffer.readSlice(length); V obj = null; try { obj = decoder.convert(objBuffer); } catch (Exception e) { LOG.error("Error occurred while trying to read object from buffer: {}", e); } return obj; }