Skip to main content

uv_normalize/
variant.rs

1use std::borrow::Cow;
2use std::fmt::{self, Display};
3use std::str::FromStr;
4
5use serde::{Deserialize, Serialize};
6
7/// An invalid component of a PEP 825 wheel variant property.
8#[derive(Debug, thiserror::Error)]
9pub enum InvalidVariantComponent {
10    #[error("Invalid variant namespace: `{0}`")]
11    InvalidNamespace(String),
12    #[error("Invalid variant feature: `{0}`")]
13    InvalidFeature(String),
14    #[error("Invalid variant value: `{0}`")]
15    InvalidValue(String),
16}
17
18/// A validated variant namespace.
19#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(try_from = "String")]
21pub struct VariantNamespace(Cow<'static, str>);
22
23impl VariantNamespace {
24    /// Return the validated component as a string.
25    pub fn as_str(&self) -> &str {
26        &self.0
27    }
28
29    /// Create a variant namespace from a static string.
30    ///
31    /// An invalid namespace causes a compilation error in a const context and a panic at runtime.
32    pub const fn from_static(value: &'static str) -> Self {
33        assert!(valid_component(value, false), "invalid variant namespace");
34        Self(Cow::Borrowed(value))
35    }
36}
37
38impl Display for VariantNamespace {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        Display::fmt(&self.0, f)
41    }
42}
43
44impl FromStr for VariantNamespace {
45    type Err = InvalidVariantComponent;
46
47    fn from_str(value: &str) -> Result<Self, Self::Err> {
48        Self::try_from(value.to_owned())
49    }
50}
51
52impl TryFrom<String> for VariantNamespace {
53    type Error = InvalidVariantComponent;
54
55    fn try_from(value: String) -> Result<Self, Self::Error> {
56        if valid_component(&value, false) {
57            Ok(Self(Cow::Owned(value)))
58        } else {
59            Err(InvalidVariantComponent::InvalidNamespace(value))
60        }
61    }
62}
63
64/// A validated variant feature.
65#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
66#[serde(try_from = "String")]
67pub struct VariantFeature(Cow<'static, str>);
68
69impl VariantFeature {
70    /// Return the validated component as a string.
71    pub fn as_str(&self) -> &str {
72        &self.0
73    }
74
75    /// Create a variant feature from a static string.
76    ///
77    /// An invalid feature causes a compilation error in a const context and a panic at runtime.
78    pub const fn from_static(value: &'static str) -> Self {
79        assert!(valid_component(value, false), "invalid variant feature");
80        Self(Cow::Borrowed(value))
81    }
82}
83
84impl Display for VariantFeature {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        Display::fmt(&self.0, f)
87    }
88}
89
90impl FromStr for VariantFeature {
91    type Err = InvalidVariantComponent;
92
93    fn from_str(value: &str) -> Result<Self, Self::Err> {
94        Self::try_from(value.to_owned())
95    }
96}
97
98impl TryFrom<String> for VariantFeature {
99    type Error = InvalidVariantComponent;
100
101    fn try_from(value: String) -> Result<Self, Self::Error> {
102        if valid_component(&value, false) {
103            Ok(Self(Cow::Owned(value)))
104        } else {
105            Err(InvalidVariantComponent::InvalidFeature(value))
106        }
107    }
108}
109
110/// A validated variant value.
111#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
112#[serde(try_from = "String")]
113pub struct VariantValue(Cow<'static, str>);
114
115impl VariantValue {
116    /// Return the validated component as a string.
117    pub fn as_str(&self) -> &str {
118        &self.0
119    }
120
121    /// Create a variant value from a static string.
122    ///
123    /// An invalid value causes a compilation error in a const context and a panic at runtime.
124    pub const fn from_static(value: &'static str) -> Self {
125        assert!(valid_component(value, true), "invalid variant value");
126        Self(Cow::Borrowed(value))
127    }
128}
129
130impl Display for VariantValue {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        Display::fmt(&self.0, f)
133    }
134}
135
136impl FromStr for VariantValue {
137    type Err = InvalidVariantComponent;
138
139    fn from_str(value: &str) -> Result<Self, Self::Err> {
140        Self::try_from(value.to_owned())
141    }
142}
143
144impl TryFrom<String> for VariantValue {
145    type Error = InvalidVariantComponent;
146
147    fn try_from(value: String) -> Result<Self, Self::Error> {
148        if valid_component(&value, true) {
149            Ok(Self(Cow::Owned(value)))
150        } else {
151            Err(InvalidVariantComponent::InvalidValue(value))
152        }
153    }
154}
155
156const fn valid_component(value: &str, allow_period: bool) -> bool {
157    if value.is_empty() {
158        return false;
159    }
160    let bytes = value.as_bytes();
161    let mut index = 0;
162    while index < bytes.len() {
163        let character = bytes[index];
164        if !(character.is_ascii_lowercase()
165            || character.is_ascii_digit()
166            || character == b'_'
167            || (allow_period && character == b'.'))
168        {
169            return false;
170        }
171        index += 1;
172    }
173    true
174}