Stream: general

Topic: (Ab)using const generics for validation


Jake Goulding (Jul 14 2019 at 02:30, on Zulip):

I've been thinking about data validation in the context of webapps a bunch recently. Combined with const generics, we can get some code like this for validating the length of a value:

#![feature(const_generics)]

#[derive(Debug)]
struct LenString<const MAX: usize>(String);

impl<const MAX: usize> LenString<{ MAX }> {
    fn new(s: impl Into<String>) -> Option<Self> {
        let s = s.into();

        if s.len() < MAX {
            Some(Self(s))
        } else {
            None
        }
    }
}

fn main() {
    println!("{:?}", LenString::<5>::new("hello")); // None
    println!("{:?}", LenString::<5>::new("hell"));  // Some
}
Jake Goulding (Jul 14 2019 at 02:32, on Zulip):

I'm trying to think if there's some way of doing the same for a more complicated validation, such as matching a regex. I'm not seeing anything obvious, but maybe smarter folk than me might have an inkling.

Jake Goulding (Jul 14 2019 at 02:32, on Zulip):

At least, not until Regex::new is const fn ;-)

Last update: Nov 20 2019 at 12:30UTC