use crate::structs::{ArchiveSerializer, StructError, StructResult}; use serde::Serialize; pub enum ByteOrder { Le, Be, Ne, } pub enum VariantIndexType { U8, U16, U32, U64, I8, I16, I32, I64, } macro_rules! impl_byte_order { ($($n:ident),+) => { impl ByteOrder {$( pub fn $n(&self, num: $n) -> Vec { match self { ByteOrder::Le => num.to_le_bytes().to_vec(), ByteOrder::Be => num.to_be_bytes().to_vec(), ByteOrder::Ne => num.to_ne_bytes().to_vec(), } } )+} }; } impl_byte_order!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64); impl VariantIndexType { pub fn cast(&self, num: u32, byte_order: &ByteOrder) -> StructResult> { Ok(match self { VariantIndexType::U8 => byte_order.u8(num .try_into() .map_err(|_| StructError::IncorrectEnumVariant)?), VariantIndexType::U16 => byte_order.u16( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), VariantIndexType::U32 => byte_order.u32( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), VariantIndexType::U64 => byte_order.u64( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), VariantIndexType::I8 => byte_order.i8(num .try_into() .map_err(|_| StructError::IncorrectEnumVariant)?), VariantIndexType::I16 => byte_order.i16( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), VariantIndexType::I32 => byte_order.i32( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), VariantIndexType::I64 => byte_order.i64( num.try_into() .map_err(|_| StructError::IncorrectEnumVariant)?, ), }) } } pub struct Settings { pub(crate) byte_order: ByteOrder, pub(crate) variant_index_type: VariantIndexType, } impl Settings { pub fn new(byte_order: ByteOrder, variant_index_type: VariantIndexType) -> Self { Self { byte_order, variant_index_type, } } pub fn byte_order(mut self, order: ByteOrder) -> Self { self.byte_order = order; self } pub fn variant_index_type(mut self, index_type: VariantIndexType) -> Self { self.variant_index_type = index_type; self } pub fn serialize(self, object: &impl Serialize) -> StructResult> { let mut serializer = ArchiveSerializer::new(self); object.serialize(&mut serializer)?; Ok(serializer.to_bytes()) } } impl Default for Settings { fn default() -> Self { Self { byte_order: ByteOrder::Le, variant_index_type: VariantIndexType::U32, } } }