Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ std = []

[dev-dependencies]
hex-literal = "0.4.1"
bytes = "1.10.1"
51 changes: 50 additions & 1 deletion src/anybuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ enum WireType {
}

/// A minmal protobuf encoder.
#[derive(Default)]
#[derive(Default, Clone)]
pub struct Anybuf {
output: Vec<u8>,
}
Expand Down Expand Up @@ -519,6 +519,35 @@ impl Anybuf {
self.output
}

/// Takes the instance and returns the protobuf bytes.
/// The return type is defined by the caller and can be anything that implements `From<Vec<u8>>`.
/// Roughly speaking, `data.into_x()` is the same as calling `data.into_vec().into()`.
///
/// ## Examples
///
/// We create an Anybuf instance and then convert it into [Bytes], which just serves
/// as an example for a type that can be created from `Vec<u8>`.
///
/// ```
/// # use anybuf::Anybuf;
/// use bytes::Bytes;
///
/// // variable type known
/// let serialized: Bytes = Anybuf::new()
/// .append_repeated_int64(4, &[-30, 0, 17])
/// .into_x();
///
/// // explicit type parameter
/// let serialized = Anybuf::new()
/// .append_repeated_int64(4, &[-30, 0, 17])
/// .into_x::<Bytes>();
/// ```
///
/// [Bytes]: https://docs.rs/bytes/latest/bytes/struct.Bytes.html
pub fn into_x<T: From<Vec<u8>>>(self) -> T {
T::from(self.output)
}

fn append_tag(&mut self, field_number: u32, field_type: WireType) {
// The top 3 bits of a field number must be unset, ie.e this shift is safe for valid field numbers
// "The smallest field number you can specify is 1, and the largest is 2^29-1, or 536,870,911"
Expand Down Expand Up @@ -1027,4 +1056,24 @@ mod tests {
let data = Anybuf::new().append_repeated_message(11, &owned);
assert_eq!(data.into_vec(), hex!("5a0208015a0208025a020803"));
}

#[test]
fn into_x_works() {
use bytes::Bytes;

let data = Anybuf::new()
.append_string(1, "hello, world")
.append_repeated_int64(2, &[-30, 0, 17]);
let vec = data.clone().into_vec();
let bytes: Bytes = data.into_x();
assert_eq!(bytes, vec);

let serialized = Anybuf::new()
.append_repeated_int64(4, &[-30, 0, 17])
.into_x::<Bytes>();
assert_eq!(
serialized,
b" \xe2\xff\xff\xff\xff\xff\xff\xff\xff\x01 \0 \x11" as &[u8]
);
}
}