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
//! A `Vec` with type-level minimum and maximum length.

struct AssertMinLeMax<const MIN: usize, const MAX: usize>;

impl<const MIN: usize, const MAX: usize> AssertMinLeMax<MIN, MAX> {
    const OK: () = assert!(MIN <= MAX, "BoundedVec requires MIN <= MAX");
}

/// A vector whose length is guaranteed to be within `MIN..=MAX`.
///
/// Use it as a collection field when the number of elements is itself
/// subject to validation. When used as a [`Field`](crate::Field) (via its
/// [`DefaultInputType`](crate::DefaultInputType)), the input and form
/// representations are plain `Vec`s — the user may transiently have too few
/// or too many entries while editing — and validation reports
/// [`Message::LengthExceedMin`](crate::Message)/
/// [`LengthExceedMax`](crate::Message) on the field.
///
/// `MIN <= MAX` is checked once monomorphized code actually reaches
/// [`from_vec`](Self::from_vec), `from_vec_unchecked`, or `deserialize`;
/// merely defining a type or holding it as a field does not trigger the
/// check.
///
/// ```
/// use validatable::BoundedVec;
///
/// let v: Option<BoundedVec<u8, 2, 4>> = BoundedVec::from_vec(vec![1, 2, 3]);
/// assert!(v.is_some());
/// let too_short: Option<BoundedVec<u8, 2, 4>> = BoundedVec::from_vec(vec![1]);
/// assert!(too_short.is_none());
/// ```
///
/// Derefs to `[T]`, so slice methods, indexing, and `.iter()`/`for &x in
/// &bounded_vec` work directly. `for x in bounded_vec` also works, consuming
/// the vector and yielding owned elements. There is no `DerefMut` to `[T]` as
/// a whole; use [`as_mut_slice`](Self::as_mut_slice) for in-place mutation of
/// elements.
///
/// # Serde
///
/// `Serialize`/`Deserialize` are only implemented when the `serde` feature
/// is enabled (off by default). Serialization is transparent (as a
/// sequence). Like everywhere else in this crate, **deserialization does
/// not validate**: a deserialized `BoundedVec` may violate the bounds if
/// the source is untrusted.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct BoundedVec<T, const MIN: usize, const MAX: usize>(Vec<T>);

#[cfg(feature = "serde")]
impl<'de, T, const MIN: usize, const MAX: usize> serde::Deserialize<'de> for BoundedVec<T, MIN, MAX>
where
    T: serde::Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let () = AssertMinLeMax::<MIN, MAX>::OK;
        Vec::<T>::deserialize(deserializer).map(BoundedVec)
    }
}

impl<T, const MIN: usize, const MAX: usize> BoundedVec<T, MIN, MAX> {
    /// Consumes the wrapper and returns the inner `Vec`.
    pub fn into_vec(self) -> Vec<T> {
        self.0
    }

    /// Wraps a `Vec`, returning `None` when its length is outside
    /// `MIN..=MAX`.
    pub fn from_vec(v: Vec<T>) -> Option<Self> {
        let () = AssertMinLeMax::<MIN, MAX>::OK;
        let len = v.len();
        if MIN <= len && len <= MAX {
            Some(BoundedVec(v))
        } else {
            None
        }
    }

    pub(crate) fn from_vec_unchecked(v: Vec<T>) -> Self {
        let () = AssertMinLeMax::<MIN, MAX>::OK;
        BoundedVec(v)
    }

    /// Returns a mutable slice of the elements.
    ///
    /// A slice cannot grow or shrink, so the length bounds remain intact.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.0
    }
}

impl<T, const MIN: usize, const MAX: usize> AsRef<Vec<T>> for BoundedVec<T, MIN, MAX> {
    fn as_ref(&self) -> &Vec<T> {
        &self.0
    }
}

impl<T, const MIN: usize, const MAX: usize> std::ops::Deref for BoundedVec<T, MIN, MAX> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        &self.0
    }
}

impl<'a, T, const MIN: usize, const MAX: usize> IntoIterator for &'a BoundedVec<T, MIN, MAX> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<T, const MIN: usize, const MAX: usize> IntoIterator for BoundedVec<T, MIN, MAX> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<T, const MIN: usize, const MAX: usize> From<BoundedVec<T, MIN, MAX>> for Vec<T> {
    fn from(value: BoundedVec<T, MIN, MAX>) -> Self {
        value.into_vec()
    }
}