binary_codec/
utils.rs

1use crate::{DeserializationError, SerializationError, SerializerConfig, dyn_int::{read_dynint, write_dynint}};
2
3pub fn ensure_size(config: &SerializerConfig, bytes: &[u8], required: usize) -> Result<bool, DeserializationError> {
4    if config.pos + required > bytes.len() {
5        return Err(DeserializationError::NotEnoughBytes(config.pos + required - bytes.len()));
6    }
7    Ok(config.pos + required == bytes.len())
8}
9
10pub fn slice<'a>(config: &mut SerializerConfig, bytes: &'a [u8], length: usize, increment: bool) -> Result<&'a [u8], DeserializationError> {
11    ensure_size(config, bytes, length)?;
12    let slice = &bytes[config.pos..config.pos + length];
13    if increment {
14        config.pos += length;
15    }
16    Ok(slice)
17}
18
19pub fn get_read_size<'a>(bytes: &'a [u8], size_key: Option<&str>, config: &mut SerializerConfig) -> Result<usize, DeserializationError> {
20    let size = if let Some(size_key) = size_key {
21        // Special case: dynamic length prefix
22        if size_key == "__dynamic" {
23            return read_dynint(bytes, config).map(|v| v as usize);
24        }
25
26        config.get_length(size_key).unwrap_or(bytes.len() - config.pos)
27    } else {
28        bytes.len() - config.pos
29    };
30
31    ensure_size(config, bytes, size)?;
32    Ok(size)
33}
34
35pub fn write_size(size: usize, size_key: Option<&str>, buffer: &mut Vec<u8>, config: &mut SerializerConfig) -> Result<(), SerializationError> {
36    if let Some(size_key) = size_key {
37        // Special case: dynamic length prefix
38        if size_key == "__dynamic" {
39            return write_dynint(size as u128, buffer, config);
40        }
41
42        if let Some(expected) = config.get_length(size_key) {
43            if expected != size {
44                return Err(SerializationError::UnexpectedLength(expected, size));
45            }
46        }
47    }
48
49    Ok(())
50}