validated_struct/
lib.rs

1pub use validated_struct_macros::*;
2
3#[derive(Debug)]
4pub enum InsertionError {
5    SyncInsertNotAvailable,
6    #[cfg(feature = "serde_json")]
7    JsonErr(serde_json::Error),
8    #[cfg(feature = "json5")]
9    Json5Err(json5::Error),
10    Str(&'static str),
11    String(String),
12}
13impl std::error::Error for InsertionError {}
14impl std::fmt::Display for InsertionError {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        write!(f, "{:?}", self)
17    }
18}
19impl InsertionError {
20    pub fn sync_insert_not_available() -> Self {
21        InsertionError::SyncInsertNotAvailable
22    }
23}
24#[cfg(feature = "serde_json")]
25impl From<serde_json::Error> for InsertionError {
26    fn from(e: serde_json::Error) -> Self {
27        InsertionError::JsonErr(e)
28    }
29}
30#[cfg(feature = "json5")]
31impl From<json5::Error> for InsertionError {
32    fn from(e: json5::Error) -> Self {
33        InsertionError::Json5Err(e)
34    }
35}
36#[derive(Debug)]
37pub enum GetError {
38    NoMatchingKey,
39    TypeMissMatch,
40    #[cfg(feature = "serde_json")]
41    Other(Box<dyn std::error::Error>),
42}
43impl std::error::Error for GetError {}
44impl std::fmt::Display for GetError {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            GetError::NoMatchingKey | GetError::TypeMissMatch => write!(f, "{:?}", self),
48            #[cfg(feature = "serde_json")]
49            GetError::Other(e) => write!(f, "{}", e),
50        }
51    }
52}
53impl From<&'static str> for InsertionError {
54    fn from(s: &'static str) -> Self {
55        InsertionError::Str(s)
56    }
57}
58impl From<String> for InsertionError {
59    fn from(s: String) -> Self {
60        InsertionError::String(s)
61    }
62}
63pub trait ValidatedMapAssociatedTypes<'a> {
64    type Accessor;
65}
66pub trait ValidatedMap: for<'a> ValidatedMapAssociatedTypes<'a> {
67    fn insert<'d, D: serde::Deserializer<'d>>(
68        &mut self,
69        key: &str,
70        value: D,
71    ) -> Result<(), InsertionError>
72    where
73        InsertionError: From<D::Error>;
74    fn get<'a>(
75        &'a self,
76        key: &str,
77    ) -> Result<<Self as ValidatedMapAssociatedTypes<'a>>::Accessor, GetError>;
78    #[cfg(feature = "serde_json")]
79    fn get_json(&self, key: &str) -> Result<String, GetError>;
80    #[cfg(feature = "json5")]
81    fn insert_json5(&mut self, key: &str, value: &str) -> Result<(), InsertionError> {
82        self.insert(key, &mut json5::Deserializer::from_str(value)?)
83    }
84    type Keys: IntoIterator<Item = String>;
85    fn keys(&self) -> Self::Keys;
86}
87pub fn split_once(s: &str, pattern: char) -> (&str, &str) {
88    let index = s.find(pattern).unwrap_or(s.len());
89    let (l, r) = s.split_at(index);
90    (l, if r.is_empty() { "" } else { &r[1..] })
91}