small-num

Crates.iosmall-num
lib.rssmall-num
version0.2.0
sourcesrc
created_at2024-05-20 14:44:44.214523
updated_at2024-05-21 21:22:36.537117
descriptionSmall crate used to create small numbers optimally.
homepage
repository
max_upload_size
id1245789
size17,562
Svyatoslav (hack3rmann)

documentation

README

Small numbers

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 number
  • Serialize (with serde feature)
  • Deserialize (with serde feature)

Crate features

  • serde enables Serialize and Deserialize derivation.
Commit count: 0

cargo fmt