Skip to content
/ bytes Public

Library providing universal interface for having an immutable representation of sequence of bytes.

License

Notifications You must be signed in to change notification settings

avast/bytes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Bytes

Build Version

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))
  • reading directly from InputStream (in some implementations, e.g. ByteArrayBytes.readFrom(is) or ByteArrayBytes.readFrom(is, offset, length))

Usage

Parsing Google Protocol Buffer message: Assume NotificationData is a class generated by protoc.

Bytes bytes = ...

try (InputStream bytesStream = bytes.newInputStream()) {
    NotificationData message = NotificationData.parseFrom(bytesStream);
}

Serializing Google Protocol Buffer message to Bytes:

NotificationData message = ...
try (Bytes.BuilderStream builder = ByteBufBytes.newBuilder(message.getSerializedSize())) {
    message.writeTo(builder);
    Bytes bytes = builder.toBytes();
}

...or serialize the message to ByteString as usual and wrap it with ByteStringBytes.

JDK-based implementations

The core module contains two implementations:

  • ByteArrayBytes - backed by byte[]
  • ByteBufferBytes - backed by java.nio.ByteBuffer
ByteArrayBytes bab = ByteArrayBytes.copyFrom(new byte[]{0, 0, 7});

ByteBufferBytes bbb = ByteBufferBytes.copyFrom(ByteBuffer.allocate(1024)); // the most useless buffer ever

com.google.protobuf.ByteString wrapper

The gpb module provides ByteStringBytes that implements Bytes by wrapping com.google.protobuf.ByteString.

ByteStringBytes bsb = ByteStringBytes.wrap(ByteString.copyFromUtf8("foo"));

About

Library providing universal interface for having an immutable representation of sequence of bytes.

Resources

License

Stars

Watchers

Forks

Packages

No packages published