validatable 0.1.0

Define validated data types once and share them between the frontend and backend of isomorphic Rust web applications, with plain, input, and form representations
Documentation
//! The [`ValidatedValue`] wrapper: values whose validity is guaranteed by
//! their type.

use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

use super::*;

pub(crate) type Marker<T> = PhantomData<fn() -> T>;

/// A value of type `P` that has passed validation, with the validators
/// recorded in the type.
///
/// * `P` — the plain (validated) value type
/// * `I` — the input type the value is parsed from (e.g. `String`)
/// * `VI` — a [`Validator`] applied to the input *before* parsing
/// * `VP` — a [`Validator`] applied to the parsed value *after* parsing
///
/// The only ways to construct a `ValidatedValue` are
/// [`from_input`](Self::from_input),
/// [`from_input_owned`](Self::from_input_owned),
/// [`from_raw`](Self::from_raw), and
/// deserialization. Holding a `ValidatedValue` therefore proves that the
/// contained value satisfied its validators at construction time — except for
/// deserialization, which performs **no validation** (see below).
///
/// Derefs to `P`, so its methods are callable directly (e.g. `.len()` on a
/// `Validated<String, …>`). There is no `DerefMut`, since mutating through it
/// could invalidate the validators that were checked at construction time.
/// This does not protect a `P` with interior mutability (e.g. `RefCell`,
/// `Mutex`, `Cell`): the shared reference returned by `Deref`/`AsRef` still
/// allows mutating the value in place, bypassing the validators.
///
/// Most code uses the [`Validated`] alias, which fills in `I` from the plain
/// type's [`DefaultInputType`].
///
/// # Serde
///
/// `Serialize`/`Deserialize` are only implemented when the `serde` feature
/// is enabled (off by default). `ValidatedValue` serializes transparently
/// as its inner value. **Deserialization does not validate**: it is
/// treated as a plain conversion, intended for restoring values from
/// trusted storage. If the source is untrusted, deserialize the
/// input/form representation instead and validate it. Note that the plain
/// type's own `Deserialize` implementation still applies its own
/// constraints: deserializing an empty string into a
/// `Validated<NonEmptyString, …>` fails, for example, because
/// [`NonEmptyString`] itself rejects it.
///
/// ```
/// use validatable::*;
///
/// type ShortName = Validated<String, LengthRange<1, 3>>;
///
/// let name = ShortName::from_input(&"Ada".to_string()).unwrap();
///
/// # #[cfg(feature = "serde")]
/// # {
/// // The following requires the `serde` feature (off by default).
/// // Serialization is transparent.
/// assert_eq!(serde_json::to_string(&name).unwrap(), r#""Ada""#);
///
/// // Deserialization does NOT run validators: this value is too long,
/// // but deserializing it succeeds anyway.
/// let restored: ShortName = serde_json::from_str(r#""this is way too long""#).unwrap();
/// assert_eq!(restored.to_string(), "this is way too long");
/// # }
/// ```
pub struct ValidatedValue<P, I, VI, VP>(P, Marker<(I, VI, VP)>);

/// A validated value using the default input type of `P`.
///
/// `Validated<P, VI, VP>` is [`ValidatedValue`] with the input type taken
/// from `P`'s [`DefaultInputType`] (for numbers and strings this is
/// `String`). `VI` validates (and possibly transforms) the raw input before
/// parsing; `VP` validates the parsed value.
///
/// Combine validators with [`Chain`], [`And`], [`Or`], and [`Not`]:
///
/// ```
/// use validatable::*;
///
/// // Input is trimmed, then must be 1..=8 characters.
/// type UserName = Validated<String, Chain<Trim, LengthRange<1, 8>>>;
/// // Input is trimmed, parsed as u32, and the value must be 5..=100.
/// type Quantity = Validated<u32, Trim, UnsignedValueRange<5, 100>>;
///
/// let name = UserName::from_input(&"  Ada  ".to_string()).unwrap();
/// assert_eq!(name.to_string(), "Ada"); // Trim transformed the input
///
/// let quantity = Quantity::from_input(&" 42 ".to_string()).unwrap();
/// assert_eq!(u32::from(quantity), 42);
///
/// assert_eq!(
///     UserName::from_input(&"   ".to_string()),
///     Err(Message::Empty)
/// );
/// assert_eq!(
///     Quantity::from_input(&"3".to_string()),
///     Err(Message::ValueExceedMin("5".to_string()))
/// );
/// ```
///
/// To use the same validation as two distinct, incompatible types, add a
/// [`Variant`] marker to one of the chains.
pub type Validated<P, VI, VP = True> =
    ValidatedValue<P, <P as DefaultInputType>::InputType, VI, VP>;

impl<P, I, VI, VP> ValidatedValue<P, I, VI, VP> {
    /// Validates raw input and constructs the value.
    ///
    /// Runs the full pipeline: `VI` on the input, then
    /// [`Parsable::parse`], then `VP` on the parsed value. Returns the first
    /// [`Message`] produced by any stage.
    pub fn from_input(i: &I) -> Result<Self, Message>
    where
        I: Clone,
        VI: Validator<I>,
        VP: Validator<P>,
        P: Parsable<I>,
    {
        Self::from_input_owned(i.clone())
    }

    /// Validates an owned input and constructs the value.
    ///
    /// Same pipeline as [`from_input`](Self::from_input), but consumes the
    /// input instead of cloning it, so `I` does not need to be `Clone`.
    ///
    /// ```
    /// use validatable::*;
    ///
    /// type UserName = Validated<String, Chain<Trim, LengthRange<1, 8>>>;
    ///
    /// let name = UserName::from_input_owned("  Ada  ".to_string()).unwrap();
    /// assert_eq!(name.to_string(), "Ada");
    /// ```
    pub fn from_input_owned(i: I) -> Result<Self, Message>
    where
        VI: Validator<I>,
        VP: Validator<P>,
        P: Parsable<I>,
    {
        VI::validate(i).and_then(|i| P::parse(i).and_then(|p| Self::from_raw(p)))
    }

    /// Constructs the value from an already-parsed `P`, running only `VP`.
    ///
    /// The input validator `VI` is *not* applied, since there is no input to
    /// validate. If your invariants live in `VI` (common for `String` types),
    /// prefer [`from_input`](Self::from_input).
    pub fn from_raw(p: P) -> Result<Self, Message>
    where
        VP: Validator<P>,
    {
        VP::validate(p).map(|p| ValidatedValue(p, PhantomData))
    }

    /// Consumes the wrapper and returns the inner value.
    pub fn into_raw(self) -> P {
        self.0
    }
}

/// Conversion from an input representation into a plain value.
///
/// `parse` turns input that already passed the input validator into the
/// plain type, reporting failures as [`Message`]s (e.g.
/// [`Message::BadFormat`] for a malformed number). Implementations are
/// provided for `String` itself and for the primitive number types
/// (from `String`).
pub trait Parsable<I>: Sized {
    /// Returns the parsed value on success, or a [`Message`] describing why
    /// `i` could not be parsed.
    fn parse(i: I) -> Result<Self, Message>;
}

impl Parsable<String> for String {
    fn parse(i: String) -> Result<Self, Message> {
        Ok(i)
    }
}

impl<P: PartialEq, I, VI, VP> PartialEq for ValidatedValue<P, I, VI, VP> {
    fn eq(&self, r: &Self) -> bool {
        self.0.eq(&r.0)
    }
}

impl<P: Eq, I, VI, VP> Eq for ValidatedValue<P, I, VI, VP> {}

impl<P: PartialOrd, I, VI, VP> PartialOrd for ValidatedValue<P, I, VI, VP> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<P: Ord, I, VI, VP> Ord for ValidatedValue<P, I, VI, VP> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        P::cmp(&self.0, &other.0)
    }
}

impl<P: Hash, I, VI, VP> Hash for ValidatedValue<P, I, VI, VP> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<P: Clone, I, VI, VP> Clone for ValidatedValue<P, I, VI, VP> {
    fn clone(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<P: Copy, I, VI, VP> Copy for ValidatedValue<P, I, VI, VP> {}

impl<P, I, VI, VP> AsRef<P> for ValidatedValue<P, I, VI, VP> {
    fn as_ref(&self) -> &P {
        &self.0
    }
}

impl<P, I, VI, VP> std::ops::Deref for ValidatedValue<P, I, VI, VP> {
    type Target = P;

    fn deref(&self) -> &P {
        &self.0
    }
}

impl<P: Debug, I, VI, VP> Debug for ValidatedValue<P, I, VI, VP> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <P as Debug>::fmt(&self.0, f)
    }
}

impl<P: Display, I, VI, VP> Display for ValidatedValue<P, I, VI, VP> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <P as Display>::fmt(&self.0, f)
    }
}

#[cfg(feature = "serde")]
impl<P: serde::Serialize, I, VI, VP> serde::Serialize for ValidatedValue<P, I, VI, VP> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }
}

/// Deserializes the inner value **without validating it**.
///
/// Deserialization is a conversion, not validation; it is meant for
/// restoring `Plain` data from trusted storage. Untrusted data should be
/// received as the input/form representation and validated explicitly.
#[cfg(feature = "serde")]
impl<'de, P, I, VI, VP> serde::Deserialize<'de> for ValidatedValue<P, I, VI, VP>
where
    P: serde::Deserialize<'de>,
{
    fn deserialize<Z>(deserializer: Z) -> Result<Self, Z::Error>
    where
        Z: serde::Deserializer<'de>,
    {
        P::deserialize(deserializer).map(|v| ValidatedValue(v, PhantomData))
    }
}