envigil 0.1.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
Documentation
//! Validation primitives for environment variable values.
//!
//! A [`Validator`] checks a parsed value and returns a human-readable
//! message on failure. Built-in constructors cover the common cases;
//! any closure `Fn(&T) -> Result<(), String>` is also a `Validator`.
//!
//! # Examples
//!
//! ```
//! use envigil::validate::{self, Validator};
//!
//! let v = validate::range(1..=65535);
//! assert!(v.validate(&8080u16).is_ok());
//! assert!(v.validate(&0u16).is_err());
//!
//! // Closures work directly:
//! let even = |n: &u32| {
//!     if n % 2 == 0 { Ok(()) }
//!     else { Err(format!("{n} is odd")) }
//! };
//! assert!(even.validate(&4).is_ok());
//! assert!(even.validate(&3).is_err());
//! ```

use std::fmt;
use std::ops::RangeInclusive;

/// A validation rule for a parsed value of type `T`.
///
/// Return `Ok(())` if the value is acceptable, or `Err(message)`
/// with a lowercase description of what went wrong.
pub trait Validator<T: ?Sized> {
    /// Check `value`. The error string should be lowercase, no
    /// trailing period.
    fn validate(&self, value: &T) -> Result<(), String>;
}

/// Any closure `Fn(&T) -> Result<(), String>` is a `Validator`.
///
/// # Examples
///
/// ```
/// use envigil::validate::Validator;
///
/// let positive = |n: &i32| {
///     if *n > 0 { Ok(()) }
///     else { Err("must be positive".to_owned()) }
/// };
///
/// assert!(positive.validate(&5).is_ok());
/// assert_eq!(
///     positive.validate(&-1).unwrap_err(),
///     "must be positive"
/// );
/// ```
impl<T: ?Sized, F> Validator<T> for F
where
    F: Fn(&T) -> Result<(), String>,
{
    fn validate(&self, value: &T) -> Result<(), String> {
        self(value)
    }
}

// ---------------------------------------------------------------------------
// range
// ---------------------------------------------------------------------------

/// Checks that a value falls within an inclusive range.
///
/// Created by [`range`].
#[derive(Debug, Clone)]
pub struct RangeValidator<T> {
    range: RangeInclusive<T>,
    description: String,
}

/// Require a value to be within `range` (inclusive).
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::range(1..=100);
/// assert!(v.validate(&50).is_ok());
/// assert!(v.validate(&0).is_err());
/// assert!(v.validate(&101).is_err());
/// ```
pub fn range<T>(range: RangeInclusive<T>) -> RangeValidator<T>
where
    T: PartialOrd + Clone + fmt::Display,
{
    let description = format!("{}..={}", range.start(), range.end());
    RangeValidator { range, description }
}

impl<T> Validator<T> for RangeValidator<T>
where
    T: PartialOrd + Clone + fmt::Display,
{
    fn validate(&self, value: &T) -> Result<(), String> {
        if self.range.contains(value) {
            Ok(())
        } else {
            Err(format!(
                "value {value} is out of range {}",
                self.description
            ))
        }
    }
}

// ---------------------------------------------------------------------------
// not_empty
// ---------------------------------------------------------------------------

/// Checks that a string-like value is not empty.
///
/// Created by [`not_empty`].
#[derive(Debug, Clone, Copy)]
pub struct NotEmpty;

/// Require a non-empty string.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::not_empty();
/// assert!(v.validate(&"hello".to_owned()).is_ok());
/// assert!(v.validate(&String::new()).is_err());
/// ```
pub fn not_empty() -> NotEmpty {
    NotEmpty
}

impl Validator<String> for NotEmpty {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.is_empty() {
            Err("must not be empty".to_owned())
        } else {
            Ok(())
        }
    }
}

impl Validator<str> for NotEmpty {
    fn validate(&self, value: &str) -> Result<(), String> {
        if value.is_empty() {
            Err("must not be empty".to_owned())
        } else {
            Ok(())
        }
    }
}

// ---------------------------------------------------------------------------
// contains / starts_with / ends_with
// ---------------------------------------------------------------------------

/// Checks that a string contains a substring.
///
/// Created by [`contains`].
#[derive(Debug, Clone)]
pub struct Contains {
    substring: String,
}

/// Require the value to contain `substring`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::contains("@");
/// assert!(v.validate(&"user@example.com".to_owned()).is_ok());
/// assert!(v.validate(&"invalid".to_owned()).is_err());
/// ```
pub fn contains(substring: impl Into<String>) -> Contains {
    Contains {
        substring: substring.into(),
    }
}

impl Validator<String> for Contains {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.contains(&self.substring) {
            Ok(())
        } else {
            Err(format!("must contain {:?}", self.substring))
        }
    }
}

/// Checks that a string starts with a prefix.
///
/// Created by [`starts_with`].
#[derive(Debug, Clone)]
pub struct StartsWith {
    prefix: String,
}

/// Require the value to start with `prefix`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::starts_with("postgres://");
/// assert!(v.validate(&"postgres://localhost/db".to_owned()).is_ok());
/// assert!(v.validate(&"mysql://localhost/db".to_owned()).is_err());
/// ```
pub fn starts_with(prefix: impl Into<String>) -> StartsWith {
    StartsWith {
        prefix: prefix.into(),
    }
}

impl Validator<String> for StartsWith {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.starts_with(&self.prefix) {
            Ok(())
        } else {
            Err(format!("must start with {:?}", self.prefix))
        }
    }
}

/// Checks that a string ends with a suffix.
///
/// Created by [`ends_with`].
#[derive(Debug, Clone)]
pub struct EndsWith {
    suffix: String,
}

/// Require the value to end with `suffix`.
///
/// # Examples
///
/// ```
/// use envigil::validate::{self, Validator};
///
/// let v = validate::ends_with(".rs");
/// assert!(v.validate(&"main.rs".to_owned()).is_ok());
/// assert!(v.validate(&"main.py".to_owned()).is_err());
/// ```
pub fn ends_with(suffix: impl Into<String>) -> EndsWith {
    EndsWith {
        suffix: suffix.into(),
    }
}

impl Validator<String> for EndsWith {
    fn validate(&self, value: &String) -> Result<(), String> {
        if value.ends_with(&self.suffix) {
            Ok(())
        } else {
            Err(format!("must end with {:?}", self.suffix))
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- range --

    #[test]
    fn range_accepts_in_bounds() {
        let v = range(1..=65535);
        assert!(v.validate(&1u16).is_ok());
        assert!(v.validate(&8080u16).is_ok());
        assert!(v.validate(&65535u16).is_ok());
    }

    #[test]
    fn range_rejects_out_of_bounds() {
        let v = range(1..=65535);
        assert!(v.validate(&0u16).is_err());
    }

    #[test]
    fn range_error_message() {
        let v = range(1..=100);
        let msg = v.validate(&200).unwrap_err();
        assert!(msg.contains("200"), "message: {msg}");
        assert!(msg.contains("1..=100"), "message: {msg}");
    }

    // -- not_empty --

    #[test]
    fn not_empty_accepts_nonempty() {
        let v = not_empty();
        assert!(v.validate(&"x".to_owned()).is_ok());
    }

    #[test]
    fn not_empty_rejects_empty_string() {
        let v = not_empty();
        let msg = v.validate(&String::new()).unwrap_err();
        assert_eq!(msg, "must not be empty");
    }

    #[test]
    fn not_empty_rejects_empty_str() {
        let v = not_empty();
        assert!(v.validate("").is_err());
        assert!(v.validate("ok").is_ok());
    }

    // -- contains --

    #[test]
    fn contains_match() {
        let v = contains("@");
        assert!(v.validate(&"a@b.com".to_owned()).is_ok());
    }

    #[test]
    fn contains_no_match() {
        let v = contains("@");
        let msg = v.validate(&"nope".to_owned()).unwrap_err();
        assert!(msg.contains("@"), "message: {msg}");
    }

    // -- starts_with --

    #[test]
    fn starts_with_match() {
        let v = starts_with("postgres://");
        assert!(v.validate(&"postgres://localhost".to_owned()).is_ok());
    }

    #[test]
    fn starts_with_no_match() {
        let v = starts_with("postgres://");
        let msg = v.validate(&"mysql://localhost".to_owned()).unwrap_err();
        assert!(msg.contains("postgres://"), "message: {msg}");
    }

    // -- ends_with --

    #[test]
    fn ends_with_match() {
        let v = ends_with(".rs");
        assert!(v.validate(&"lib.rs".to_owned()).is_ok());
    }

    #[test]
    fn ends_with_no_match() {
        let v = ends_with(".rs");
        let msg = v.validate(&"lib.py".to_owned()).unwrap_err();
        assert!(msg.contains(".rs"), "message: {msg}");
    }

    // -- closure as Validator --

    #[test]
    fn closure_validator() {
        let even = |n: &u32| {
            if n % 2 == 0 {
                Ok(())
            } else {
                Err(format!("{n} is odd"))
            }
        };

        assert!(even.validate(&4).is_ok());
        assert_eq!(even.validate(&3).unwrap_err(), "3 is odd");
    }

    // -- trait object safety --

    #[test]
    fn works_as_trait_object() {
        let validators: Vec<Box<dyn Validator<String>>> =
            vec![Box::new(not_empty()), Box::new(contains("@"))];

        let value = "user@example.com".to_owned();
        for v in &validators {
            assert!(v.validate(&value).is_ok());
        }

        let bad = String::new();
        assert!(validators[0].validate(&bad).is_err());
    }
}