#codec #protobuf #buffer #protocols #decoder #encoder #bytecodec

protobuf_codec

Encoders and decoders for Protocol Buffers based on bytecodec crate

12 releases

0.2.8 Oct 6, 2019
0.2.7 May 18, 2019
0.2.6 Oct 17, 2018
0.2.4 May 28, 2018
0.1.2 May 15, 2018

#2212 in Encoding

38 downloads per month
Used in 10 crates (6 directly)

MIT license

150KB
4K SLoC

protobuf_codec

protobuf_codec Documentation Build Status Code Coverage License: MIT

A Rust implementation of encoders and decoders for Protocol Buffers based on bytecodec crate.

Documentation

Examples

An encoder/decoder for SearchRequest message defined in the Language Guide.

extern crate bytecodec;
extern crate protobuf_codec;

use bytecodec::EncodeExt;
use bytecodec::io::{IoDecodeExt, IoEncodeExt};
use protobuf_codec::field::{Fields, FieldDecoder, FieldEncoder, MaybeDefault};
use protobuf_codec::field::num::{F1, F2, F3};
use protobuf_codec::message::{MessageDecoder, MessageEncoder};
use protobuf_codec::scalar::{Int32Decoder, Int32Encoder, StringDecoder, StringEncoder};

// syntax = "proto3";
//
// message SearchRequest {
//   string query = 1;
//   int32 page_number = 2;
//   int32 result_per_page = 3;
// }
type SearchRequestEncoder = MessageEncoder<
    Fields<(
        MaybeDefault<FieldEncoder<F1, StringEncoder>>,
        MaybeDefault<FieldEncoder<F2, Int32Encoder>>,
        MaybeDefault<FieldEncoder<F3, Int32Encoder>>,
    )>,
>;
type SearchRequestDecoder = MessageDecoder<
    Fields<(
        MaybeDefault<FieldDecoder<F1, StringDecoder>>,
        MaybeDefault<FieldDecoder<F2, Int32Decoder>>,
        MaybeDefault<FieldDecoder<F3, Int32Decoder>>,
    )>,
>;

fn main() {
    let mut buf = Vec::new();
    let mut encoder = SearchRequestEncoder::with_item(("foo".to_owned(), 3, 10)).unwrap();
    encoder.encode_all(&mut buf).unwrap();
    assert_eq!(buf, [10, 3, 102, 111, 111, 16, 3, 24, 10]);

    let mut decoder = SearchRequestDecoder::default();
    let message = decoder.decode_exact(&buf[..]).unwrap();
    assert_eq!(message, ("foo".to_owned(), 3, 10));
}

References

Dependencies

~2MB
~43K SLoC