bare-types 0.3.0

A zero-cost foundation for type-safe domain modeling in Rust. Implements the 'Parse, don't validate' philosophy to eliminate primitive obsession and ensure data integrity at the system boundary.
Documentation
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
40
41
42
43
44
45
46
47
48
49
50
51
52
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! OS distribution type for system information.
//!
//! This module provides a type-safe abstraction for OS distribution names,
//! ensuring valid distribution name strings.
//!
//! # Distribution Name Format
//!
//! OS distribution names follow these rules:
//!
//! - Must be 1-64 characters
//! - Must start with an alphanumeric character
//! - Can contain alphanumeric characters, spaces, hyphens, and underscores
//!
//! # Examples
//!
//! ```rust
//! use bare_types::sys::Distro;
//!
//! // Parse from string
//! let distro: Distro = "Ubuntu".parse()?;
//!
//! // Access as string
//! assert_eq!(distro.as_str(), "Ubuntu");
//! # Ok::<(), bare_types::sys::DistroError>(())
//! ```

use core::fmt;
use core::str::FromStr;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Error type for distribution name parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum DistroError {
    /// Empty distribution name
    ///
    /// The provided string is empty. Distribution names must contain at least one character.
    Empty,
    /// Distribution name too long (max 64 characters)
    ///
    /// Distribution names must not exceed 64 characters.
    /// This variant contains the actual length of the provided distribution name.
    TooLong(usize),
    /// Invalid first character (must be alphanumeric)
    ///
    /// Distribution names must start with an alphanumeric character (letter or digit).
    /// Spaces, hyphens, and underscores are not allowed as the first character.
    InvalidFirstCharacter,
    /// Invalid character in distribution name
    ///
    /// Distribution names can only contain ASCII letters, digits, spaces, hyphens, and underscores.
    /// This variant indicates an invalid character was found.
    InvalidCharacter,
}

impl fmt::Display for DistroError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "distribution name cannot be empty"),
            Self::TooLong(len) => write!(
                f,
                "distribution name too long (got {len}, max 64 characters)"
            ),
            Self::InvalidFirstCharacter => {
                write!(
                    f,
                    "distribution name must start with an alphanumeric character"
                )
            }
            Self::InvalidCharacter => write!(f, "distribution name contains invalid character"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DistroError {}

/// OS distribution name.
///
/// This type provides type-safe OS distribution names.
/// It uses the newtype pattern with `#[repr(transparent)]` for zero-cost abstraction.
#[repr(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Distro(heapless::String<64>);

impl Distro {
    /// Maximum length of a distribution name
    pub const MAX_LEN: usize = 64;

    /// Creates a new distribution name from a string.
    ///
    /// # Errors
    ///
    /// Returns an error `DistroError` if the string is not a valid distribution name.
    pub fn new(s: &str) -> Result<Self, DistroError> {
        Self::validate(s)?;
        let mut value = heapless::String::new();
        value
            .push_str(s)
            .map_err(|_| DistroError::TooLong(s.len()))?;
        Ok(Self(value))
    }

    /// Validates a distribution name string.
    fn validate(s: &str) -> Result<(), DistroError> {
        if s.is_empty() {
            return Err(DistroError::Empty);
        }
        if s.len() > Self::MAX_LEN {
            return Err(DistroError::TooLong(s.len()));
        }
        let mut chars = s.chars();
        if let Some(first) = chars.next()
            && !first.is_ascii_alphanumeric()
        {
            return Err(DistroError::InvalidFirstCharacter);
        }
        for ch in chars {
            if !ch.is_ascii_alphanumeric() && ch != ' ' && ch != '-' && ch != '_' {
                return Err(DistroError::InvalidCharacter);
            }
        }
        Ok(())
    }

    /// Returns the distribution name as a string slice.
    #[must_use]
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns a reference to the underlying `heapless::String`.
    #[must_use]
    #[inline]
    pub const fn as_inner(&self) -> &heapless::String<64> {
        &self.0
    }

    /// Consumes this distribution name and returns the underlying string.
    #[must_use]
    #[inline]
    pub fn into_inner(self) -> heapless::String<64> {
        self.0
    }

    /// Returns `true` if this is a Debian-based distribution.
    ///
    /// This includes Debian, Ubuntu, Linux Mint, Pop!_OS, Kali Linux, etc.
    #[must_use]
    #[inline]
    pub fn is_debian_based(&self) -> bool {
        let s = self.0.to_lowercase();
        s.contains("debian")
            || s.contains("ubuntu")
            || s.contains("mint")
            || s.contains("pop")
            || s.contains("kali")
    }

    /// Returns `true` if this is a Red Hat-based distribution.
    ///
    /// This includes Red Hat Enterprise Linux, Fedora, `CentOS`, Rocky Linux, `AlmaLinux`, etc.
    #[must_use]
    #[inline]
    pub fn is_redhat_based(&self) -> bool {
        let s = self.0.to_lowercase();
        s.contains("red hat")
            || s.contains("redhat")
            || s.contains("fedora")
            || s.contains("centos")
            || s.contains("rhel")
            || s.contains("rocky")
            || s.contains("almalinux")
    }

    /// Returns `true` if this is an Arch-based distribution.
    ///
    /// This includes Arch Linux, Manjaro, `EndeavourOS`, etc.
    #[must_use]
    #[inline]
    pub fn is_arch_based(&self) -> bool {
        let s = self.0.to_lowercase();
        s.contains("arch") || s.contains("manjaro") || s.contains("endeavouros")
    }

    /// Returns `true` if this is a rolling release distribution.
    ///
    /// This includes Arch Linux, Gentoo, Fedora, Void Linux, Debian Sid, etc.
    #[must_use]
    #[inline]
    pub fn is_rolling_release(&self) -> bool {
        let s = self.0.to_lowercase();
        s.contains("arch")
            || s.contains("gentoo")
            || s.contains("fedora")
            || s.contains("void")
            || s.contains("sid")
    }

    /// Returns `true` if this is a long-term support (LTS) distribution.
    ///
    /// This includes Ubuntu LTS, Debian, RHEL, Rocky Linux, `AlmaLinux`, etc.
    #[must_use]
    #[inline]
    pub fn is_lts(&self) -> bool {
        let s = self.0.to_lowercase();
        s.contains("lts")
            || s.contains("ubuntu")
            || s.contains("debian")
            || s.contains("rhel")
            || s.contains("rocky")
            || s.contains("almalinux")
    }
}

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

impl TryFrom<&str> for Distro {
    type Error = DistroError;

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

impl FromStr for Distro {
    type Err = DistroError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

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

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Distro {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
        const DIGITS: &[u8] = b"0123456789";

        // Generate 1-64 character distribution name
        let len = 1 + (u8::arbitrary(u)? % 64).min(63);
        let mut inner = heapless::String::<64>::new();

        // First character: alphanumeric
        let first_byte = u8::arbitrary(u)?;
        if first_byte % 2 == 0 {
            let first = ALPHABET[(first_byte % 26) as usize] as char;
            inner
                .push(first)
                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
        } else {
            let first = DIGITS[(first_byte % 10) as usize] as char;
            inner
                .push(first)
                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
        }

        // Remaining characters: alphanumeric, space, hyphen, or underscore
        for _ in 1..len {
            let byte = u8::arbitrary(u)?;
            let c = match byte % 5 {
                0 => ALPHABET[((byte >> 2) % 26) as usize] as char,
                1 => DIGITS[((byte >> 2) % 10) as usize] as char,
                2 => ' ',
                3 => '-',
                _ => '_',
            };
            inner
                .push(c)
                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
        }

        Ok(Self(inner))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_valid() {
        let distro = Distro::new("Ubuntu").unwrap();
        assert_eq!(distro.as_str(), "Ubuntu");
    }

    #[test]
    fn test_new_empty() {
        assert!(matches!(Distro::new(""), Err(DistroError::Empty)));
    }

    #[test]
    fn test_new_too_long() {
        let long_name = "a".repeat(65);
        assert!(matches!(
            Distro::new(&long_name),
            Err(DistroError::TooLong(65))
        ));
    }

    #[test]
    fn test_new_invalid_first_character() {
        assert!(matches!(
            Distro::new("-Ubuntu"),
            Err(DistroError::InvalidFirstCharacter)
        ));
        assert!(matches!(
            Distro::new(" Ubuntu"),
            Err(DistroError::InvalidFirstCharacter)
        ));
    }

    #[test]
    fn test_new_invalid_character() {
        assert!(matches!(
            Distro::new("Ubuntu@"),
            Err(DistroError::InvalidCharacter)
        ));
        assert!(matches!(
            Distro::new("Ubuntu.Distro"),
            Err(DistroError::InvalidCharacter)
        ));
    }

    #[test]
    fn test_is_debian_based() {
        let ubuntu = Distro::new("Ubuntu").unwrap();
        assert!(ubuntu.is_debian_based());
        let debian = Distro::new("Debian").unwrap();
        assert!(debian.is_debian_based());
        let mint = Distro::new("Linux Mint").unwrap();
        assert!(mint.is_debian_based());
        let fedora = Distro::new("Fedora").unwrap();
        assert!(!fedora.is_debian_based());
    }

    #[test]
    fn test_is_redhat_based() {
        let fedora = Distro::new("Fedora").unwrap();
        assert!(fedora.is_redhat_based());
        let centos = Distro::new("CentOS").unwrap();
        assert!(centos.is_redhat_based());
        let rhel = Distro::new("RHEL").unwrap();
        assert!(rhel.is_redhat_based());
        let ubuntu = Distro::new("Ubuntu").unwrap();
        assert!(!ubuntu.is_redhat_based());
    }

    #[test]
    fn test_is_arch_based() {
        let arch = Distro::new("Arch Linux").unwrap();
        assert!(arch.is_arch_based());
        let manjaro = Distro::new("Manjaro").unwrap();
        assert!(manjaro.is_arch_based());
        let ubuntu = Distro::new("Ubuntu").unwrap();
        assert!(!ubuntu.is_arch_based());
    }

    #[test]
    fn test_is_rolling_release() {
        let arch = Distro::new("Arch Linux").unwrap();
        assert!(arch.is_rolling_release());
        let gentoo = Distro::new("Gentoo").unwrap();
        assert!(gentoo.is_rolling_release());
        let fedora = Distro::new("Fedora").unwrap();
        assert!(fedora.is_rolling_release());
        let ubuntu = Distro::new("Ubuntu").unwrap();
        assert!(!ubuntu.is_rolling_release());
    }

    #[test]
    fn test_is_lts() {
        let ubuntu = Distro::new("Ubuntu LTS").unwrap();
        assert!(ubuntu.is_lts());
        let debian = Distro::new("Debian").unwrap();
        assert!(debian.is_lts());
        let fedora = Distro::new("Fedora").unwrap();
        assert!(!fedora.is_lts());
    }

    #[test]
    fn test_from_str() {
        let distro: Distro = "Ubuntu".parse().unwrap();
        assert_eq!(distro.as_str(), "Ubuntu");
    }

    #[test]
    fn test_from_str_error() {
        assert!("".parse::<Distro>().is_err());
        assert!("-Ubuntu".parse::<Distro>().is_err());
    }

    #[test]
    fn test_display() {
        let distro = Distro::new("Ubuntu").unwrap();
        assert_eq!(format!("{}", distro), "Ubuntu");
    }

    #[test]
    fn test_as_ref() {
        let distro = Distro::new("Ubuntu").unwrap();
        let s: &str = distro.as_ref();
        assert_eq!(s, "Ubuntu");
    }

    #[test]
    fn test_clone() {
        let distro = Distro::new("Ubuntu").unwrap();
        let distro2 = distro.clone();
        assert_eq!(distro, distro2);
    }

    #[test]
    fn test_equality() {
        let d1 = Distro::new("Ubuntu").unwrap();
        let d2 = Distro::new("Ubuntu").unwrap();
        let d3 = Distro::new("Fedora").unwrap();
        assert_eq!(d1, d2);
        assert_ne!(d1, d3);
    }
}