binary_codec/
utils.rs

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