use crate::{
HOSTNAME_DESCRIPTION, Input, Integer, Number, boolean, float, hostname, port_number, range_description,
range_number, text_description, text_length, white_list_description,
};
pub trait Validator {
type Output;
fn validate(&self, value: Input<'_>) -> Option<Self::Output>;
fn description(&self) -> String;
}
fn text(description: Vec<u8>) -> String {
String::from_utf8_lossy(&description).into_owned()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Boolean;
impl Validator for Boolean {
type Output = bool;
fn validate(&self, value: Input<'_>) -> Option<bool> {
if !boolean(true, value) {
return None;
}
Some(match value {
Input::Bool(b) => b,
Input::Int(i) => i == 1,
Input::Str(s) => matches!(s, b"true" | b"1"),
_ => false,
})
}
fn description(&self) -> String {
"Value must be a valid boolean".to_string()
}
}
impl Validator for Integer {
type Output = i64;
fn validate(&self, value: Input<'_>) -> Option<i64> {
match value.numeric() {
Some(Number::Int(i)) if self.accepts(true, value) => Some(i),
_ => None,
}
}
fn description(&self) -> String {
let mut description = Vec::new();
Integer::description(*self, &mut description);
text(description)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Float;
impl Validator for Float {
type Output = f64;
fn validate(&self, value: Input<'_>) -> Option<f64> {
if !float(true, value) {
return None;
}
value.numeric().map(Number::as_f64)
}
fn description(&self) -> String {
"Value must be a valid float".to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Range {
pub min: i64,
pub max: i64,
}
impl Range {
pub fn new(min: i64, max: i64) -> Self {
Self { min, max }
}
}
impl Validator for Range {
type Output = i64;
fn validate(&self, value: Input<'_>) -> Option<i64> {
match range_number(b"integer", value) {
Some(Number::Int(i)) if i >= self.min && i <= self.max => Some(i),
_ => None,
}
}
fn description(&self) -> String {
let mut description = Vec::new();
range_description(Number::Int(self.min), Number::Int(self.max), &mut description);
text(description)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Port;
impl Validator for Port {
type Output = u16;
fn validate(&self, value: Input<'_>) -> Option<u16> {
let digits;
let value = match value {
Input::Int(i) => {
digits = i.to_string();
digits.as_bytes()
}
Input::Str(s) => s,
_ => return None,
};
if !port_number(value) {
return None;
}
std::str::from_utf8(value).ok()?.parse().ok()
}
fn description(&self) -> String {
"Value must be a port between 1 and 65535".to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Text {
pub length: i64,
pub min: i64,
}
impl Text {
pub fn new(length: i64) -> Self {
Self { length, min: 1 }
}
pub fn min(mut self, min: i64) -> Self {
self.min = min;
self
}
}
impl Validator for Text {
type Output = String;
fn validate(&self, value: Input<'_>) -> Option<String> {
let Input::Str(value) = value else {
return None;
};
if !text_length(value, self.min, self.length) {
return None;
}
String::from_utf8(value.to_vec()).ok()
}
fn description(&self) -> String {
let mut description = Vec::new();
text_description(self.length, self.min, None, false, &mut description);
text(description)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hostname;
impl Validator for Hostname {
type Output = String;
fn validate(&self, value: Input<'_>) -> Option<String> {
let Input::Str(value) = value else {
return None;
};
if !hostname(value) {
return None;
}
String::from_utf8(value.to_vec()).ok()
}
fn description(&self) -> String {
HOSTNAME_DESCRIPTION.to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WhiteList<'a> {
pub list: &'a [&'a str],
}
impl<'a> WhiteList<'a> {
pub fn new(list: &'a [&'a str]) -> Self {
Self { list }
}
}
impl Validator for WhiteList<'_> {
type Output = String;
fn validate(&self, value: Input<'_>) -> Option<String> {
let Input::Str(value) = value else {
return None;
};
self.list.iter().find(|allowed| allowed.as_bytes() == value).map(|allowed| allowed.to_string())
}
fn description(&self) -> String {
let mut description = Vec::new();
white_list_description(self.list.join(", ").as_bytes(), &mut description);
text(description)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn booleans() {
assert_eq!(Boolean.validate(Input::Bool(true)), Some(true));
assert_eq!(Boolean.validate(Input::Str(b"true")), Some(true));
assert_eq!(Boolean.validate(Input::Str(b"0")), Some(false));
assert_eq!(Boolean.validate(Input::Int(1)), Some(true));
assert_eq!(Boolean.validate(Input::Str(b"yes")), None);
assert_eq!(Boolean.validate(Input::Int(2)), None);
}
#[test]
fn integers() {
let byte = Integer::new(8, true).unwrap();
assert_eq!(byte.validate(Input::Int(255)), Some(255));
assert_eq!(byte.validate(Input::Str(b"255")), Some(255));
assert_eq!(byte.validate(Input::Str(b"256")), None);
assert_eq!(byte.validate(Input::Float(1.0)), None);
assert_eq!(Validator::description(&byte), "Value must be a valid unsigned 8-bit integer between 0 and 255");
}
#[test]
fn floats() {
assert_eq!(Float.validate(Input::Float(1.5)), Some(1.5));
assert_eq!(Float.validate(Input::Int(15)), Some(15.0));
assert_eq!(Float.validate(Input::Str(b"1.5")), Some(1.5));
assert_eq!(Float.validate(Input::Str(b"fast")), None);
assert_eq!(Float.validate(Input::Bool(true)), None);
}
#[test]
fn ranges() {
let range = Range::new(0, 10);
assert_eq!(range.validate(Input::Int(10)), Some(10));
assert_eq!(range.validate(Input::Str(b"0")), Some(0));
assert_eq!(range.validate(Input::Str(b"11")), None);
assert_eq!(range.validate(Input::Int(-1)), None);
assert_eq!(range.validate(Input::Float(5.0)), None);
assert_eq!(range.validate(Input::Float(f64::INFINITY)), None);
assert_eq!(range.description(), "Value must be a valid range between 0 and 10");
}
#[test]
fn ports() {
assert_eq!(Port.validate(Input::Int(6379)), Some(6379));
assert_eq!(Port.validate(Input::Str(b"65535")), Some(65535));
assert_eq!(Port.validate(Input::Str(b"65536")), None);
assert_eq!(Port.validate(Input::Str(b"080")), None);
assert_eq!(Port.validate(Input::Int(0)), None);
assert_eq!(Port.validate(Input::Str(b"127.0.0.1:80")), None);
}
#[test]
fn texts() {
assert_eq!(Text::new(5).validate(Input::Str(b"redis")), Some("redis".to_string()));
assert_eq!(Text::new(5).validate(Input::Str(b"redis6")), None);
assert_eq!(Text::new(5).validate(Input::Str(b"")), None);
assert_eq!(Text::new(5).min(0).validate(Input::Str(b"")), Some(String::new()));
assert_eq!(Text::new(0).validate(Input::Str(&[b'a'; 4096])).map(|text| text.len()), Some(4096));
assert_eq!(Text::new(5).validate(Input::Int(5)), None);
assert_eq!(Text::new(5).validate(Input::Str(b"\xff")), None);
assert_eq!(
Text::new(5).description(),
"Value must be a valid string and at least 1 chars and no longer than 5 chars"
);
}
#[test]
fn hostnames() {
assert_eq!(Hostname.validate(Input::Str(b"redis.internal")), Some("redis.internal".to_string()));
assert_eq!(Hostname.validate(Input::Str(b"redis:6379")), None);
assert_eq!(Hostname.validate(Input::Str(b"")), None);
}
#[test]
fn white_lists() {
let level = WhiteList::new(&["high", "low"]);
assert_eq!(level.validate(Input::Str(b"low")), Some("low".to_string()));
assert_eq!(level.validate(Input::Str(b"LOW")), None);
assert_eq!(level.validate(Input::Int(1)), None);
assert_eq!(level.description(), "Value must be one of (high, low)");
}
}