slug.rs 3.96 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3
4
5
6
7
8
9
10
11

use serde::de::{self, Deserializer, Visitor};
use serde::{Deserialize, Serialize};
use std::fmt;

const REPLACEMENT_CHAR: char = '_';

/// URL and NATS friendly string.
/// Only a-z, 0-9, - and _.
12
#[derive(Serialize, Clone, Debug, Eq, PartialEq, Default)]
Ryan Olson's avatar
Ryan Olson committed
13
14
15
16
17
18
19
20
21
22
23
pub struct Slug(String);

impl Slug {
    fn new(s: String) -> Slug {
        // remove any leading REPLACEMENT_CHAR
        let s = s.trim_start_matches(REPLACEMENT_CHAR).to_string();
        Slug(s)
    }

    /// Create [`Slug`] from a string.
    pub fn from_string(s: impl AsRef<str>) -> Slug {
24
        Slug::slugify(s.as_ref())
Ryan Olson's avatar
Ryan Olson committed
25
26
    }

27
28
29
30
31
32
33
    /// Turn the string into a valid slug, replacing any not-web-or-nats-safe characters with '-'
    pub fn slugify(s: &str) -> Slug {
        let out = s
            .to_lowercase()
            .chars()
            .map(|c| {
                let is_valid = c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_';
34
                if is_valid { c } else { REPLACEMENT_CHAR }
35
36
37
38
            })
            .collect::<String>();
        Slug::new(out)
    }
Ryan Olson's avatar
Ryan Olson committed
39
40

    /// Like slugify but also add a four byte hash on the end, in case two different strings slug
41
    /// to the same thing (e.g. because of case differences).
42
    pub fn slugify_unique(s: &str) -> Slug {
Ryan Olson's avatar
Ryan Olson committed
43
44
45
46
        let out = s
            .to_lowercase()
            .chars()
            .map(|c| {
Ryan Olson's avatar
Ryan Olson committed
47
                let is_valid = c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_';
48
                if is_valid { c } else { REPLACEMENT_CHAR }
Ryan Olson's avatar
Ryan Olson committed
49
50
51
            })
            .collect::<String>();
        let hash = blake3::hash(s.as_bytes()).to_string();
Ryan Olson's avatar
Ryan Olson committed
52
        let out = format!("{out}_{}", &hash[(hash.len() - 8)..]);
Ryan Olson's avatar
Ryan Olson committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        Slug::new(out)
    }
}

impl fmt::Display for Slug {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug)]
pub struct InvalidSlugError(char);

impl fmt::Display for InvalidSlugError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Invalid char '{}'. String can only contain a-z, 0-9, - and _.",
            self.0
        )
    }
}

impl std::error::Error for InvalidSlugError {}

impl TryFrom<&str> for Slug {
    type Error = InvalidSlugError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.to_string().try_into()
    }
}

impl TryFrom<String> for Slug {
    type Error = InvalidSlugError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let is_invalid =
            |c: &char| !c.is_ascii_lowercase() && !c.is_ascii_digit() && *c != '-' && *c != '_';
        match s.chars().find(is_invalid) {
            None => Ok(Slug(s)),
            Some(c) => Err(InvalidSlugError(c)),
        }
    }
}

impl<'de> Deserialize<'de> for Slug {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct SlugVisitor;

        impl Visitor<'_> for SlugVisitor {
            type Value = Slug;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter
                    .write_str("a valid slug string containing only characters a-z, 0-9, - and _.")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Slug::try_from(v).map_err(de::Error::custom)
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Slug::try_from(v.as_ref()).map_err(de::Error::custom)
            }
        }

        deserializer.deserialize_string(SlugVisitor)
    }
}

impl AsRef<str> for Slug {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for Slug {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}