Isn't it amazing !
May 19, 2023Arkar Kaung Myat
Rust
Some of the snippets I love writing in Rust !
struct GreaterThanZero(i32);
impl TryFrom<i32> for GreaterThanZero {
type Error = &'static str;
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value > 0 {
Ok(Self(value))
} else {
Err("Number must be greater than zero")
}
}
}
// one more !
pub struct SubscriberName(String);
impl SubscriberName {
pub fn parse(s: String) -> Result<SubscriberName, String> {
let is_empty_or_whitespace = s.trim().is_empty();
let is_too_long = s.graphemes(true).count() > 256;
let forbidden_chars = ['/', '(', ')', '"', '<', '>', '\\', '{', '}'];
let is_forbidden_chars = s.chars().any(|c| forbidden_chars.contains(&c));
let is_valid = !(is_too_long | is_empty_or_whitespace | is_forbidden_chars);
match is_valid {
true => Ok(Self(s)),
false => Err(format!("{} is not a valid subscriber name.", s)),
}
}
pub fn inner(&self) -> &String {
&self.0
}
pub fn inner_mut(&mut self) -> &mut str {
&mut self.0
}
pub fn inner_ref(&self) -> &str {
&self.0
}
}
impl AsRef<str> for SubscriberName {
fn as_ref(&self) -> &str {
&self.0
}
}