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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Hostname type for network programming.
//!
//! This module provides a type-safe abstraction for DNS hostnames,
//! ensuring compliance with RFC 1123 hostname specifications.
//!
//! # RFC 1123 Hostname Rules
//!
//! According to [RFC 1123 ยง2.1](https://datatracker.ietf.org/doc/html/rfc1123#section-2.1):
//!
//! - Total length: 1-253 characters
//! - Each label (segment separated by dots): 1-63 characters
//! - Valid characters: letters (a-z, A-Z), digits (0-9), and hyphens (-)
//! - Labels cannot start or end with a hyphen
//! - Hostnames are case-insensitive (stored in lowercase internally)
//! - Only ASCII characters are allowed
//!
//! # Examples
//!
//! ```rust
//! use bare_types::net::Hostname;
//!
//! // Create a hostname
//! let hostname = Hostname::new("example.com")?;
//!
//! // Check if it's localhost
//! assert!(!hostname.is_localhost());
//!
//! // Get the string representation
//! assert_eq!(hostname.as_str(), "example.com");
//!
//! // Parse from string
//! let hostname: Hostname = "www.example.com".parse()?;
//! # Ok::<(), bare_types::net::HostnameError>(())
//! ```

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

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

#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

/// Error type for hostname validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum HostnameError {
    /// Empty hostname
    ///
    /// The provided string is empty. Hostnames must contain at least one character.
    Empty,
    /// Hostname exceeds maximum length of 253 characters
    ///
    /// According to RFC 1123, hostnames must not exceed 253 characters.
    /// This variant contains the actual length of the provided hostname.
    TooLong(usize),
    /// Label exceeds maximum length of 63 characters
    ///
    /// Each label (segment separated by dots) must not exceed 63 characters.
    /// This variant contains the label index and its actual length.
    LabelTooLong {
        /// Label index
        label: usize,
        /// Label length
        len: usize,
    },
    /// Label starts with invalid character
    ///
    /// Labels must start with a letter (a-z, A-Z). Hyphens and digits
    /// are not allowed as the first character.
    /// This variant contains the invalid character.
    InvalidLabelStart(char),
    /// Label ends with invalid character
    ///
    /// Labels must end with a letter (a-z, A-Z) or digit (0-9).
    /// Hyphens are not allowed as the last character.
    /// This variant contains the invalid character.
    InvalidLabelEnd(char),
    /// Invalid character in hostname
    ///
    /// Hostnames can only contain ASCII letters, digits, and hyphens.
    /// This variant contains the invalid character.
    InvalidChar(char),
    /// Empty label (consecutive dots or leading/trailing dots)
    ///
    /// Consecutive dots (e.g., "example..com") or leading/trailing dots
    /// (e.g., ".example.com" or "example.com.") are not allowed.
    EmptyLabel,
}

impl fmt::Display for HostnameError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "hostname cannot be empty"),
            Self::TooLong(len) => write!(
                f,
                "hostname exceeds maximum length of 253 characters (got {len})"
            ),
            Self::LabelTooLong { label, len } => {
                write!(
                    f,
                    "label {label} exceeds maximum length of 63 characters (got {len})"
                )
            }
            Self::InvalidLabelStart(c) => write!(f, "label cannot start with '{c}'"),
            Self::InvalidLabelEnd(c) => write!(f, "label cannot end with '{c}'"),
            Self::InvalidChar(c) => write!(f, "invalid character '{c}' in hostname"),
            Self::EmptyLabel => write!(f, "hostname cannot contain empty labels"),
        }
    }
}

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

/// A DNS hostname.
///
/// This type provides type-safe hostnames with RFC 1123 validation.
/// It uses the newtype pattern with `#[repr(transparent)]` for zero-cost abstraction.
///
/// # Invariants
///
/// - Total length is 1-253 characters
/// - Each label is 1-63 characters
/// - Only ASCII letters, digits, and hyphens are allowed
/// - Labels cannot start or end with hyphens
/// - Stored in lowercase for case-insensitive comparison
///
/// # Examples
///
/// ```rust
/// use bare_types::net::Hostname;
///
/// // Create a hostname
/// let hostname = Hostname::new("example.com")?;
///
/// // Access the string representation
/// assert_eq!(hostname.as_str(), "example.com");
///
/// // Check if it's localhost
/// assert!(!hostname.is_localhost());
///
/// // Iterate over labels
/// let labels: Vec<&str> = hostname.labels().collect();
/// assert_eq!(labels, vec!["example", "com"]);
///
/// // Parse from string
/// let hostname: Hostname = "www.example.com".parse()?;
/// # Ok::<(), bare_types::net::HostnameError>(())
/// ```
#[repr(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "zeroize", derive(Zeroize))]
pub struct Hostname(heapless::String<253>);

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

        // Generate 1-4 labels
        let label_count = 1 + (u8::arbitrary(u)? % 4);
        let mut inner = heapless::String::<253>::new();

        for label_idx in 0..label_count {
            // Generate 1-20 character label
            let label_len = 1 + (u8::arbitrary(u)? % 20).min(19);

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

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

            // Last character: alphanumeric (if label_len > 1)
            if label_len > 1 {
                let last_byte = u8::arbitrary(u)?;
                let last = ALPHABET[(last_byte % 26) as usize] as char;
                inner
                    .push(last)
                    .map_err(|_| arbitrary::Error::IncorrectFormat)?;
            }

            // Add dot between labels (but not after the last one)
            if label_idx < label_count - 1 {
                inner
                    .push('.')
                    .map_err(|_| arbitrary::Error::IncorrectFormat)?;
            }
        }

        Ok(Self(inner))
    }
}

impl Hostname {
    /// Creates a new hostname from a string.
    ///
    /// # Errors
    ///
    /// Returns `HostnameError` if the string does not comply with RFC 1123.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// let hostname = Hostname::new("example.com")?;
    /// assert_eq!(hostname.as_str(), "example.com");
    /// # Ok::<(), bare_types::net::HostnameError>(())
    /// ```
    #[allow(clippy::missing_panics_doc)]
    pub fn new(s: &str) -> Result<Self, HostnameError> {
        if s.is_empty() {
            return Err(HostnameError::Empty);
        }

        if s.len() > 253 {
            return Err(HostnameError::TooLong(s.len()));
        }

        let mut inner = heapless::String::<253>::new();
        let mut label_index = 0;
        let mut label_len = 0;
        let mut first_char: Option<char> = None;
        let mut last_char: char = '\0';

        for c in s.chars() {
            if c == '.' {
                if label_len == 0 {
                    return Err(HostnameError::EmptyLabel);
                }

                if label_len > 63 {
                    return Err(HostnameError::LabelTooLong {
                        label: label_index,
                        len: label_len,
                    });
                }

                let first = first_char.expect("label_len > 0 guarantees first_char is Some");
                if !first.is_ascii_alphanumeric() {
                    return Err(HostnameError::InvalidLabelStart(first));
                }

                if !last_char.is_ascii_alphanumeric() {
                    return Err(HostnameError::InvalidLabelEnd(last_char));
                }

                inner.push('.').map_err(|_| HostnameError::TooLong(253))?;
                label_index += 1;
                label_len = 0;
                first_char = None;
            } else {
                if !c.is_ascii() {
                    return Err(HostnameError::InvalidChar(c));
                }

                if !c.is_ascii_alphanumeric() && c != '-' {
                    return Err(HostnameError::InvalidChar(c));
                }

                if label_len == 0 {
                    first_char = Some(c);
                }
                last_char = c;
                label_len += 1;

                inner
                    .push(c.to_ascii_lowercase())
                    .map_err(|_| HostnameError::TooLong(253))?;
            }
        }

        if label_len == 0 {
            return Err(HostnameError::EmptyLabel);
        }

        if label_len > 63 {
            return Err(HostnameError::LabelTooLong {
                label: label_index,
                len: label_len,
            });
        }

        let first = first_char.expect("label_len > 0 guarantees first_char is Some");
        if !first.is_ascii_alphanumeric() {
            return Err(HostnameError::InvalidLabelStart(first));
        }

        if !last_char.is_ascii_alphanumeric() {
            return Err(HostnameError::InvalidLabelEnd(last_char));
        }

        Ok(Self(inner))
    }

    /// Returns the hostname as a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// let hostname = Hostname::new("example.com").unwrap();
    /// assert_eq!(hostname.as_str(), "example.com");
    /// ```
    #[must_use]
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns a reference to the underlying `heapless::String`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// let hostname = Hostname::new("example.com").unwrap();
    /// let inner: &heapless::String<253> = hostname.as_inner();
    /// assert_eq!(inner.as_str(), "example.com");
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_inner(&self) -> &heapless::String<253> {
        &self.0
    }

    /// Consumes this hostname and returns the underlying string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// let hostname = Hostname::new("example.com").unwrap();
    /// let inner = hostname.into_inner();
    /// assert_eq!(inner.as_str(), "example.com");
    /// ```
    #[must_use]
    #[inline]
    pub fn into_inner(self) -> heapless::String<253> {
        self.0
    }

    /// Returns `true` if this is the localhost hostname.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// assert!(Hostname::new("localhost").unwrap().is_localhost());
    /// assert!(!Hostname::new("example.com").unwrap().is_localhost());
    /// ```
    #[must_use]
    #[inline]
    pub fn is_localhost(&self) -> bool {
        self.as_str() == "localhost"
    }

    /// Returns an iterator over the labels in this hostname.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Hostname;
    ///
    /// let hostname = Hostname::new("www.example.com").unwrap();
    /// let labels: Vec<&str> = hostname.labels().collect();
    /// assert_eq!(labels, vec!["www", "example", "com"]);
    /// ```
    pub fn labels(&self) -> impl Iterator<Item = &str> {
        self.as_str().split('.')
    }
}

impl TryFrom<&str> for Hostname {
    type Error = HostnameError;

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

impl From<Hostname> for heapless::String<253> {
    fn from(hostname: Hostname) -> Self {
        hostname.0
    }
}

impl FromStr for Hostname {
    type Err = HostnameError;

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

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

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

    #[test]
    fn test_new_valid_hostname() {
        assert!(Hostname::new("example.com").is_ok());
        assert!(Hostname::new("www.example.com").is_ok());
        assert!(Hostname::new("localhost").is_ok());
        assert!(Hostname::new("a").is_ok());
    }

    #[test]
    fn test_empty_hostname() {
        assert_eq!(Hostname::new(""), Err(HostnameError::Empty));
    }

    #[test]
    fn test_too_long_hostname() {
        let long = "a".repeat(254);
        assert_eq!(Hostname::new(&long), Err(HostnameError::TooLong(254)));
    }

    #[test]
    fn test_label_too_long() {
        let long_label = "a".repeat(64);
        assert_eq!(
            Hostname::new(&long_label),
            Err(HostnameError::LabelTooLong { label: 0, len: 64 })
        );
    }

    #[test]
    fn test_invalid_label_start() {
        assert_eq!(
            Hostname::new("-example.com"),
            Err(HostnameError::InvalidLabelStart('-'))
        );
    }

    #[test]
    fn test_invalid_label_end() {
        assert_eq!(
            Hostname::new("example-.com"),
            Err(HostnameError::InvalidLabelEnd('-'))
        );
    }

    #[test]
    fn test_invalid_char() {
        assert_eq!(
            Hostname::new("example_com"),
            Err(HostnameError::InvalidChar('_'))
        );
    }

    #[test]
    fn test_empty_label() {
        assert_eq!(
            Hostname::new("example..com"),
            Err(HostnameError::EmptyLabel)
        );
        assert_eq!(
            Hostname::new(".example.com"),
            Err(HostnameError::EmptyLabel)
        );
        assert_eq!(
            Hostname::new("example.com."),
            Err(HostnameError::EmptyLabel)
        );
    }

    #[test]
    fn test_as_str() {
        let hostname = Hostname::new("example.com").unwrap();
        assert_eq!(hostname.as_str(), "example.com");
    }

    #[test]
    fn test_into_inner() {
        let hostname = Hostname::new("example.com").unwrap();
        let inner = hostname.into_inner();
        assert_eq!(inner.as_str(), "example.com");
    }

    #[test]
    fn test_is_localhost() {
        assert!(Hostname::new("localhost").unwrap().is_localhost());
        assert!(!Hostname::new("example.com").unwrap().is_localhost());
    }

    #[test]
    fn test_labels() {
        let hostname = Hostname::new("www.example.com").unwrap();
        let labels: Vec<&str> = hostname.labels().collect();
        assert_eq!(labels, vec!["www", "example", "com"]);
    }

    #[test]
    fn test_labels_single() {
        let hostname = Hostname::new("localhost").unwrap();
        let labels: Vec<&str> = hostname.labels().collect();
        assert_eq!(labels, vec!["localhost"]);
    }

    #[test]
    fn test_try_from_str() {
        let hostname = Hostname::try_from("example.com").unwrap();
        assert_eq!(hostname.as_str(), "example.com");
    }

    #[test]
    fn test_from_hostname_to_string() {
        let hostname = Hostname::new("example.com").unwrap();
        let inner: heapless::String<253> = hostname.into();
        assert_eq!(inner.as_str(), "example.com");
    }

    #[test]
    fn test_from_str() {
        let hostname: Hostname = "example.com".parse().unwrap();
        assert_eq!(hostname.as_str(), "example.com");
    }

    #[test]
    fn test_from_str_invalid() {
        assert!("".parse::<Hostname>().is_err());
        assert!("-example.com".parse::<Hostname>().is_err());
        assert!("example..com".parse::<Hostname>().is_err());
    }

    #[test]
    fn test_display() {
        let hostname = Hostname::new("example.com").unwrap();
        assert_eq!(format!("{hostname}"), "example.com");
    }

    #[test]
    fn test_equality() {
        let hostname1 = Hostname::new("example.com").unwrap();
        let hostname2 = Hostname::new("example.com").unwrap();
        let hostname3 = Hostname::new("www.example.com").unwrap();

        assert_eq!(hostname1, hostname2);
        assert_ne!(hostname1, hostname3);
    }

    #[test]
    fn test_ordering() {
        let hostname1 = Hostname::new("a.example.com").unwrap();
        let hostname2 = Hostname::new("b.example.com").unwrap();

        assert!(hostname1 < hostname2);
    }

    #[test]
    fn test_clone() {
        let hostname = Hostname::new("example.com").unwrap();
        let hostname2 = hostname.clone();
        assert_eq!(hostname, hostname2);
    }

    #[test]
    fn test_valid_characters() {
        assert!(Hostname::new("a-b.example.com").is_ok());
        assert!(Hostname::new("a1.example.com").is_ok());
        assert!(Hostname::new("example-123.com").is_ok());
    }

    #[test]
    fn test_maximum_length() {
        let hostname = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(61)
        );
        assert_eq!(hostname.len(), 253);
        assert!(Hostname::new(&hostname).is_ok());
    }

    #[test]
    fn test_error_display() {
        assert_eq!(
            format!("{}", HostnameError::Empty),
            "hostname cannot be empty"
        );
        assert_eq!(
            format!("{}", HostnameError::TooLong(300)),
            "hostname exceeds maximum length of 253 characters (got 300)"
        );
        assert_eq!(
            format!("{}", HostnameError::LabelTooLong { label: 0, len: 70 }),
            "label 0 exceeds maximum length of 63 characters (got 70)"
        );
        assert_eq!(
            format!("{}", HostnameError::InvalidLabelStart('-')),
            "label cannot start with '-'"
        );
        assert_eq!(
            format!("{}", HostnameError::InvalidLabelEnd('-')),
            "label cannot end with '-'"
        );
        assert_eq!(
            format!("{}", HostnameError::InvalidChar('_')),
            "invalid character '_' in hostname"
        );
        assert_eq!(
            format!("{}", HostnameError::EmptyLabel),
            "hostname cannot contain empty labels"
        );
    }

    #[test]
    fn test_case_insensitive() {
        let hostname1 = Hostname::new("Example.COM").unwrap();
        let hostname2 = Hostname::new("example.com").unwrap();
        assert_eq!(hostname1, hostname2);
        assert_eq!(hostname1.as_str(), "example.com");
    }
}