Skip to content

Instantly share code, notes, and snippets.

@yuk1ty

yuk1ty/validated_str.rs

Last active Jul 1, 2021
Embed
What would you like to do?
Create string type validated
use std::{marker::PhantomData, str::FromStr};
use super::error::ValidationError;
pub trait ValidationStrategy {
fn validate(target: &str) -> Result<String, ValidationError>;
}
pub struct NonEmptyString<V>
where
V: ValidationStrategy,
{
pub value: String,
_marker: PhantomData<fn() -> V>,
}
pub mod rules {
use super::ValidationStrategy;
use crate::types::error::ValidationError;
pub struct LessThanEqualFour;
impl ValidationStrategy for LessThanEqualFour {
fn validate(target: &str) -> Result<String, ValidationError> {
if target.len() <= 4 {
Ok(target.to_string())
} else {
Err(ValidationError::InvalidFormat(format!(
"{} must be less than equal 4",
&target
)))
}
}
}
pub struct LessThanEqualEight;
impl ValidationStrategy for LessThanEqualEight {
fn validate(target: &str) -> Result<String, ValidationError> {
if target.len() <= 8 {
Ok(target.to_string())
} else {
Err(ValidationError::InvalidFormat(format!(
"{} must be less than equal 8",
&target
)))
}
}
}
}
impl<T> FromStr for NonEmptyString<T>
where
T: ValidationStrategy,
{
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Err(ValidationError::NotAllowedEmpty);
}
let validated = T::validate(s)?;
Ok(NonEmptyString {
value: validated,
_marker: PhantomData,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment