Skip to main content

non_empty_name

Macro non_empty_name 

Source
macro_rules! non_empty_name {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident;
        $(#[$error_meta:meta])*
        $error_vis:vis error $error:ident($message:literal);
    ) => { ... };
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident;
        $(#[$error_meta:meta])*
        $error_vis:vis error $error:ident($message:literal);
        normalize = $normalize:expr;
    ) => { ... };
}
Expand description

Define a string newtype that is never empty.

The type decodes from a string and fails on the empty string with the given error type. It compares and sorts like its string, so it works as a map key that is looked up by &str. An optional last argument rewrites the string before it is stored.

ephemeris_forge::non_empty_name! {
    /// A tag name.
    pub struct TagName;
    /// A tag name was the empty string.
    pub error EmptyTagName("tag name cannot be empty");
}

assert_eq!(TagName::try_from("v1".to_owned()).unwrap().as_str(), "v1");
assert_eq!(TagName::try_from(String::new()), Err(EmptyTagName));