sos_core/encoding/
mod.rs

1//! Binary encoding implementation.
2mod v1;
3
4/// Version 1 encoding.
5pub use v1::VERSION as VERSION1;
6
7/// Current encoding version.
8pub use v1::VERSION;
9
10use crate::Result;
11use binary_stream::{
12    futures::{BinaryReader, Decodable, Encodable},
13    Endian, Options,
14};
15use tokio::io::{AsyncRead, AsyncSeek};
16
17/// Helper for mapping an encoding error.
18pub fn encoding_error(
19    e: impl std::error::Error + Send + Sync + 'static,
20) -> std::io::Error {
21    std::io::Error::new(std::io::ErrorKind::Other, e)
22}
23
24/// Maximum buffer size allowed when encoding and decoding.
25const MAX_BUFFER_SIZE: usize = 1024 * 1024 * 16;
26
27/// Standard encoding options.
28pub fn encoding_options() -> Options {
29    Options {
30        endian: Endian::Little,
31        max_buffer_size: Some(MAX_BUFFER_SIZE),
32    }
33}
34
35/// Encode to a binary buffer.
36pub async fn encode(encodable: &impl Encodable) -> Result<Vec<u8>> {
37    Ok(binary_stream::futures::encode(encodable, encoding_options()).await?)
38}
39
40/// Decode from a binary buffer.
41pub async fn decode<T: Decodable + Default>(buffer: &[u8]) -> Result<T> {
42    Ok(binary_stream::futures::decode(buffer, encoding_options()).await?)
43}
44
45/// Helper to decode a UUIDv4.
46#[doc(hidden)]
47pub async fn decode_uuid<R: AsyncRead + AsyncSeek + Unpin + Send>(
48    reader: &mut BinaryReader<R>,
49) -> std::result::Result<uuid::Uuid, std::io::Error> {
50    let uuid: [u8; 16] = reader
51        .read_bytes(16)
52        .await?
53        .as_slice()
54        .try_into()
55        .map_err(encoding_error)?;
56    Ok(uuid::Uuid::from_bytes(uuid))
57}