diff --git a/Cargo.toml b/Cargo.toml index 6c13844..156d970 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,8 +18,9 @@ categories = ["embedded", "no-std", "data-structures"] [dependencies] [features] -default = [] +default = ["const-generics"] # This is a no-op feature only provided for compatibility in case it is # explicitly selected by a user. This crate works without explicit indication # both on std and no_std systems. std = [] +const-generics = [] diff --git a/src/lib.rs b/src/lib.rs index de735d9..ffaf6b7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,61 @@ use lib::core::cmp::{Ord, Ordering, PartialOrd}; use lib::core::fmt::{Binary, Display, Formatter, LowerHex, Octal, UpperHex}; +#[cfg(feature = "const-generics")] +pub trait ToUnsignedType { + type Output; +} + +#[cfg(feature = "const-generics")] +pub trait ToSignedType { + type Output; +} + +#[cfg(feature = "const-generics")] +pub struct Const; + +#[cfg(feature = "const-generics")] +pub type Unsigned = as ToUnsignedType>::Output; + +#[cfg(feature = "const-generics")] +pub type Signed = as ToSignedType>::Output; + +#[cfg(feature = "const-generics")] +macro_rules! impl_type_dispatch { + (signed, $name:ident, $bits:expr) => { + impl ToSignedType for Const<$bits> { + type Output = $name; + } + }; + (unsigned, $name:ident, $bits:expr) => { + impl ToUnsignedType for Const<$bits> { + type Output = $name; + } + }; +} + +#[cfg(feature = "const-generics")] +impl_type_dispatch!(signed, i8, 8); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(signed, i16, 16); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(signed, i32, 32); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(signed, i64, 64); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(signed, i128, 128); + +#[cfg(feature = "const-generics")] +impl_type_dispatch!(unsigned, u8, 8); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(unsigned, u16, 16); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(unsigned, u32, 32); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(unsigned, u64, 64); +#[cfg(feature = "const-generics")] +impl_type_dispatch!(unsigned, u128, 128); + macro_rules! define_unsigned { ($name:ident, $bits:expr, $type:ident) => {define_unsigned!(#[doc=""], $name, $bits, $type);}; (#[$doc:meta], $name:ident, $bits:expr, $type:ident) => { @@ -51,6 +106,9 @@ macro_rules! define_unsigned { implement_common!($name, $bits, $type); + #[cfg(feature = "const-generics")] + impl_type_dispatch!(unsigned, $name, $bits); + } } @@ -79,6 +137,9 @@ macro_rules! define_signed { implement_common!($name, $bits, $type); + #[cfg(feature = "const-generics")] + impl_type_dispatch!(signed, $name, $bits); + } }