#![deny(missing_docs)]
use crate::__codegen::{
CanonicalDouble, Date as CodegenDate, DateTime as CodegenDateTime,
DateTimeTz as CodegenDateTimeTz, Decimal as CodegenDecimal, Duration as CodegenDuration,
ValidationError,
};
use type_bridge_contract::value::CanonicalString;
fn literal_error(field: &'static str, code: &'static str) -> ValidationError {
ValidationError::new(field, code)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Text(String);
impl Text {
pub fn new(value: impl Into<String>) -> Result<Self, ValidationError> {
let value = value.into();
CanonicalString::new(&value).map_err(|_| literal_error("text", "string_limit_exceeded"))?;
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
pub(crate) fn into_string(self) -> String {
self.0
}
}
#[derive(Clone, Debug)]
pub struct Regex(String);
impl Regex {
pub fn new(pattern: impl Into<String>) -> Result<Self, ValidationError> {
let pattern = pattern.into();
CanonicalString::new(&pattern)
.map_err(|_| literal_error("regex", "string_limit_exceeded"))?;
regex::Regex::new(&pattern).map_err(|_| literal_error("regex", "invalid_regex_pattern"))?;
Ok(Self(pattern))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
pub(crate) fn into_string(self) -> String {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Double(f64);
impl Double {
pub fn new(value: f64) -> Result<Self, ValidationError> {
CanonicalDouble::try_new(value)?;
Ok(Self(value))
}
#[must_use]
pub fn get(&self) -> f64 {
self.0
}
}
macro_rules! grammar_literal {
($(#[$doc:meta])* $name:ident, $inner:ident) => {
$(#[$doc])*
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct $name(String);
impl $name {
pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
let validated = $inner::try_new(value.as_ref())?;
Ok(Self(validated.as_str().to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
pub(crate) fn into_string(self) -> String {
self.0
}
}
};
}
grammar_literal!(
Decimal,
CodegenDecimal
);
grammar_literal!(
Date,
CodegenDate
);
grammar_literal!(
DateTime,
CodegenDateTime
);
grammar_literal!(
DateTimeTz,
CodegenDateTimeTz
);
grammar_literal!(
Duration,
CodegenDuration
);