Skip to main content

semantic_versions/
identifier.rs

1use std::cmp::Ordering;
2use std::fmt;
3
4/// One pre-release or build identifier, borrowed from its version.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub enum Identifier<'a> {
7    /// All digits, compared numerically.
8    Numeric(&'a str),
9    /// Contains a letter or hyphen, compared in ASCII order.
10    AlphaNumeric(&'a str),
11}
12
13impl<'a> Identifier<'a> {
14    pub(crate) fn new(s: &'a str) -> Self {
15        if s.bytes().all(|c| c.is_ascii_digit()) {
16            Identifier::Numeric(s)
17        } else {
18            Identifier::AlphaNumeric(s)
19        }
20    }
21
22    /// The identifier as written.
23    pub fn as_str(&self) -> &'a str {
24        match self {
25            Identifier::Numeric(s) | Identifier::AlphaNumeric(s) => s,
26        }
27    }
28
29    /// The numeric value, for a numeric identifier that fits in a `u64`.
30    pub fn as_number(&self) -> Option<u64> {
31        match self {
32            Identifier::Numeric(s) => s.parse().ok(),
33            Identifier::AlphaNumeric(_) => None,
34        }
35    }
36}
37
38impl fmt::Display for Identifier<'_> {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(self.as_str())
41    }
42}
43
44impl Ord for Identifier<'_> {
45    /// Numeric identifiers compare numerically (ignoring leading zeroes, which
46    /// builds may carry) and sort before alphanumeric ones, which compare in
47    /// ASCII order.
48    fn cmp(&self, other: &Self) -> Ordering {
49        match (self, other) {
50            (Identifier::Numeric(a), Identifier::Numeric(b)) => {
51                let a = a.trim_start_matches('0');
52                let b = b.trim_start_matches('0');
53                a.len()
54                    .cmp(&b.len())
55                    .then_with(|| a.as_bytes().cmp(b.as_bytes()))
56            }
57            (Identifier::Numeric(_), Identifier::AlphaNumeric(_)) => Ordering::Less,
58            (Identifier::AlphaNumeric(_), Identifier::Numeric(_)) => Ordering::Greater,
59            (Identifier::AlphaNumeric(a), Identifier::AlphaNumeric(b)) => {
60                a.as_bytes().cmp(b.as_bytes())
61            }
62        }
63    }
64}
65
66impl PartialOrd for Identifier<'_> {
67    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
68        Some(self.cmp(other))
69    }
70}
71
72/// Compare two identifiers given as bytes (always ASCII).
73#[inline]
74fn cmp_id_bytes(a: &[u8], b: &[u8]) -> Ordering {
75    let da = a.iter().all(u8::is_ascii_digit);
76    let db = b.iter().all(u8::is_ascii_digit);
77    match (da, db) {
78        (true, true) => {
79            let a = trim_zeros(a);
80            let b = trim_zeros(b);
81            a.len().cmp(&b.len()).then_with(|| a.cmp(b))
82        }
83        (true, false) => Ordering::Less,
84        (false, true) => Ordering::Greater,
85        (false, false) => a.cmp(b),
86    }
87}
88
89#[inline]
90fn trim_zeros(s: &[u8]) -> &[u8] {
91    let n = s.iter().take_while(|&&c| c == b'0').count();
92    &s[n..]
93}
94
95const INLINE: usize = 22;
96
97#[derive(Clone)]
98enum Repr {
99    Empty,
100    Inline { len: u8, buf: [u8; INLINE] },
101    Heap(Box<[u8]>),
102}
103
104/// Dot-separated identifiers (a pre-release or a build), stored as written.
105/// Empty when the version has none. Short lists (up to 22 bytes, which covers
106/// `rc.1`, `beta.4`, `next.12`, …) are stored inline without allocating;
107/// identifiers are produced on demand.
108#[derive(Clone)]
109pub struct Identifiers(Repr);
110
111impl Default for Identifiers {
112    fn default() -> Self {
113        Identifiers::empty()
114    }
115}
116
117impl PartialEq for Identifiers {
118    fn eq(&self, other: &Self) -> bool {
119        self.bytes() == other.bytes()
120    }
121}
122
123impl Eq for Identifiers {}
124
125impl std::hash::Hash for Identifiers {
126    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
127        self.bytes().hash(state);
128    }
129}
130
131impl Identifiers {
132    pub(crate) fn from_validated(s: &str) -> Self {
133        Identifiers::from_ascii(s.as_bytes())
134    }
135
136    /// `b` must already be validated identifier text (ASCII only).
137    #[inline]
138    pub(crate) fn from_ascii(b: &[u8]) -> Self {
139        if b.is_empty() {
140            Identifiers(Repr::Empty)
141        } else if b.len() <= INLINE {
142            let mut buf = [0u8; INLINE];
143            buf[..b.len()].copy_from_slice(b);
144            Identifiers(Repr::Inline {
145                len: b.len() as u8,
146                buf,
147            })
148        } else {
149            Identifiers(Repr::Heap(b.into()))
150        }
151    }
152
153    pub(crate) const fn empty() -> Self {
154        Identifiers(Repr::Empty)
155    }
156
157    #[inline]
158    fn bytes(&self) -> &[u8] {
159        match &self.0 {
160            Repr::Empty => &[],
161            Repr::Inline { len, buf } => &buf[..*len as usize],
162            Repr::Heap(b) => b,
163        }
164    }
165
166    /// True when there are no identifiers.
167    #[inline]
168    pub fn is_empty(&self) -> bool {
169        self.bytes().is_empty()
170    }
171
172    /// The identifiers as written, joined by `.` (empty when there are none).
173    pub fn as_str(&self) -> &str {
174        // Only ASCII identifier characters are ever stored.
175        std::str::from_utf8(self.bytes()).expect("identifiers are ASCII")
176    }
177
178    /// The identifiers in order.
179    pub fn iter(&self) -> impl Iterator<Item = Identifier<'_>> + '_ {
180        let s = self.as_str();
181        s.split('.')
182            .filter(move |_| !s.is_empty())
183            .map(Identifier::new)
184    }
185
186    /// Number of identifiers.
187    pub fn len(&self) -> usize {
188        let b = self.bytes();
189        if b.is_empty() {
190            0
191        } else {
192            b.iter().filter(|&&c| c == b'.').count() + 1
193        }
194    }
195
196    /// True if `prefix`'s identifiers are a prefix of these (identifier-wise:
197    /// `rc` is a prefix of `rc.1` but not of `rc1`).
198    #[inline]
199    pub fn starts_with(&self, prefix: &Identifiers) -> bool {
200        let (s, p) = (self.bytes(), prefix.bytes());
201        p.is_empty() || (s.starts_with(p) && (s.len() == p.len() || s[p.len()] == b'.'))
202    }
203
204    /// Identifier-wise comparison; a longer list wins when one is a prefix of
205    /// the other.
206    pub(crate) fn cmp_ids(&self, other: &Identifiers) -> Ordering {
207        let (a, b) = (self.bytes(), other.bytes());
208        // Identifiers before the first differing byte are equal: skip them in
209        // one pass (eight bytes at a time) rather than classifying each one.
210        // Canaries and nightlies share long prefixes.
211        let n = a.len().min(b.len());
212        let mut k = 0;
213        while k + 8 <= n && a[k..k + 8] == b[k..k + 8] {
214            k += 8;
215        }
216        while k < n && a[k] == b[k] {
217            k += 1;
218        }
219        if k == a.len() && k == b.len() {
220            return Ordering::Equal;
221        }
222        let mut i = k;
223        while i > 0 && a[i - 1] != b'.' {
224            i -= 1;
225        }
226        let mut j = i;
227        loop {
228            let ea = a[i..]
229                .iter()
230                .position(|&c| c == b'.')
231                .map_or(a.len(), |p| i + p);
232            let eb = b[j..]
233                .iter()
234                .position(|&c| c == b'.')
235                .map_or(b.len(), |p| j + p);
236            match cmp_id_bytes(&a[i..ea], &b[j..eb]) {
237                Ordering::Equal => {}
238                o => return o,
239            }
240            match (ea == a.len(), eb == b.len()) {
241                (true, true) => return Ordering::Equal,
242                (true, false) => return Ordering::Less,
243                (false, true) => return Ordering::Greater,
244                (false, false) => {}
245            }
246            i = ea + 1;
247            j = eb + 1;
248        }
249    }
250}
251
252impl fmt::Debug for Identifiers {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.debug_list().entries(self.iter()).finish()
255    }
256}
257
258impl fmt::Display for Identifiers {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        f.write_str(self.as_str())
261    }
262}