next_web_ai/util/
key_value.rs

1pub(crate) const NONE_VALUE: &'static str = "None";
2
3use next_web_core::DynClone;
4
5pub trait KeyValue
6where
7    Self: DynClone,
8    Self: Send + Sync,
9{
10    fn key(&self) -> &str;
11
12    fn value(&self) -> &str;
13}
14
15next_web_core::clone_trait_object!(KeyValue);
16
17#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
18pub struct NoneKeyValue;
19
20impl NoneKeyValue {
21    pub fn of_immutable(key: impl Into<String>, value: impl Into<String>) -> ImmutableKeyValue {
22        ImmutableKeyValue::new(key, value)
23    }
24
25    pub fn of_validated<T>(
26        key: impl Into<String>,
27        value: T,
28        validator: impl Predicate<T>,
29    ) -> ValidatedKeyValue
30    where
31        T: ToString,
32    {
33        ValidatedKeyValue::new(key, value, validator)
34    }
35}
36
37#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
38pub struct ImmutableKeyValue {
39    key: String,
40    value: String,
41}
42
43impl ImmutableKeyValue {
44    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
45        Self {
46            key: key.into(),
47            value: value.into(),
48        }
49    }
50}
51
52impl KeyValue for ImmutableKeyValue {
53    fn key(&self) -> &str {
54        &self.key
55    }
56
57    fn value(&self) -> &str {
58        todo!()
59    }
60}
61
62#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
63pub struct ValidatedKeyValue {
64    key: String,
65    value: String,
66}
67
68impl ValidatedKeyValue {
69    pub fn new<T>(key: impl Into<String>, value: T, validator: impl Predicate<T>) -> Self
70    where
71        T: ToString,
72    {
73        assert!(validator.test(&value));
74        Self {
75            key: key.into(),
76            value: value.to_string(),
77        }
78    }
79}
80
81impl KeyValue for ValidatedKeyValue {
82    fn key(&self) -> &str {
83        &self.key
84    }
85
86    fn value(&self) -> &str {
87        &self.value
88    }
89}
90
91pub trait Predicate<T> {
92    fn test(&self, t: &T) -> bool;
93}
94
95impl KeyValue for () {
96    fn key(&self) -> &str {
97        ""
98    }
99
100    fn value(&self) -> &str {
101        ""
102    }
103}