assemblyline_models/types/
mapping_keys.rs

1use std::sync::LazyLock;
2
3
4
5#[derive(Debug, Clone, thiserror::Error)]
6#[error("An invalid field key found: {0}")]
7pub struct InvalidField(String);
8
9pub struct FieldName(String);
10
11impl std::fmt::Display for FieldName {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        f.write_str(&self.0)
14    }
15}
16
17impl std::ops::Deref for FieldName {
18    type Target = String;
19
20    fn deref(&self) -> &Self::Target {
21        &self.0
22    }
23}
24
25/// Regex to match valid elasticsearch/json field names. 
26/// Compile it once on first access, from then on just share a compiled regex instance.
27pub static FIELD_SANITIZER: LazyLock<regex::Regex> = LazyLock::new(|| {
28    regex::Regex::new("^[a-z][a-z0-9_.]*$").expect("Field Regex could not compile")
29});
30
31impl std::str::FromStr for FieldName {
32    type Err = InvalidField;
33
34    fn from_str(s: &str) -> Result<Self, Self::Err> {
35        if FIELD_SANITIZER.is_match(s) {
36            Ok(Self(s.to_owned()))
37        } else {
38            Err(InvalidField(s.to_string()))
39        }
40    }
41}