Skip to main content

steel_utils/serial/
mod.rs

1//! This module contains traits for serializing and deserializing data.
2use std::io::{Cursor, Result, Write};
3
4/// A module for reading prefixed data.
5pub mod prefixed_read;
6/// A module for writing prefixed data.
7pub mod prefixed_write;
8/// A module for reading data.
9pub mod read;
10pub mod vec_as_map;
11/// A module for writing data.
12pub mod write;
13
14pub use write::OptionalNbt;
15
16const DEFAULT_BOUND: usize = i16::MAX as _;
17
18/// A trait for reading data from a cursor.
19pub trait ReadFrom: Sized {
20    /// Reads data from a cursor.
21    fn read(data: &mut Cursor<&[u8]>) -> Result<Self>;
22}
23
24/// A trait for writing data to a writer.
25pub trait WriteTo {
26    /// Writes data to a writer.
27    fn write(&self, writer: &mut impl Write) -> Result<()>;
28
29    /// writes a slice as consecutive values without a length prefix
30    fn write_slice(values: &[Self], writer: &mut impl Write) -> Result<()>
31    where
32        Self: Sized,
33    {
34        for value in values {
35            value.write(writer)?;
36        }
37
38        Ok(())
39    }
40}
41
42/// A trait for reading prefixed data from a cursor.
43pub trait PrefixedRead: Sized {
44    /// Reads prefixed data from a cursor with a bound.
45    fn read_prefixed_bound<P: TryInto<usize> + ReadFrom>(
46        data: &mut Cursor<&[u8]>,
47        bound: usize,
48    ) -> Result<Self>;
49
50    /// Reads prefixed data from a cursor.
51    fn read_prefixed<P: TryInto<usize> + ReadFrom>(data: &mut Cursor<&[u8]>) -> Result<Self> {
52        Self::read_prefixed_bound::<P>(data, DEFAULT_BOUND)
53    }
54}
55
56/// A trait for writing prefixed data to a writer.
57pub trait PrefixedWrite {
58    /// Writes prefixed data to a writer with a bound.
59    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
60        &self,
61        writer: &mut impl Write,
62        bound: usize,
63    ) -> Result<()>;
64
65    /// Writes prefixed data to a writer.
66    fn write_prefixed<P: TryFrom<usize> + WriteTo>(&self, writer: &mut impl Write) -> Result<()> {
67        self.write_prefixed_bound::<P>(writer, DEFAULT_BOUND)
68    }
69}