a2kit_macro/
lib.rs

1//! # Procedural macro module for a2kit
2
3use core::fmt::Display;
4use core::fmt::Debug;
5
6#[derive(Debug)]
7pub enum DiskStructError {
8    OutOfData,
9    UnexpectedSize,
10    UnexpectedValue,
11    IllegalValue
12}
13
14impl Display for DiskStructError {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        match self {
17            Self::OutOfData => write!(f,"out of data while loading DiskStruct"),
18            Self::UnexpectedSize => write!(f,"size of data is not normal"),
19            Self::UnexpectedValue => write!(f,"unexpected value while loading DiskStruct"),
20            Self::IllegalValue => write!(f,"illegal value while loading DiskStruct")
21        }
22    }
23}
24
25impl std::error::Error for DiskStructError {
26}
27
28/// Automatically derived trait for any fixed length disk structure.
29/// This trait is used to create them, and move them in and out of buffers.
30pub trait DiskStruct {
31    /// create a structure with all zeros, requires concrete type
32    fn new() -> Self where Self: Sized;
33    /// flatten the structure into a byte stream
34    fn to_bytes(&self) -> Vec<u8>;
35    /// create a structure from a byte stream, requires concrete type
36    fn from_bytes(bytes: &[u8]) -> Result<Self, DiskStructError> where Self: Sized;
37    /// update a structure from a byte stream, OK to use on trait objects
38    fn update_from_bytes(&mut self,bytes: &[u8]) -> Result<(), DiskStructError>;
39    /// the length in bytes of the structure
40    fn len(&self) -> usize;
41    /// convenience function to call `from_bytes` and increment `ptr` by `len()`
42    fn from_bytes_adv(bytes: &[u8], ptr: &mut usize) -> Result<Self,DiskStructError> where Self: Sized {
43        match Self::from_bytes(bytes) {
44            Ok(res) => {
45                *ptr += res.len();
46                Ok(res)
47            }
48            Err(e) => Err(e)
49        }
50    }
51}