graphite_binary/slice_serialization/
mod.rs1use thiserror::Error;
2
3mod option;
4
5mod sized_array;
6pub use sized_array::SizedArray;
7
8mod single_byte;
9pub use single_byte::Single;
10
11mod varint;
12pub use varint::VarInt;
13
14mod blob;
15pub use blob::GreedyBlob;
16pub use blob::NBTBlob;
17pub use blob::SizedBlob;
18pub use blob::SizedString;
19pub use blob::WriteOnlyBlob;
20
21mod primitive;
22pub use primitive::BigEndian;
23pub use primitive::LittleEndian;
24
25mod from;
26pub use from::AttemptFrom;
27
28#[derive(Error, Debug)]
29pub enum BinaryReadError {
30 #[error("buffer does not contain enough bytes to perform read")]
31 NotEnoughRemainingBytes,
32 #[error("string byte count ({0}) exceeds maximum ({1})")]
33 BlobBytesExceedMaxSize(usize, usize),
34 #[error("string character count ({0}) exceeds maximum ({1})")]
35 StringCharsExceedMaxSize(usize, usize),
36 #[error("didn't fully consume buffer, {0} byte(s) remained")]
37 DidntFullyConsume(usize),
38}
39
40pub trait SliceSerializable<'a, T = Self> {
41 type CopyType: Copy;
42 fn as_copy_type(t: &'a T) -> Self::CopyType;
43
44 fn read(bytes: &mut &'a [u8]) -> anyhow::Result<T>;
45 fn read_fully(bytes: &mut &'a [u8]) -> anyhow::Result<T> {
46 let serialized = Self::read(bytes)?;
47
48 if bytes.is_empty() {
49 Ok(serialized)
50 } else {
51 Err(BinaryReadError::DidntFullyConsume(bytes.len()).into())
52 }
53 }
54
55 unsafe fn write(bytes: &mut [u8], data: Self::CopyType) -> &mut [u8];
58 fn get_write_size(data: Self::CopyType) -> usize;
59}
60
61pub use graphite_binary_macros::slice_serializable;