Non blank string type for approach suggested by Alexis King - "Parse, don't validate".
Add dependency:
cargo add non-blank-string-rs
Use:
let username = NonBlankString::from_str("Hellow")?;
let username: NonBlankString = "Hellow".parse()?;
// fn login(username: &str)
login(&username)
Useful for REST API Endpoints, i.e. /api/register
accepts:
#[derive(Deserialize)]
struct UserRegistrationRequest {
pub username: NonBlankString,
...
}
Incoming JSON with blank value in username
field will raise deserialization error (Serde).
Add to Cargo.toml
:
[dev-dependencies]
non-blank-string-rs = { version = "1.0.3", features = ["utils"] }
Functions:
get_random_nonblank_string()
- return randomNonBlankString
. Useful for tests.
- Alexis King, article - Parse, don't validate
- Justin Wernick, article - The Newtype Pattern In Rust