#enums #numbers #integer #deserialize #data #num #constrained

small-num

Small crate used to create small numbers optimally

3 unstable releases

0.2.0 May 21, 2024
0.1.1 May 20, 2024
0.1.0 May 20, 2024

#1676 in Encoding

44 downloads per month

MIT license

17KB
331 lines

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.

Dependencies

~170KB