Skip to content

Instantly share code, notes, and snippets.

@yuk1ty
Last active July 1, 2021 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuk1ty/16af4a0a6e8c143a390f047bf752c0d0 to your computer and use it in GitHub Desktop.
Save yuk1ty/16af4a0a6e8c143a390f047bf752c0d0 to your computer and use it in GitHub Desktop.
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