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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
//! Domain name type for DNS programming.
//!
//! This module provides a type-safe abstraction for DNS domain names,
//! ensuring compliance with RFC 1035 domain name specifications.
//!
//! # RFC 1035 Domain Name Rules
//!
//! According to [RFC 1035 ยง2.3.4](https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.4):
//!
//! - 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
//! - Domain names are case-insensitive (stored in lowercase internally)
//! - Only ASCII characters are allowed
//! - Labels CAN start with digits (unlike RFC 1123 hostnames)
//!
//! # Domain Name vs Hostname
//!
//! The key difference between `DomainName` and `Hostname`:
//! - **`DomainName`** (RFC 1035): Labels can start with digits (e.g., "123.example.com")
//! - **`Hostname`** (RFC 1123): Labels must start with letters (e.g., "www.example.com")
//!
//! # Examples
//!
//! ```rust
//! use bare_types::net::DomainName;
//!
//! // Create a domain name
//! let domain = DomainName::new("example.com")?;
//!
//! // Check depth (number of labels)
//! assert_eq!(domain.depth(), 2);
//!
//! // Check if it's a subdomain
//! let parent = DomainName::new("example.com")?;
//! let child = DomainName::new("www.example.com")?;
//! assert!(child.is_subdomain_of(&parent));
//!
//! // Get the string representation
//! assert_eq!(domain.as_str(), "example.com");
//!
//! // Parse from string
//! let domain: DomainName = "123.example.com".parse()?;
//! # Ok::<(), bare_types::net::DomainNameError>(())
//! ```

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

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

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

/// Error type for domain name validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum DomainNameError {
    /// Empty domain name
    ///
    /// The provided string is empty. Domain names must contain at least one character.
    Empty,
    /// Domain name exceeds maximum length of 253 characters
    ///
    /// According to RFC 1035, domain names must not exceed 253 characters.
    /// This variant contains the actual length of the provided domain name.
    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 an alphanumeric character (letter or digit).
    /// Hyphens are not allowed as the first character.
    /// This variant contains the invalid character.
    InvalidLabelStart(char),
    /// Label ends with invalid character
    ///
    /// Labels must end with an alphanumeric character (letter or digit).
    /// Hyphens are not allowed as the last character.
    /// This variant contains the invalid character.
    InvalidLabelEnd(char),
    /// Invalid character in domain name
    ///
    /// Domain names 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 DomainNameError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "domain name cannot be empty"),
            Self::TooLong(len) => write!(
                f,
                "domain name 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 domain name"),
            Self::EmptyLabel => write!(f, "domain name cannot contain empty labels"),
        }
    }
}

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

/// A DNS domain name.
///
/// This type provides type-safe domain names with RFC 1035 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
/// - Labels CAN start with digits (unlike RFC 1123 hostnames)
/// - Stored in lowercase for case-insensitive comparison
///
/// # Examples
///
/// ```rust
/// use bare_types::net::DomainName;
///
/// // Create a domain name
/// let domain = DomainName::new("example.com")?;
///
/// // Access the string representation
/// assert_eq!(domain.as_str(), "example.com");
///
/// // Check depth (number of labels)
/// assert_eq!(domain.depth(), 2);
///
/// // Check if it's a subdomain
/// let parent = DomainName::new("example.com")?;
/// let child = DomainName::new("www.example.com")?;
/// assert!(child.is_subdomain_of(&parent));
///
/// // Iterate over labels
/// let labels: Vec<&str> = domain.labels().collect();
/// assert_eq!(labels, vec!["example", "com"]);
///
/// // Parse from string
/// let domain: DomainName = "123.example.com".parse()?;
/// # Ok::<(), bare_types::net::DomainNameError>(())
/// ```
#[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 DomainName(heapless::String<253>);

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for DomainName {
    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 (digits allowed for domain names)
            let first_byte = u8::arbitrary(u)?;
            let first = match first_byte % 2 {
                0 => ALPHABET[((first_byte >> 1) % 26) as usize] as char,
                _ => DIGITS[((first_byte >> 1) % 10) 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 % 4 {
                    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 = match last_byte % 2 {
                    0 => ALPHABET[((last_byte >> 1) % 26) as usize] as char,
                    _ => DIGITS[((last_byte >> 1) % 10) 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 DomainName {
    /// Creates a new domain name from a string.
    ///
    /// # Errors
    ///
    /// Returns `DomainNameError` if the string does not comply with RFC 1035.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let domain = DomainName::new("example.com")?;
    /// assert_eq!(domain.as_str(), "example.com");
    ///
    /// // Labels can start with digits (RFC 1035)
    /// let domain = DomainName::new("123.example.com")?;
    /// assert_eq!(domain.as_str(), "123.example.com");
    /// # Ok::<(), bare_types::net::DomainNameError>(())
    /// ```
    #[allow(clippy::missing_panics_doc)]
    pub fn new(s: &str) -> Result<Self, DomainNameError> {
        if s.is_empty() {
            return Err(DomainNameError::Empty);
        }

        if s.len() > 253 {
            return Err(DomainNameError::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(DomainNameError::EmptyLabel);
                }

                if label_len > 63 {
                    return Err(DomainNameError::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(DomainNameError::InvalidLabelStart(first));
                }

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

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

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

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

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

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

        if label_len > 63 {
            return Err(DomainNameError::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(DomainNameError::InvalidLabelStart(first));
        }

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

        Ok(Self(inner))
    }

    /// Returns the domain name as a string slice.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let domain = DomainName::new("example.com").unwrap();
    /// assert_eq!(domain.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::DomainName;
    ///
    /// let domain = DomainName::new("example.com").unwrap();
    /// let inner: &heapless::String<253> = domain.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 domain name and returns the underlying string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let domain = DomainName::new("example.com").unwrap();
    /// let inner = domain.into_inner();
    /// assert_eq!(inner.as_str(), "example.com");
    /// ```
    #[must_use]
    #[inline]
    pub fn into_inner(self) -> heapless::String<253> {
        self.0
    }

    /// Returns the depth (number of labels) of this domain name.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let domain = DomainName::new("example.com").unwrap();
    /// assert_eq!(domain.depth(), 2);
    ///
    /// let domain = DomainName::new("www.example.com").unwrap();
    /// assert_eq!(domain.depth(), 3);
    /// ```
    #[must_use]
    #[inline]
    pub fn depth(&self) -> usize {
        self.as_str().chars().filter(|&c| c == '.').count() + 1
    }

    /// Returns `true` if this domain name is a subdomain of `other`.
    ///
    /// A domain name is considered a subdomain if it has more labels
    /// and ends with the parent domain name.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let parent = DomainName::new("example.com").unwrap();
    /// let child = DomainName::new("www.example.com").unwrap();
    /// assert!(child.is_subdomain_of(&parent));
    /// assert!(!parent.is_subdomain_of(&child));
    /// assert!(!parent.is_subdomain_of(&parent));
    /// ```
    #[must_use]
    #[inline]
    pub fn is_subdomain_of(&self, other: &Self) -> bool {
        if self.depth() <= other.depth() {
            return false;
        }

        let self_str = self.as_str();
        let other_str = other.as_str();

        self_str.len() > other_str.len() + 1 && self_str.ends_with(&format!(".{other_str}"))
    }

    /// Returns `true` if this domain name is a top-level domain (TLD).
    ///
    /// A TLD is a domain name with only one label.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let tld = DomainName::new("com").unwrap();
    /// assert!(tld.is_tld());
    ///
    /// let domain = DomainName::new("example.com").unwrap();
    /// assert!(!domain.is_tld());
    /// ```
    #[must_use]
    #[inline]
    pub fn is_tld(&self) -> bool {
        self.depth() == 1
    }

    /// Returns an iterator over the labels in this domain name.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::DomainName;
    ///
    /// let domain = DomainName::new("www.example.com").unwrap();
    /// let labels: Vec<&str> = domain.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 DomainName {
    type Error = DomainNameError;

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

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

impl FromStr for DomainName {
    type Err = DomainNameError;

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

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

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

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

    #[test]
    fn test_empty_domain_name() {
        assert_eq!(DomainName::new(""), Err(DomainNameError::Empty));
    }

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

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

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

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

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

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

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

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

    #[test]
    fn test_depth() {
        let domain = DomainName::new("com").unwrap();
        assert_eq!(domain.depth(), 1);

        let domain = DomainName::new("example.com").unwrap();
        assert_eq!(domain.depth(), 2);

        let domain = DomainName::new("www.example.com").unwrap();
        assert_eq!(domain.depth(), 3);
    }

    #[test]
    fn test_is_subdomain_of() {
        let parent = DomainName::new("example.com").unwrap();
        let child = DomainName::new("www.example.com").unwrap();
        let grandchild = DomainName::new("sub.www.example.com").unwrap();

        assert!(child.is_subdomain_of(&parent));
        assert!(grandchild.is_subdomain_of(&parent));
        assert!(grandchild.is_subdomain_of(&child));
        assert!(!parent.is_subdomain_of(&child));
        assert!(!parent.is_subdomain_of(&parent));
        assert!(!child.is_subdomain_of(&child));
    }

    #[test]
    fn test_is_tld() {
        let tld = DomainName::new("com").unwrap();
        assert!(tld.is_tld());

        let domain = DomainName::new("example.com").unwrap();
        assert!(!domain.is_tld());
    }

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

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

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

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

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

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

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

    #[test]
    fn test_equality() {
        let domain1 = DomainName::new("example.com").unwrap();
        let domain2 = DomainName::new("example.com").unwrap();
        let domain3 = DomainName::new("www.example.com").unwrap();

        assert_eq!(domain1, domain2);
        assert_ne!(domain1, domain3);
    }

    #[test]
    fn test_ordering() {
        let domain1 = DomainName::new("a.example.com").unwrap();
        let domain2 = DomainName::new("b.example.com").unwrap();

        assert!(domain1 < domain2);
    }

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

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

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

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

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

    #[test]
    fn test_digit_start_labels() {
        // RFC 1035 allows labels to start with digits
        assert!(DomainName::new("123.example.com").is_ok());
        assert!(DomainName::new("50-name.example.com").is_ok());
        assert!(DomainName::new("235235").is_ok());
        assert!(DomainName::new("0a.example.com").is_ok());
        assert!(DomainName::new("9z.example.com").is_ok());
    }

    #[test]
    fn test_digit_start_labels_valid() {
        let domain = DomainName::new("123.example.com").unwrap();
        assert_eq!(domain.as_str(), "123.example.com");
        assert_eq!(domain.depth(), 3);

        let labels: Vec<&str> = domain.labels().collect();
        assert_eq!(labels, vec!["123", "example", "com"]);
    }

    #[test]
    fn test_hyphen_not_at_boundaries() {
        assert!(DomainName::new("a-b.example.com").is_ok());
        assert!(DomainName::new("a-b-c.example.com").is_ok());
        assert!(DomainName::new("example.a-b.com").is_ok());
    }

    #[test]
    fn test_multiple_labels() {
        let domain = DomainName::new("a.b.c.d.e.f.g").unwrap();
        assert_eq!(domain.depth(), 7);

        let labels: Vec<&str> = domain.labels().collect();
        assert_eq!(labels, vec!["a", "b", "c", "d", "e", "f", "g"]);
    }

    #[test]
    fn test_subdomain_edge_cases() {
        let parent = DomainName::new("example.com").unwrap();
        let child = DomainName::new("example.com").unwrap();

        // Same domain is not a subdomain
        assert!(!child.is_subdomain_of(&parent));

        // TLD is not a subdomain of anything
        let tld = DomainName::new("com").unwrap();
        assert!(!tld.is_subdomain_of(&parent));
    }

    #[test]
    fn test_single_label_domain() {
        let domain = DomainName::new("localhost").unwrap();
        assert_eq!(domain.depth(), 1);
        assert!(domain.is_tld());

        let labels: Vec<&str> = domain.labels().collect();
        assert_eq!(labels, vec!["localhost"]);
    }

    #[test]
    fn test_numeric_only_label() {
        assert!(DomainName::new("123").is_ok());
        assert!(DomainName::new("123.456").is_ok());
        assert!(DomainName::new("123.456.789").is_ok());
    }

    #[test]
    fn test_mixed_alphanumeric_labels() {
        assert!(DomainName::new("a1b2c3.example.com").is_ok());
        assert!(DomainName::new("123abc.example.com").is_ok());
        assert!(DomainName::new("abc123.example.com").is_ok());
    }

    #[test]
    fn test_maximum_label_length() {
        let label = "a".repeat(63);
        {
            let domain = DomainName::new(&label).unwrap();
            assert_eq!(domain.depth(), 1);
        }

        let domain = format!("{}.{}", "a".repeat(63), "b".repeat(63));
        assert_eq!(domain.len(), 127);
        assert!(DomainName::new(&domain).is_ok());
    }

    #[test]
    fn test_maximum_total_length() {
        let domain = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(61)
        );
        assert_eq!(domain.len(), 253);

        let domain = DomainName::new(&domain).unwrap();
        assert_eq!(domain.depth(), 4);
        assert_eq!(domain.as_str().len(), 253);
    }

    #[test]
    fn test_maximum_total_length_plus_one() {
        let domain = format!(
            "{}.{}.{}.{}",
            "a".repeat(63),
            "b".repeat(63),
            "c".repeat(63),
            "d".repeat(62)
        );
        assert_eq!(domain.len(), 254);
        assert_eq!(DomainName::new(&domain), Err(DomainNameError::TooLong(254)));
    }

    #[test]
    fn test_unicode_rejected() {
        assert!(DomainName::new("exรคmple.com").is_err());
        assert!(DomainName::new("ไพ‹ใˆ.com").is_err());
        assert!(DomainName::new("ไพ‹ใˆ.ใƒ†ใ‚นใƒˆ").is_err());
    }

    #[test]
    fn test_special_characters_rejected() {
        assert!(DomainName::new("example_com").is_err());
        assert!(DomainName::new("example.com/test").is_err());
        assert!(DomainName::new("example.com?").is_err());
        assert!(DomainName::new("example.com#").is_err());
        assert!(DomainName::new("example.com@").is_err());
        assert!(DomainName::new("example.com!").is_err());
    }

    #[test]
    fn test_whitespace_rejected() {
        assert!(DomainName::new("example .com").is_err());
        assert!(DomainName::new("example. com").is_err());
        assert!(DomainName::new("example . com").is_err());
        assert!(DomainName::new("example\t.com").is_err());
        assert!(DomainName::new("example\n.com").is_err());
    }

    #[test]
    fn test_empty_labels_rejected() {
        assert!(DomainName::new(".example.com").is_err());
        assert!(DomainName::new("example..com").is_err());
        assert!(DomainName::new("example.com.").is_err());
        assert!(DomainName::new("..").is_err());
        assert!(DomainName::new(".").is_err());
    }

    #[test]
    fn test_hyphen_at_start_rejected() {
        assert!(DomainName::new("-example.com").is_err());
        assert!(DomainName::new("example.-com").is_err());
        assert!(DomainName::new("-.example.com").is_err());
    }

    #[test]
    fn test_hyphen_at_end_rejected() {
        assert!(DomainName::new("example-.com").is_err());
        assert!(DomainName::new("example.com-").is_err());
        assert!(DomainName::new("example.-").is_err());
    }

    #[test]
    fn test_consecutive_hyphens_allowed() {
        assert!(DomainName::new("a--b.example.com").is_ok());
        assert!(DomainName::new("a---b.example.com").is_ok());
    }

    #[test]
    fn test_hash() {
        use core::hash::Hash;
        use core::hash::Hasher;

        #[derive(Default)]
        struct SimpleHasher(u64);

        impl Hasher for SimpleHasher {
            fn finish(&self) -> u64 {
                self.0
            }

            fn write(&mut self, bytes: &[u8]) {
                for byte in bytes {
                    self.0 = self.0.wrapping_mul(31).wrapping_add(*byte as u64);
                }
            }
        }

        let domain1 = DomainName::new("example.com").unwrap();
        let domain2 = DomainName::new("example.com").unwrap();
        let domain3 = DomainName::new("www.example.com").unwrap();

        let mut hasher1 = SimpleHasher::default();
        let mut hasher2 = SimpleHasher::default();
        let mut hasher3 = SimpleHasher::default();

        domain1.hash(&mut hasher1);
        domain2.hash(&mut hasher2);
        domain3.hash(&mut hasher3);

        assert_eq!(hasher1.finish(), hasher2.finish());
        assert_ne!(hasher1.finish(), hasher3.finish());
    }

    #[test]
    fn test_ordering_lexicographic() {
        let domain1 = DomainName::new("a.example.com").unwrap();
        let domain2 = DomainName::new("b.example.com").unwrap();
        let domain3 = DomainName::new("a.example.com").unwrap();

        assert!(domain1 < domain2);
        assert!(domain2 > domain1);
        assert_eq!(domain1, domain3);
    }

    #[test]
    fn test_ordering_different_lengths() {
        let domain1 = DomainName::new("a.com").unwrap();
        let domain2 = DomainName::new("a.example.com").unwrap();

        assert!(domain1 < domain2);
    }

    #[test]
    fn test_debug() {
        let domain = DomainName::new("example.com").unwrap();
        assert_eq!(format!("{:?}", domain), "DomainName(\"example.com\")");
    }

    #[test]
    fn test_as_inner() {
        let domain = DomainName::new("example.com").unwrap();
        let inner = domain.as_inner();
        assert_eq!(inner.as_str(), "example.com");
    }

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