Crates.io | small-num |
lib.rs | small-num |
version | 0.2.0 |
source | src |
created_at | 2024-05-20 14:44:44.214523 |
updated_at | 2024-05-21 21:22:36.537117 |
description | Small crate used to create small numbers optimally. |
homepage | |
repository | |
max_upload_size | |
id | 1245789 |
size | 17,562 |
Small numbers can be used to describe some constrained data. For example, a number of alignment bytes:
use small_num::small_num;
small_num! {
#[derive(Clone, Debug, PartialEq, Copy, Eq, PartialOrd, Ord, Hash)]
pub enum AlignBytes: [1, 2, 4];
}
let bytes = AlignBytes::new(2);
assert_eq!(bytes, Some(AlignBytes::_2));
assert_eq!(AlignBytes::new(3), None);
assert_eq!(std::mem::size_of::<Option<AlignBytes>>(), 1);
Or an integer valid for a spicific range:
use small_num::small_num;
small_num! {
#[derive(Clone, Debug, PartialEq, Copy, Eq, PartialOrd, Ord, Hash)]
pub enum U7: ..128;
}
assert_eq!(U7::new(0), Some(U7::_0));
assert_eq!(U7::new(50), Some(U7::_50));
assert_eq!(U7::new(127), Some(U7::_127));
assert_eq!(U7::new(128), None);
assert_eq!(std::mem::size_of::<Option<U7>>(), 1);
It can be casted to an integer with as
operator:
use small_num::small_num;
small_num! {
#[derive(Clone, Debug, PartialEq, Copy, Eq, PartialOrd, Ord, Hash)]
pub enum Num50to100: 50..=100;
}
assert_eq!(Num50to100::new(69).unwrap() as u32, 69);
Where clause can be used to derive supported traits:
use small_num::small_num;
small_num! {
#[derive(Clone)]
pub enum MySmallNumber: [0, 42, 121]
where
Self: Debug + Serialize;
}
Supported traits in the where clause:
Debug
- prints your small number as a regular numberSerialize
(with serde
feature)Deserialize
(with serde
feature)serde
enables Serialize
and Deserialize
derivation.