#zero #generic #zst #const-zero #const-one

zero-one

用于泛型代码的零和一ZSTs

1个不稳定版本

0.1.0 2021年12月3日

#5#zst

MIT/Apache

11KB
214

const@Zeroconst@One ZSTs 用于泛型代码。

这些可以用于泛型代码,其中 01 文字不适用。

use zero_one::{Zero, One};

assert_eq!(u64::from(Zero), 0);
assert_eq!(i8::from(Zero), 0);
assert_eq!(u64::from(One), 1);
assert_eq!(i8::from(One), 1);

assert_eq!(Zero, 0);
assert_ne!(Zero, 1);
assert_ne!(One, 0);
assert_eq!(One, 1);

assert!(Zero < 10);
assert!(-10 < Zero);
assert!(One < 10);
assert!(-10 < One);

assert!(matches!(Zero::try_from(0_u16), Ok(Zero)));
assert!(matches!(Zero::try_from(1_i16), Err(_)));
assert!(matches!(One::try_from(0_u16), Err(_)));
assert!(matches!(One::try_from(1_i16), Ok(One)));

assert_eq!(Zero.to_string(), "0");
assert_eq!(One.to_string(), "1");

即使在泛型代码之外,它们也能使使用一些 std 类型变得更简单

use zero_one::{Zero, One};
use std::num::*;

assert_eq!(NonZeroU64::from(One), NonZeroU64::new(1).unwrap());
assert_eq!(NonZeroI8::from(One), NonZeroI8::new(1).unwrap());

它们甚至可以在想要进行 as 转型的宏中工作

use zero_one::{Zero, One};

assert_eq!(Zero as u32, 0);
assert_eq!(Zero as i128, 0);
assert_eq!(One as u32, 1);
assert_eq!(One as i128, 1);

您还可以用它们进行数学运算

use zero_one::{Zero, One};

assert_eq!(Zero + 5, 5);
assert_eq!(Zero | 5, 5);
assert_eq!(One * 5, 5);
assert_eq!(One + 5, 6);

assert_eq!(Zero % One, Zero);
assert_eq!(One - Zero, One);
assert_eq!(Zero * 5, Zero);
assert_eq!(Zero & 5, Zero);

assert_eq!(10 + One, 11);
assert_eq!(10 + Zero, 10);

无运行时依赖