Skip to main content

karyon_p2p/
util.rs

1use bincode::{config, Decode, Encode};
2
3use crate::Result;
4
5fn bincode_config() -> impl config::Config {
6    config::standard().with_fixed_int_encoding()
7}
8
9/// Encode the given type `T` into a `Vec<u8>`.
10pub fn encode<T: Encode>(src: &T) -> Result<Vec<u8>> {
11    Ok(bincode::encode_to_vec(src, bincode_config())?)
12}
13
14/// Decode a given type `T` from the given slice. Returns the decoded value
15/// along with the number of bytes read.
16pub fn decode<T: Decode<()>>(src: &[u8]) -> Result<(T, usize)> {
17    let (result, bytes_read) = bincode::decode_from_slice::<T, _>(src, bincode_config())?;
18    Ok((result, bytes_read))
19}