assemblyline_models/types/
ids.rs

1use serde_with::{DeserializeFromStr, SerializeDisplay};
2use struct_metadata::Described;
3
4use crate::{ElasticMeta, ModelError};
5
6
7
8/// Validated uuid type with base62 encoding
9#[derive(SerializeDisplay, DeserializeFromStr, Debug, Described, Hash, PartialEq, Eq, Clone, Copy)]
10#[metadata_type(ElasticMeta)]
11#[metadata(mapping="keyword")]
12pub struct Sid(u128);
13
14impl std::fmt::Display for Sid {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        f.write_str(&base62::encode(self.0))
17    }
18}
19
20impl std::str::FromStr for Sid {
21    type Err = ModelError;
22
23    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
24        Ok(Sid(base62::decode(s)?))
25    }
26}
27
28impl Sid {
29    pub fn assign(&self, bins: usize) -> usize {
30        (self.0 % bins as u128) as usize
31    }
32}
33
34#[cfg(feature = "rand")]
35impl rand::distr::Distribution<Sid> for rand::distr::StandardUniform {
36    fn sample<R: rand::prelude::Rng + ?Sized>(&self, rng: &mut R) -> Sid {
37        Sid(rng.random())
38    }
39}
40
41/// Uuid type
42#[derive(SerializeDisplay, DeserializeFromStr, Debug, Hash, PartialEq, Eq, Clone, Copy)]
43pub struct Uuid(uuid::Uuid);
44
45impl Described<ElasticMeta> for Uuid {
46    fn metadata() -> struct_metadata::Descriptor<ElasticMeta> {
47        struct_metadata::Descriptor {
48            docs: None,
49            metadata: ElasticMeta { mapping: Some("keyword"), ..Default::default() },
50            kind: struct_metadata::Kind::String,
51        }
52    }
53}
54
55impl std::fmt::Display for Uuid {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str(&self.0.to_string())
58    }
59}
60
61impl std::str::FromStr for Uuid {
62    type Err = uuid::Error;
63
64    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
65        Ok(Uuid(s.parse()?))
66    }
67}