use std::collections::BTreeSet;
use super::validated::Marker;
use super::*;
pub trait Validator<T> {
fn validate(i: T) -> Result<T, Message>;
}
pub struct True;
pub struct False;
pub struct And2<A, B>(Marker<(A, B)>);
pub struct Or2<A, B>(Marker<(A, B)>);
pub struct Not<A>(Marker<A>);
pub type Chain2<A, B> = And2<A, B>;
pub type Chain3<A, B, C> = Chain2<Chain2<A, B>, C>;
pub type Chain4<A, B, C, D> = Chain2<Chain3<A, B, C>, D>;
pub type Chain5<A, B, C, D, E> = Chain2<Chain4<A, B, C, D>, E>;
pub type Chain6<A, B, C, D, E, F> = Chain2<Chain5<A, B, C, D, E>, F>;
pub type Chain7<A, B, C, D, E, F, G> = Chain2<Chain6<A, B, C, D, E, F>, G>;
pub type Chain8<A, B, C, D, E, F, G, H> = Chain2<Chain7<A, B, C, D, E, F, G>, H>;
pub type Chain<A, B = True, C = True, D = True, E = True, F = True, G = True, H = True> =
Chain8<A, B, C, D, E, F, G, H>;
pub type And3<A, B, C> = And2<And2<A, B>, C>;
pub type And4<A, B, C, D> = And2<And3<A, B, C>, D>;
pub type And5<A, B, C, D, E> = And2<And4<A, B, C, D>, E>;
pub type And6<A, B, C, D, E, F> = And2<And5<A, B, C, D, E>, F>;
pub type And7<A, B, C, D, E, F, G> = And2<And6<A, B, C, D, E, F>, G>;
pub type And8<A, B, C, D, E, F, G, H> = And2<And7<A, B, C, D, E, F, G>, H>;
pub type And<A, B = True, C = True, D = True, E = True, F = True, G = True, H = True> =
And8<A, B, C, D, E, F, G, H>;
pub type Or3<A, B, C> = Or2<A, Or2<B, C>>;
pub type Or4<A, B, C, D> = Or2<A, Or3<B, C, D>>;
pub type Or5<A, B, C, D, E> = Or2<A, Or4<B, C, D, E>>;
pub type Or6<A, B, C, D, E, F> = Or2<A, Or5<B, C, D, E, F>>;
pub type Or7<A, B, C, D, E, F, G> = Or2<A, Or6<B, C, D, E, F, G>>;
pub type Or8<A, B, C, D, E, F, G, H> = Or2<A, Or7<B, C, D, E, F, G, H>>;
pub type Or<A, B = False, C = False, D = False, E = False, F = False, G = False, H = False> =
Or8<A, B, C, D, E, F, G, H>;
pub struct Variant<const N: usize>;
pub struct SignedValueMin<const MIN: i64>;
pub struct SignedValueMax<const MAX: i64>;
pub type SignedValueRange<const MIN: i64, const MAX: i64> =
Chain2<SignedValueMin<MIN>, SignedValueMax<MAX>>;
pub struct UnsignedValueMin<const MIN: u64>;
pub struct UnsignedValueMax<const MAX: u64>;
pub type UnsignedValueRange<const MIN: u64, const MAX: u64> =
Chain2<UnsignedValueMin<MIN>, UnsignedValueMax<MAX>>;
pub struct FloatValueMinX1000<const MIN: i64>;
pub struct FloatValueMaxX1000<const MAX: i64>;
pub type FloatValueRangeX1000<const MIN: i64, const MAX: i64> =
Chain2<FloatValueMinX1000<MIN>, FloatValueMaxX1000<MAX>>;
pub struct LengthMin<const MIN: usize>;
pub struct LengthMax<const MAX: usize>;
pub struct LengthRange<const MIN: usize, const MAX: usize>;
pub struct AllChars<C: CharClass>(Marker<C>);
pub struct TrimChars<C: CharClass>(Marker<C>);
pub struct RemoveChars<C: CharClass>(Marker<C>);
pub type Trim = TrimChars<CharClassWhitespace>;
impl<A: Validator<T>, B: Validator<T>, T: Clone> Validator<T> for Or2<A, B> {
fn validate(s: T) -> Result<T, Message> {
match A::validate(s.clone()) {
Ok(v) => Ok(v),
Err(e) => B::validate(s).map_err(|_| e),
}
}
}
impl<A: Validator<T>, B: Validator<T>, T> Validator<T> for And2<A, B> {
fn validate(s: T) -> Result<T, Message> {
A::validate(s).and_then(|s| B::validate(s))
}
}
impl<A: Validator<T>, T: Clone> Validator<T> for Not<A> {
fn validate(s: T) -> Result<T, Message> {
match A::validate(s.clone()) {
Ok(_) => Err(Message::ContentProblem),
Err(_) => Ok(s),
}
}
}
impl<T> Validator<T> for True {
fn validate(i: T) -> Result<T, Message> {
Ok(i)
}
}
impl<T> Validator<T> for False {
fn validate(_: T) -> Result<T, Message> {
Err(Message::Empty)
}
}
impl<T, const N: usize> Validator<T> for Variant<N> {
fn validate(i: T) -> Result<T, Message> {
Ok(i)
}
}
macro_rules! impl_signed_value_min_max {
($t: ty) => {
impl<const MIN: i64> Validator<$t> for SignedValueMin<MIN> {
fn validate(i: $t) -> Result<$t, Message> {
const {
assert!(
MIN as i128 >= <$t>::MIN as i128 && MIN as i128 <= <$t>::MAX as i128,
concat!(
"SignedValueMin<MIN>: MIN is outside the range representable by ",
stringify!($t)
)
);
}
if (i as i128) < (MIN as i128) {
Err(Message::ValueExceedMin(MIN.to_string()))
} else {
Ok(i)
}
}
}
impl<const MAX: i64> Validator<$t> for SignedValueMax<MAX> {
fn validate(i: $t) -> Result<$t, Message> {
const {
assert!(
MAX as i128 >= <$t>::MIN as i128 && MAX as i128 <= <$t>::MAX as i128,
concat!(
"SignedValueMax<MAX>: MAX is outside the range representable by ",
stringify!($t)
)
);
}
if (i as i128) > (MAX as i128) {
Err(Message::ValueExceedMax(MAX.to_string()))
} else {
Ok(i)
}
}
}
};
}
impl_signed_value_min_max!(i8);
impl_signed_value_min_max!(i16);
impl_signed_value_min_max!(i32);
impl_signed_value_min_max!(i64);
impl_signed_value_min_max!(u8);
impl_signed_value_min_max!(u16);
impl_signed_value_min_max!(u32);
impl_signed_value_min_max!(u64);
macro_rules! impl_unsigned_value_min_max {
($t: ty) => {
impl<const MIN: u64> Validator<$t> for UnsignedValueMin<MIN> {
fn validate(i: $t) -> Result<$t, Message> {
const {
assert!(
MIN as u128 <= <$t>::MAX as u128,
concat!(
"UnsignedValueMin<MIN>: MIN is outside the range representable by ",
stringify!($t)
)
);
}
match TryInto::<u128>::try_into(i) {
Ok(v) if v >= MIN as u128 => Ok(i),
_ => Err(Message::ValueExceedMin(MIN.to_string())),
}
}
}
impl<const MAX: u64> Validator<$t> for UnsignedValueMax<MAX> {
fn validate(i: $t) -> Result<$t, Message> {
const {
assert!(
MAX as u128 <= <$t>::MAX as u128,
concat!(
"UnsignedValueMax<MAX>: MAX is outside the range representable by ",
stringify!($t)
)
);
}
match TryInto::<u128>::try_into(i) {
Ok(v) if v <= MAX as u128 => Ok(i),
Ok(_) => Err(Message::ValueExceedMax(MAX.to_string())),
Err(_) => Err(Message::ValueExceedMin(0.to_string())),
}
}
}
};
}
impl_unsigned_value_min_max!(i8);
impl_unsigned_value_min_max!(i16);
impl_unsigned_value_min_max!(i32);
impl_unsigned_value_min_max!(i64);
impl_unsigned_value_min_max!(u8);
impl_unsigned_value_min_max!(u16);
impl_unsigned_value_min_max!(u32);
impl_unsigned_value_min_max!(u64);
macro_rules! impl_float_value_x1000 {
($t: ty) => {
impl<const MIN: i64> Validator<$t> for FloatValueMinX1000<MIN> {
fn validate(i: $t) -> Result<$t, Message> {
if i.is_nan() {
return Err(Message::BadFormat(Format::Float));
}
let t = ((MIN as f64) / 1000.0) as $t;
if i < t {
Err(Message::ValueExceedMin(t.to_string()))
} else {
Ok(i)
}
}
}
impl<const MAX: i64> Validator<$t> for FloatValueMaxX1000<MAX> {
fn validate(i: $t) -> Result<$t, Message> {
if i.is_nan() {
return Err(Message::BadFormat(Format::Float));
}
let t = ((MAX as f64) / 1000.0) as $t;
if i > t {
Err(Message::ValueExceedMax(t.to_string()))
} else {
Ok(i)
}
}
}
};
}
impl_float_value_x1000!(f32);
impl_float_value_x1000!(f64);
impl<const MIN: usize> Validator<String> for LengthMin<MIN> {
fn validate(s: String) -> Result<String, Message> {
let len = s.chars().count();
if len < MIN {
Err(if len == 0 {
Message::Empty
} else {
Message::LengthExceedMin(MIN.to_string())
})
} else {
Ok(s)
}
}
}
impl<const MAX: usize> Validator<String> for LengthMax<MAX> {
fn validate(s: String) -> Result<String, Message> {
let len = s.chars().count();
if len > MAX {
Err(Message::LengthExceedMax(MAX.to_string()))
} else {
Ok(s)
}
}
}
impl<const MIN: usize, const MAX: usize> Validator<String> for LengthRange<MIN, MAX> {
fn validate(s: String) -> Result<String, Message> {
let len = s.chars().count();
if len < MIN {
Err(if len == 0 {
Message::Empty
} else {
Message::LengthExceedMin(MIN.to_string())
})
} else if len > MAX {
Err(Message::LengthExceedMax(MAX.to_string()))
} else {
Ok(s)
}
}
}
impl<C: CharClass> Validator<String> for TrimChars<C> {
fn validate(s: String) -> Result<String, Message> {
Ok(s.trim_matches(C::is_a).to_string())
}
}
impl<C: CharClass> Validator<String> for RemoveChars<C> {
fn validate(s: String) -> Result<String, Message> {
Ok(s.chars().filter(|c| !C::is_a(*c)).collect())
}
}
pub trait CharClass {
fn is_a(c: char) -> bool;
}
impl CharClass for True {
fn is_a(_: char) -> bool {
true
}
}
impl CharClass for False {
fn is_a(_: char) -> bool {
false
}
}
impl<A: CharClass, B: CharClass> CharClass for And2<A, B> {
fn is_a(c: char) -> bool {
A::is_a(c) && B::is_a(c)
}
}
impl<A: CharClass, B: CharClass> CharClass for Or2<A, B> {
fn is_a(c: char) -> bool {
A::is_a(c) || B::is_a(c)
}
}
impl<A: CharClass> CharClass for Not<A> {
fn is_a(c: char) -> bool {
!A::is_a(c)
}
}
pub struct CharClassJust<const C: char>;
impl<const C: char> CharClass for CharClassJust<C> {
fn is_a(c: char) -> bool {
c == C
}
}
const MAX_REPORTED_INVALID_CHARS: usize = 10;
impl<C: CharClass> Validator<String> for AllChars<C> {
fn validate(i: String) -> Result<String, Message> {
let mut invalid = BTreeSet::new();
for c in i.chars() {
if !C::is_a(c) {
invalid.insert(c);
if invalid.len() >= MAX_REPORTED_INVALID_CHARS {
break;
}
}
}
if invalid.is_empty() {
Ok(i)
} else {
Err(Message::InvalidChars(invalid.into_iter().collect()))
}
}
}
macro_rules! impl_char_class {
($t: ident, $m: ident, $e: literal $(, homoglyph_note: $ascii: ident)?) => {
#[doc = concat!("The [`CharClass`] of characters for which [`char::", stringify!($m), "`] returns `true`.")]
#[doc = $e]
$(
#[doc = ""]
#[doc = concat!(
"This matches on the full Unicode category and performs no confusable-character ",
"detection: visually similar characters from different scripts (e.g. Cyrillic `а` ",
"next to Latin `a`) are treated as distinct and may both pass. Where visual spoofing ",
"(e.g. usernames, handles) must be prevented, prefer [`", stringify!($ascii), "`] instead."
)]
)?
pub struct $t;
impl CharClass for $t {
fn is_a(c: char) -> bool {
c.$m()
}
}
};
($t: ident, $m: ident, $a: expr, $e: literal $(, homoglyph_note: $ascii: ident)?) => {
#[doc = concat!("The [`CharClass`] of characters for which [`char::", stringify!($m), "`] (with argument `", stringify!($a), "`) returns `true`.")]
#[doc = $e]
$(
#[doc = ""]
#[doc = concat!(
"This matches on the full Unicode category and performs no confusable-character ",
"detection: visually similar characters from different scripts (e.g. Cyrillic `а` ",
"next to Latin `a`) are treated as distinct and may both pass. Where visual spoofing ",
"(e.g. usernames, handles) must be prevented, prefer [`", stringify!($ascii), "`] instead."
)]
)?
pub struct $t;
impl CharClass for $t {
fn is_a(c: char) -> bool {
c.$m($a)
}
}
};
}
impl_char_class!(
CharClassAlphabetic,
is_alphabetic,
"type Name = Validated<NonEmptyString, AllChars<CharClassAlphabetic>>;",
homoglyph_note: CharClassAsciiAlphabetic
);
impl_char_class!(
CharClassAlphanumeric,
is_alphanumeric,
"type FileStem = Validated<NonEmptyString, AllChars<CharClassAlphanumeric>>;",
homoglyph_note: CharClassAsciiAlphanumeric
);
impl_char_class!(
CharClassAscii,
is_ascii,
"type AsciiText = Validated<NonEmptyString, AllChars<CharClassAscii>>;"
);
impl_char_class!(
CharClassAsciiAlphabetic,
is_ascii_alphabetic,
"type RomanName = Validated<NonEmptyString, AllChars<CharClassAsciiAlphabetic>>;"
);
impl_char_class!(
CharClassAsciiAlphanumeric,
is_ascii_alphanumeric,
"type ProductCode = Validated<NonEmptyString, AllChars<CharClassAsciiAlphanumeric>>;"
);
impl_char_class!(
CharClassAsciiControl,
is_ascii_control,
"type PlainLine = Validated<String, RemoveChars<CharClassAsciiControl>>;"
);
impl_char_class!(
CharClassAsciiDigit,
is_ascii_digit,
"type ZipCode = Validated<NonEmptyString, AllChars<CharClassAsciiDigit>>;"
);
impl_char_class!(
CharClassAsciiGraphic,
is_ascii_graphic,
"type Password = Validated<NonEmptyString, AllChars<CharClassAsciiGraphic>>;"
);
impl_char_class!(
CharClassAsciiHexdigit,
is_ascii_hexdigit,
"type ColorCode = Validated<NonEmptyString, AllChars<CharClassAsciiHexdigit>>;"
);
impl_char_class!(
CharClassAsciiLowercase,
is_ascii_lowercase,
"type Subdomain = Validated<NonEmptyString, AllChars<CharClassAsciiLowercase>>;"
);
impl_char_class!(
CharClassAsciiPunctuation,
is_ascii_punctuation,
"type SearchWord = Validated<String, RemoveChars<CharClassAsciiPunctuation>>;"
);
impl_char_class!(
CharClassAsciiUppercase,
is_ascii_uppercase,
"type CountryCode = Validated<NonEmptyString, AllChars<CharClassAsciiUppercase>>;"
);
impl_char_class!(
CharClassAsciiWhitespace,
is_ascii_whitespace,
"type Joined = Validated<String, RemoveChars<CharClassAsciiWhitespace>>;"
);
impl_char_class!(
CharClassControl,
is_control,
"type SafeText = Validated<String, RemoveChars<CharClassControl>>;"
);
impl_char_class!(
CharClassDigit,
is_digit,
10,
"type PhoneNumber = Validated<NonEmptyString, AllChars<CharClassDigit>>;"
);
impl_char_class!(
CharClassLowercase,
is_lowercase,
"type Tag = Validated<NonEmptyString, AllChars<CharClassLowercase>>;",
homoglyph_note: CharClassAsciiLowercase
);
impl_char_class!(
CharClassNumeric,
is_numeric,
"type NumeralText = Validated<NonEmptyString, AllChars<CharClassNumeric>>;",
homoglyph_note: CharClassAsciiDigit
);
impl_char_class!(
CharClassUppercase,
is_uppercase,
"type Acronym = Validated<NonEmptyString, AllChars<CharClassUppercase>>;",
homoglyph_note: CharClassAsciiUppercase
);
impl_char_class!(
CharClassWhitespace,
is_whitespace,
"type Trimmed = Validated<String, TrimChars<CharClassWhitespace>>;"
);