Rust's NonZero and Parsing Over Validation
I just found out one of the most interesting things that makes Rust what it is and it
is the generic NonZero.
To begin with, what is the NonZero type. If you guessed that it is a number that can not be zero,
you would be a hundred percent correct.
NonZero is just a wrapper around a number where you assert that it will not be zero. You can use it like this
use std::num::NonZero;
fn main() { let x: NonZero<usize> = NonZero::new(1).unwrap(); println!("{}", x.get());}And this is a possible implementation I came up with my meager rust skills
mod sealed { pub trait Zeroable: Copy + PartialEq { const ZERO: Self; }}use sealed::Zeroable;
macro_rules! impl_zeroable { ($($t:ty),*) => { $( impl Zeroable for $t { const ZERO: Self = 0; } )* };}impl_zeroable!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
#[derive(Copy, Clone, PartialEq, Eq, Debug)]pub struct NonZero<T: Zeroable>(T);
impl<T: Zeroable> NonZero<T> { pub fn new(val: T) -> Option<Self> { if val == T::ZERO { None } else { Some(Self(val)) } }
pub const unsafe fn new_unchecked(val: T) -> Self { Self(val) }
pub fn get(self) -> T { self.0 }}I found this really interesting because it reveals a philosophy that Rust seems to abide with, which is parsing should supersede validation. To a lot of many, this could be useless. After all, why do this when a simple if zero is enough. But to a lot of others, this is utilizing the very powerful type system to prove our invariants true. Now, my invariant is not associated simply with the accompaning if condition, but with the actual type.
After seeing this type, if for some reason, I need to have a number that can not be some arbitrary number , my first
thought would be creating a new type called NonN that I can leverage to my advantage and force the compiler to help me with. If for some reason, I need to change that to another number, it will be one line of code and that’s it.
Of course, it doesn’t have to be this case, but you get the idea.
Pretty fascinating how advanced type systems are, and people’s ideas of utilizing them.
That’s it, Peace. I started school, so my frequency will decrease :(