betterproto-rust-codec (Rust-backed Protobuf Codec)

0.1.1 · active · verified Fri Apr 10

betterproto-rust-codec provides a high-performance codec for `betterproto` messages, leveraging a Rust implementation to serialize and deserialize Protobuf wire format. It significantly speeds up conversion compared to Python-native alternatives, especially for large or frequently processed messages. The current version is 0.1.1, and releases are generally ad-hoc, often in response to `betterproto` updates or targeted performance improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `betterproto` message, instantiate the `ProtobufCodec`, and then use it to efficiently encode and decode the message to and from Protobuf wire format bytes.

import betterproto
from betterproto.lib.google.protobuf import Timestamp
from betterproto_rust_codec import ProtobufCodec
import datetime

@betterproto.dataclass
class MyMessage(betterproto.Message):
    name: str = betterproto.string_field(1)
    value: int = betterproto.int32_field(2)
    timestamp: Timestamp = betterproto.message_field(3, wraps=True)

# Create an instance of the codec
codec = ProtobufCodec()

# Create a betterproto message
now_timestamp = Timestamp().from_datetime(datetime.datetime.now(datetime.timezone.utc))
original_message = MyMessage(
    name="Test Name",
    value=123,
    timestamp=now_timestamp
)

print(f"Original message: {original_message}")

# Encode the message
encoded_bytes = codec.encode(original_message)
print(f"Encoded bytes length: {len(encoded_bytes)}")

# Decode the message
decoded_message = codec.decode(MyMessage, encoded_bytes)

# Verify
print(f"Decoded message: {decoded_message}")
assert original_message.name == decoded_message.name
assert original_message.value == decoded_message.value
assert original_message.timestamp.seconds == decoded_message.timestamp.seconds
print("\nEncode/Decode successful!")

view raw JSON →