diff --git a/src/lib.rs b/src/lib.rs index 64f26ec..7931c36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -347,7 +347,7 @@ impl Setting { let u = min.remove(0); assert_eq!(u, 'u'); let min: u8 = min.parse().unwrap(); - Ok(Setting::MinFieldSize(Type::new(min))) + Ok(Setting::MinFieldSize(Type::ux(min))) } name => return Err(format!("'{name}' is not a supported setting.")), } diff --git a/src/type.rs b/src/type.rs index ca97012..9c70962 100644 --- a/src/type.rs +++ b/src/type.rs @@ -4,26 +4,29 @@ use proc_macro2::TokenStream; use quote::{quote, format_ident}; #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] -pub struct Type(u8); +pub enum Type { + Bool, + Ux(u8), +} impl Type { - pub const BOOL: Type = Type(1); + pub const BOOL: Type = Type::Bool; - pub fn new(len: u8) -> Type { + pub fn ux(len: u8) -> Type { match len { 0 => panic!(), - 1..=128 => Type(len.try_into().unwrap()), + 1..=128 => Type::ux(len.try_into().unwrap()), 129..=u8::MAX => panic!("Integers larger than u128 are not supported."), } } pub fn for_template(len: u8) -> Type { match len { - 8 => Type(8), - 16 => Type(16), - 32 => Type(32), - 64 => Type(64), - 128 => Type(128), + 8 => Type::ux(8), + 16 => Type::ux(16), + 32 => Type::ux(32), + 64 => Type::ux(64), + 128 => Type::ux(128), len => panic!("Template length must be 8, 16, 32, 64, or 128, but was {len}."), } } @@ -31,23 +34,27 @@ impl Type { pub fn for_field(len: u8, precision: Precision) -> Type { match len { 0 => panic!(), - 1..=128 if precision == Precision::Ux => Type(len.try_into().unwrap()), - 1 => Type(1), - 2..=8 => Type(8), - 9..=16 => Type(16), - 17..=32 => Type(32), - 33..=64 => Type(64), - 65..=128 => Type(128), + 1..=128 if precision == Precision::Ux => Type::ux(len.try_into().unwrap()), + 1 => Type::ux(1), + 2..=8 => Type::ux(8), + 9..=16 => Type::ux(16), + 17..=32 => Type::ux(32), + 33..=64 => Type::ux(64), + 65..=128 => Type::ux(128), 129..=u8::MAX => panic!("Integers larger than u128 are not supported."), } } pub fn is_standard(self) -> bool { - matches!(self.0, 1 | 8 | 16 | 32 | 64 | 128) + if let Type::Ux(ux) = self { + matches!(ux, 1 | 8 | 16 | 32 | 64 | 128) + } else { + false + } } pub fn concat(self, other: Type) -> Type { - Type::for_field(self.0 + other.0, Precision::Standard) + Type::for_field(self.size() + other.size(), Precision::Standard) } pub fn to_token_stream(self) -> TokenStream { @@ -58,20 +65,26 @@ impl Type { quote! { ux::#ident } } } + + pub fn size(self) -> u8 { + match self { + Type::Bool => 1, + Type::Ux(ux) => ux, + } + } } impl From for Type { fn from(value: u8) -> Type { - Type(value) + Type::Ux(value) } } impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.0 == 1 { - write!(f, "bool") - } else { - write!(f, "u{}", self.0) + match *self { + Type::Bool => write!(f, "bool"), + Type::Ux(ux) => write!(f, "u{}", ux) } } }