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;
10/// A module for writing data.
11pub mod write;
12
13pub use write::OptionalNbt;
14
15const DEFAULT_BOUND: usize = i16::MAX as _;
16
17/// A trait for reading data from a cursor.
18pub trait ReadFrom: Sized {
19    /// Reads data from a cursor.
20    fn read(data: &mut Cursor<&[u8]>) -> Result<Self>;
21}
22
23/// A trait for writing data to a writer.
24pub trait WriteTo {
25    /// Writes data to a writer.
26    fn write(&self, writer: &mut impl Write) -> Result<()>;
27}
28
29/// A trait for reading prefixed data from a cursor.
30pub trait PrefixedRead: Sized {
31    /// Reads prefixed data from a cursor with a bound.
32    fn read_prefixed_bound<P: TryInto<usize> + ReadFrom>(
33        data: &mut Cursor<&[u8]>,
34        bound: usize,
35    ) -> Result<Self>;
36
37    /// Reads prefixed data from a cursor.
38    fn read_prefixed<P: TryInto<usize> + ReadFrom>(data: &mut Cursor<&[u8]>) -> Result<Self> {
39        Self::read_prefixed_bound::<P>(data, DEFAULT_BOUND)
40    }
41}
42
43/// A trait for writing prefixed data to a writer.
44pub trait PrefixedWrite {
45    /// Writes prefixed data to a writer with a bound.
46    fn write_prefixed_bound<P: TryFrom<usize> + WriteTo>(
47        &self,
48        writer: &mut impl Write,
49        bound: usize,
50    ) -> Result<()>;
51
52    /// Writes prefixed data to a writer.
53    fn write_prefixed<P: TryFrom<usize> + WriteTo>(&self, writer: &mut impl Write) -> Result<()> {
54        self.write_prefixed_bound::<P>(writer, DEFAULT_BOUND)
55    }
56}