core_lib/models/
str_id.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use uuid::Uuid;

use crate::models::Error;

#[derive(Debug, Clone, PartialEq)]
pub struct StrId {
    id: String,
}

impl StrId {
    pub fn new<S: Into<String>>(id: S) -> Result<StrId, Error> {
        let id = id.into();

        if id.is_empty() {
            return Err(Error::InvalidId(id));
        }

        Ok(StrId { id })
    }

    pub fn generate_uuid() -> Result<StrId, Error> {
        let uuid = Uuid::new_v4();
        StrId::new(uuid.to_string())
    }

    pub fn generate_slug<S: Into<String>>(str: S) -> Result<StrId, Error> {
        StrId::new(slug::slugify(str.into()))
    }

    pub fn value(&self) -> &str {
        &self.id
    }
}

impl ToString for StrId {
    fn to_string(&self) -> String {
        self.id.to_owned()
    }
}