This library contains an immutable representation of sequence of bytes: com.avast.bytes.Bytes
.
The goal is to provide single immutable representation of bytes that is not dependent on a third-party library (like com.google.protobuf.ByteString
).
However, multiple implementations of the Bytes
interface can be created using third-party libraries to take advantage of their benefits (io.netty.buffer.ByteBuf
for example).
Implementations that require third-party dependencies will be separated to their own module, while the core module provides only the API and implementations
based on Java standard library.
Features of Bytes include:
- reading encapsulated data using random (
Bytes.byteAt(int)
) and linear (Bytes.newInputStream()
) access - zero copy substring views (
Bytes.view(int, int)
) - zero copy concat (
Bytes.concat(otherBytes)
) - utility methods for reading & writing hex strings (
Bytes.copyFromHex(someBytes.toHexString)
)
Parsing Google Protocol Buffer message:
Assume NotificationData
is a class generated by protoc
.
Bytes bytes = ...
NotificationData message = NotificationData.parseFrom(bytes.newInputStream());
Serializing Google Protocol Buffer message to Bytes
:
NotificationData message = ...
Bytes.BuilderStream builder = ByteBufBytes.newBuilder(message.getSerializedSize());
message.writeTo(builder);
Bytes bytes = builder.toBytes();
The core
module contains two implementations:
ByteArrayBytes
- backed bybyte[]
ByteBufferBytes
- backed byjava.nio.ByteBuffer
ByteArrayBytes bab = ByteArrayBytes.copyFrom(new byte[]{0, 0, 7});
ByteBufferBytes bbb = ByteBufferBytes.copyFrom(ByteBuffer.allocate(1024)); // the most useless buffer ever
The gpb
module provides ByteStringBytes
that implements Bytes
by wrapping com.google.protobuf.ByteString
.
ByteStringBytes bsb = ByteStringBytes.wrap(ByteString.copyFromUtf8("foo"));