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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Operating system version type for system information.
//!
//! This module provides a type-safe abstraction for operating system versions,
//! ensuring valid version number parsing and comparison.
//!
//! # Version Format
//!
//! OS versions follow semantic versioning principles:
//!
//! - **Major**: Major version number (e.g., 14 for macOS Sonoma)
//! - **Minor**: Minor version number (e.g., 6 for macOS 14.6)
//! - **Patch**: Patch/build number (e.g., 1 for 14.6.1)
//!
//! # Examples
//!
//! ```rust
//! use bare_types::sys::OsVersion;
//!
//! // Parse from string
//! let version: OsVersion = "14.6.1".parse()?;
//!
//! // Access components
//! assert_eq!(version.major(), 14);
//! assert_eq!(version.minor(), 6);
//! assert_eq!(version.patch(), Some(1));
//!
//! // Compare versions
//! assert!(version >= OsVersion::new(14, 0, None));
//!
//! // Short version (no patch)
//! let version: OsVersion = "14.6".parse()?;
//! assert_eq!(version.patch(), None);
//! # Ok::<(), bare_types::sys::OsVersionError>(())
//! ```

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

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

#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;

/// Error type for OS version parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum OsVersionError {
    /// Empty version string
    ///
    /// The provided string is empty. Version strings must contain at least
    /// major and a minor version number (e.g., "14.6").
    Empty,
    /// Invalid major version number
    ///
    /// The major version component could not be parsed as a valid u16 number.
    /// Version numbers must be non-negative integers.
    InvalidMajor,
    /// Invalid minor version number
    ///
    /// The minor version component could not be parsed as a valid u16 number.
    /// Version numbers must be non-negative integers.
    InvalidMinor,
    /// Invalid patch version number
    ///
    /// The patch version component could not be parsed as a valid u16 number.
    /// Version numbers must be non-negative integers.
    InvalidPatch,
    /// Too many version components (max 3)
    ///
    /// Version strings can have at most 3 components: major.minor.patch.
    /// More than 3 components (e.g., "1.2.3.4") are not supported.
    TooManyComponents,
    /// Negative version number
    ///
    /// Version numbers cannot be negative. This error may occur if parsing
    /// negative integers in version components.
    NegativeVersion,
}

impl fmt::Display for OsVersionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "version string is empty"),
            Self::InvalidMajor => write!(f, "invalid major version number"),
            Self::InvalidMinor => write!(f, "invalid minor version number"),
            Self::InvalidPatch => write!(f, "invalid patch version number"),
            Self::TooManyComponents => write!(f, "version has too many components (max 3)"),
            Self::NegativeVersion => write!(f, "version numbers cannot be negative"),
        }
    }
}

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

/// Operating system version.
///
/// This type provides type-safe OS version numbers with up to three components:
/// major, minor, and optional patch version.
///
/// # Invariants
///
/// - Major and minor versions are always present (u16)
/// - Patch version is optional (Some(u16) or None)
/// - All version numbers are non-negative
///
/// # Examples
///
/// ```rust
/// use bare_types::sys::OsVersion;
///
/// // Create from components
/// let version = OsVersion::new(14, 6, Some(1));
///
/// // Parse from string
/// let version: OsVersion = "14.6.1".parse()?;
/// assert_eq!(version.major(), 14);
///
/// // Two-component version
/// let version: OsVersion = "22.04".parse()?;
/// assert_eq!(version.patch(), None);
/// # Ok::<(), bare_types::sys::OsVersionError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub struct OsVersion {
    /// The major version number
    major: u16,
    /// The minor version number
    minor: u16,
    /// The optional patch version number
    patch: Option<u16>,
}

impl OsVersion {
    /// Creates a new OS version from components.
    ///
    /// # Arguments
    ///
    /// * `major` - The major version number
    /// * `minor` - The minor version number
    /// * `patch` - The optional patch version number
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// // Three-component version
    /// let version = OsVersion::new(14, 6, Some(1));
    /// assert_eq!(version.major(), 14);
    /// assert_eq!(version.minor(), 6);
    /// assert_eq!(version.patch(), Some(1));
    ///
    /// // Two-component version
    /// let version = OsVersion::new(22, 4, None);
    /// assert_eq!(version.patch(), None);
    /// ```
    #[must_use]
    pub const fn new(major: u16, minor: u16, patch: Option<u16>) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Returns the major version number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, Some(1));
    /// assert_eq!(version.major(), 14);
    /// ```
    #[must_use]
    #[inline]
    pub const fn major(&self) -> u16 {
        self.major
    }

    /// Returns the minor version number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, Some(1));
    /// assert_eq!(version.minor(), 6);
    /// ```
    #[must_use]
    #[inline]
    pub const fn minor(&self) -> u16 {
        self.minor
    }

    /// Returns the optional patch version number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, Some(1));
    /// assert_eq!(version.patch(), Some(1));
    ///
    /// let version = OsVersion::new(22, 4, None);
    /// assert_eq!(version.patch(), None);
    /// ```
    #[must_use]
    #[inline]
    pub const fn patch(&self) -> Option<u16> {
        self.patch
    }

    /// Returns `true` if this is a major version (x.0.x or x.0).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// assert!(OsVersion::new(14, 0, Some(0)).is_major_release());
    /// assert!(OsVersion::new(14, 0, None).is_major_release());
    /// assert!(!OsVersion::new(14, 6, Some(0)).is_major_release());
    /// ```
    #[must_use]
    pub const fn is_major_release(&self) -> bool {
        self.minor == 0
            && match self.patch {
                Some(p) => p == 0,
                None => true,
            }
    }

    /// Returns `true` if this is an initial release (x.0.0 or x.0).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// assert!(OsVersion::new(14, 0, Some(0)).is_initial_release());
    /// assert!(!OsVersion::new(14, 6, Some(0)).is_initial_release());
    /// ```
    #[must_use]
    pub const fn is_initial_release(&self) -> bool {
        self.minor == 0
            && match self.patch {
                Some(p) => p == 0,
                None => true,
            }
    }

    /// Returns a tuple of (major, minor, patch) for comparison.
    ///
    /// For versions without a patch, 0 is used as the patch number for comparison.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, Some(1));
    /// assert_eq!(version.as_tuple(), (14, 6, 1));
    ///
    /// let version = OsVersion::new(22, 4, None);
    /// assert_eq!(version.as_tuple(), (22, 4, 0));
    /// ```
    #[must_use]
    pub const fn as_tuple(&self) -> (u16, u16, u16) {
        (
            self.major,
            self.minor,
            match self.patch {
                Some(p) => p,
                None => 0,
            },
        )
    }

    /// Returns a new version with only major and minor components.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, Some(1));
    /// let short = version.to_short();
    /// assert_eq!(short.patch(), None);
    /// assert_eq!(short.major(), 14);
    /// assert_eq!(short.minor(), 6);
    /// ```
    #[must_use]
    pub const fn to_short(&self) -> Self {
        Self::new(self.major, self.minor, None)
    }

    /// Returns a new version with the patch component set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new(14, 6, None);
    /// let patched = version.with_patch(1);
    /// assert_eq!(patched.patch(), Some(1));
    /// ```
    #[must_use]
    pub const fn with_patch(&self, patch: u16) -> Self {
        Self::new(self.major, self.minor, Some(patch))
    }

    /// Creates a version from major and minor only.
    ///
    /// This is a convenience method for two-component versions.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::sys::OsVersion;
    ///
    /// let version = OsVersion::new_short(22, 4);
    /// assert_eq!(version.major(), 22);
    /// assert_eq!(version.minor(), 4);
    /// assert_eq!(version.patch(), None);
    /// ```
    #[must_use]
    pub const fn new_short(major: u16, minor: u16) -> Self {
        Self::new(major, minor, None)
    }
}

impl FromStr for OsVersion {
    type Err = OsVersionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(OsVersionError::Empty);
        }

        let parts: Vec<&str> = s.split('.').collect();

        if parts.len() > 3 {
            return Err(OsVersionError::TooManyComponents);
        }

        if parts.len() < 2 {
            return Err(OsVersionError::InvalidMinor);
        }

        let major = parts[0]
            .parse::<u16>()
            .map_err(|_| OsVersionError::InvalidMajor)?;

        let minor = parts[1]
            .parse::<u16>()
            .map_err(|_| OsVersionError::InvalidMinor)?;

        let patch = if parts.len() > 2 {
            Some(
                parts[2]
                    .parse::<u16>()
                    .map_err(|_| OsVersionError::InvalidPatch)?,
            )
        } else {
            None
        };

        Ok(Self::new(major, minor, patch))
    }
}

impl TryFrom<&str> for OsVersion {
    type Error = OsVersionError;

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

impl fmt::Display for OsVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(patch) = self.patch {
            write!(f, "{}.{}.{}", self.major, self.minor, patch)
        } else {
            write!(f, "{}.{}", self.major, self.minor)
        }
    }
}

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

    #[test]
    fn test_new() {
        let version = OsVersion::new(14, 6, Some(1));
        assert_eq!(version.major(), 14);
        assert_eq!(version.minor(), 6);
        assert_eq!(version.patch(), Some(1));

        let version = OsVersion::new(22, 4, None);
        assert_eq!(version.major(), 22);
        assert_eq!(version.minor(), 4);
        assert_eq!(version.patch(), None);
    }

    #[test]
    fn test_new_short() {
        let version = OsVersion::new_short(22, 4);
        assert_eq!(version.major(), 22);
        assert_eq!(version.minor(), 4);
        assert_eq!(version.patch(), None);
    }

    #[test]
    fn test_is_major_release() {
        assert!(OsVersion::new(14, 0, Some(0)).is_major_release());
        assert!(OsVersion::new(14, 0, None).is_major_release());
        assert!(!OsVersion::new(14, 6, Some(0)).is_major_release());
        assert!(!OsVersion::new(14, 6, None).is_major_release());
    }

    #[test]
    fn test_is_initial_release() {
        assert!(OsVersion::new(14, 0, Some(0)).is_initial_release());
        assert!(!OsVersion::new(14, 6, Some(0)).is_initial_release());
        assert!(OsVersion::new(14, 0, None).is_initial_release());
    }

    #[test]
    fn test_as_tuple() {
        let version = OsVersion::new(14, 6, Some(1));
        assert_eq!(version.as_tuple(), (14, 6, 1));

        let version = OsVersion::new(22, 4, None);
        assert_eq!(version.as_tuple(), (22, 4, 0));
    }

    #[test]
    fn test_to_short() {
        let version = OsVersion::new(14, 6, Some(1));
        let short = version.to_short();
        assert_eq!(short.patch(), None);
        assert_eq!(short.major(), 14);
        assert_eq!(short.minor(), 6);
    }

    #[test]
    fn test_with_patch() {
        let version = OsVersion::new(14, 6, None);
        let patched = version.with_patch(1);
        assert_eq!(patched.patch(), Some(1));
        assert_eq!(patched.major(), 14);
        assert_eq!(patched.minor(), 6);
    }

    #[test]
    fn test_from_str_three_components() {
        let version: OsVersion = "14.6.1".parse().unwrap();
        assert_eq!(version.major(), 14);
        assert_eq!(version.minor(), 6);
        assert_eq!(version.patch(), Some(1));
    }

    #[test]
    fn test_from_str_two_components() {
        let version: OsVersion = "22.04".parse().unwrap();
        assert_eq!(version.major(), 22);
        assert_eq!(version.minor(), 4);
        assert_eq!(version.patch(), None);
    }

    #[test]
    fn test_from_str_zero_padded() {
        let version: OsVersion = "10.0.19041".parse().unwrap();
        assert_eq!(version.major(), 10);
        assert_eq!(version.minor(), 0);
        assert_eq!(version.patch(), Some(19041));
    }

    #[test]
    fn test_from_str_errors() {
        // Empty
        assert!(matches!(
            "".parse::<OsVersion>(),
            Err(OsVersionError::Empty)
        ));

        // Too many components
        assert!(matches!(
            "1.2.3.4".parse::<OsVersion>(),
            Err(OsVersionError::TooManyComponents)
        ));

        // Only one component
        assert!(matches!(
            "14".parse::<OsVersion>(),
            Err(OsVersionError::InvalidMinor)
        ));

        // Invalid numbers
        assert!("abc.def".parse::<OsVersion>().is_err());
        assert!("14.abc".parse::<OsVersion>().is_err());
        assert!("14.6.abc".parse::<OsVersion>().is_err());
    }

    #[test]
    fn test_display() {
        let version = OsVersion::new(14, 6, Some(1));
        assert_eq!(format!("{}", version), "14.6.1");

        let version = OsVersion::new(22, 4, None);
        assert_eq!(format!("{}", version), "22.4");
    }

    #[test]
    fn test_equality() {
        let v1 = OsVersion::new(14, 6, Some(1));
        let v2 = OsVersion::new(14, 6, Some(1));
        let v3 = OsVersion::new(14, 6, None);

        assert_eq!(v1, v2);
        assert_ne!(v1, v3);
    }

    #[test]
    fn test_ordering() {
        let v1 = OsVersion::new(14, 6, Some(1));
        let v2 = OsVersion::new(14, 6, Some(2));
        let v3 = OsVersion::new(14, 7, None);
        let v4 = OsVersion::new(15, 0, None);

        assert!(v1 < v2);
        assert!(v2 < v3);
        assert!(v3 < v4);

        // Version with patch > version without patch at same major.minor
        let with_patch = OsVersion::new(14, 6, Some(0));
        let without_patch = OsVersion::new(14, 6, None);
        assert!(without_patch < with_patch);
    }

    #[test]
    fn test_copy() {
        let version = OsVersion::new(14, 6, Some(1));
        let version2 = version;
        assert_eq!(version, version2);
    }

    #[test]
    fn test_clone() {
        let version = OsVersion::new(14, 6, Some(1));
        let version2 = version.clone();
        assert_eq!(version, version2);
    }

    #[test]
    fn test_common_versions() {
        // Ubuntu LTS versions
        let ubuntu_2204: OsVersion = "22.04".parse().unwrap();
        assert_eq!(ubuntu_2204.major(), 22);
        assert_eq!(ubuntu_2204.minor(), 4);

        let ubuntu_2404: OsVersion = "24.04".parse().unwrap();
        assert_eq!(ubuntu_2404.major(), 24);

        // macOS versions
        let macos_sonoma: OsVersion = "14.6.1".parse().unwrap();
        assert_eq!(macos_sonoma.major(), 14);
        assert_eq!(macos_sonoma.minor(), 6);
        assert_eq!(macos_sonoma.patch(), Some(1));

        // Windows versions
        let win11: OsVersion = "10.0.22000".parse().unwrap();
        assert_eq!(win11.major(), 10);
        assert_eq!(win11.minor(), 0);
        assert_eq!(win11.patch(), Some(22000));
    }
}