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
//! Digits of fractions of a second.

#[cfg(feature = "alloc")]
mod owned;

use core::{
    cmp,
    convert::TryFrom,
    fmt,
    ops::{self, RangeTo},
    str,
};

use crate::{
    error::{ComponentKind, Error, ErrorKind},
    parse::parse_digits8,
};

#[cfg(feature = "alloc")]
pub use self::owned::SecfracDigitsString;

/// Range of a milliseconds part.
const MILLI_RANGE: RangeTo<usize> = ..3;
/// Range of a microsecodns part.
const MICRO_RANGE: RangeTo<usize> = ..6;
/// Range of a milliseconds part.
const NANO_RANGE: RangeTo<usize> = ..9;

/// Validates the given string as digits of fractions of a second.
///
/// This function ensures that the given bytes is not empty and consists of only ASCII digits.
fn validate_bytes(s: &[u8]) -> Result<(), Error> {
    if s.is_empty() {
        return Err(ErrorKind::TooShort.into());
    }

    if !s.iter().all(u8::is_ascii_digit) {
        return Err(ErrorKind::InvalidComponentType(ComponentKind::Secfrac).into());
    }

    Ok(())
}

/// String slice for digits of fractions of a second.
///
/// Note that values of this type cannot be not empty string.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
// Note that `derive(Serialize)` cannot used here, because it encodes this as
// `[u8]` rather than as a string.
//
// Comparisons implemented for the type are consistent (at least it is intended to be so).
// See <https://github.com/rust-lang/rust-clippy/issues/2025>.
// Note that `clippy::derive_ord_xor_partial_ord` would be introduced since Rust 1.47.0.
#[allow(clippy::derive_hash_xor_eq)]
#[allow(clippy::unknown_clippy_lints, clippy::derive_ord_xor_partial_ord)]
pub struct SecfracDigitsStr([u8]);

impl SecfracDigitsStr {
    /// Creates a `&SecfracDigitsStr` from the given byte slice.
    ///
    /// This performs assertion in debug build, but not in release build.
    ///
    /// # Safety
    ///
    /// `validate_bytes(s)` should return `Ok(())`.
    #[inline]
    #[must_use]
    pub(crate) unsafe fn from_bytes_maybe_unchecked(s: &[u8]) -> &Self {
        debug_assert_ok!(validate_bytes(s));
        &*(s as *const [u8] as *const Self)
    }

    /// Creates a `&mut SecfracDigitsStr` from the given mutable byte slice.
    ///
    /// This performs assertion in debug build, but not in release build.
    ///
    /// # Safety
    ///
    /// `validate_bytes(s)` should return `Ok(())`.
    #[inline]
    #[must_use]
    pub(crate) unsafe fn from_bytes_maybe_unchecked_mut(s: &mut [u8]) -> &mut Self {
        debug_assert_ok!(validate_bytes(s));
        &mut *(s as *mut [u8] as *mut Self)
    }

    /// Creates a `&mut SecfracDigitsStr` from the given mutable string slice.
    ///
    /// This performs assertion in debug build, but not in release build.
    ///
    /// # Safety
    ///
    /// `validate_bytes(s.as_bytes())` should return `Ok(())`.
    #[inline]
    #[must_use]
    unsafe fn from_str_maybe_unchecked_mut(s: &mut str) -> &mut Self {
        // This is safe because `SecfracDigitsStr` ensures that the underlying
        // bytes are ASCII string after modification.
        Self::from_bytes_maybe_unchecked_mut(s.as_bytes_mut())
    }

    /// Creates a new `&SecfracDigitsStr` from a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let secfrac = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// assert!(SecfracDigitsStr::from_str("0").is_ok());
    /// assert!(SecfracDigitsStr::from_str("0000000000").is_ok());
    /// assert!(SecfracDigitsStr::from_str("9999999999").is_ok());
    ///
    /// assert!(SecfracDigitsStr::from_str("").is_err(), "Fractions should not be empty");
    /// assert!(SecfracDigitsStr::from_str(".0").is_err(), "Only digits are allowed");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    // `FromStr` trait cannot be implemented for a slice.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Result<&Self, Error> {
        TryFrom::try_from(s)
    }

    /// Creates a new `&mut SecfracDigitsStr` from a mutable string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "1234".to_owned();
    /// let secfrac = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// secfrac.fill_with_zero();
    /// assert_eq!(secfrac.as_str(), "0000");
    ///
    /// assert_eq!(buf, "0000");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_mut_str(s: &mut str) -> Result<&mut Self, Error> {
        TryFrom::try_from(s)
    }

    /// Creates a new `&SecfracDigitsStr` from a byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let secfrac = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// assert!(SecfracDigitsStr::from_str("0").is_ok());
    /// assert!(SecfracDigitsStr::from_str("0000000000").is_ok());
    /// assert!(SecfracDigitsStr::from_str("9999999999").is_ok());
    ///
    /// assert!(SecfracDigitsStr::from_str("").is_err(), "Fractions should not be empty");
    /// assert!(SecfracDigitsStr::from_str(".0").is_err(), "Only digits are allowed");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_bytes(s: &[u8]) -> Result<&Self, Error> {
        TryFrom::try_from(s)
    }

    /// Creates a new `&mut SecfracDigitsStr` from a mutable byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf: [u8; 4] = *b"1234";
    /// let secfrac = SecfracDigitsStr::from_bytes_mut(&mut buf)?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// secfrac.fill_with_zero();
    /// assert_eq!(secfrac.as_str(), "0000");
    ///
    /// assert_eq!(&buf[..], b"0000");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_bytes_mut(s: &mut [u8]) -> Result<&mut Self, Error> {
        TryFrom::try_from(s)
    }

    /// Returns a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let secfrac = SecfracDigitsStr::from_str("1234")?;
    ///
    /// assert_eq!(secfrac.as_str(), "1234");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        unsafe {
            // This is safe because the `SecfracDigitsStr` ensures that the
            // underlying bytes are ASCII string.
            debug_assert_safe_version_ok!(str::from_utf8(&self.0));
            str::from_utf8_unchecked(&self.0)
        }
    }

    /// Returns a byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let secfrac = SecfracDigitsStr::from_str("1234")?;
    ///
    /// assert_eq!(secfrac.as_str(), "1234");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Retruns a milliseconds value in integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1")?;
    /// assert_eq!(not_precise.milliseconds(), 100);
    ///
    /// let precise = SecfracDigitsStr::from_str("012")?;
    /// assert_eq!(precise.milliseconds(), 12);
    ///
    /// let more_precise = SecfracDigitsStr::from_str("369999")?;
    /// assert_eq!(more_precise.milliseconds(), 369);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn milliseconds(&self) -> u16 {
        let bytes = &self.0;
        match self.len() {
            1 => (bytes[0] - b'0') as u16 * 100,
            2 => (bytes[0] - b'0') as u16 * 100 + (bytes[1] - b'0') as u16 * 10,
            _ => {
                debug_assert!(self.len() >= 3);
                (bytes[0] - b'0') as u16 * 100
                    + (bytes[1] - b'0') as u16 * 10
                    + (bytes[2] - b'0') as u16
            }
        }
    }

    /// Returns a milliseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1")?;
    /// assert_eq!(not_precise.milliseconds_digits(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012")?;
    /// assert_eq!(precise.milliseconds_digits().unwrap(), "012");
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.milliseconds_digits().unwrap(), "012");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn milliseconds_digits(&self) -> Option<&SecfracDigitsStr> {
        self.0.get(MILLI_RANGE).map(|s| unsafe {
            debug_assert_ok!(validate_bytes(s));
            debug_assert_safe_version_ok!(<&Self>::try_from(s));
            // This is safe because `self.0` consists of only ASCII digits,
            // and so is the substring.
            Self::from_bytes_maybe_unchecked(s)
        })
    }

    /// Returns a milliseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "012345678901".to_owned();
    /// let digits = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(digits.as_str(), "012345678901");
    ///
    /// digits.milliseconds_digits_mut().unwrap().fill_with_zero();
    /// assert_eq!(digits.as_str(), "000345678901");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn milliseconds_digits_mut(&mut self) -> Option<&mut SecfracDigitsStr> {
        self.0.get_mut(MILLI_RANGE).map(|s| {
            unsafe {
                // This is safe because `self.0` consists of only ASCII digits,
                // and so is the substring.
                debug_assert_ok!(Self::from_bytes(s));
                Self::from_bytes_maybe_unchecked_mut(s)
            }
        })
    }

    /// Returns a milliseconds digits as a fixed bytes slice, if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1")?;
    /// assert_eq!(not_precise.milliseconds_bytes_fixed_len(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012")?;
    /// assert_eq!(precise.milliseconds_bytes_fixed_len(), Some(b"012"));
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.milliseconds_bytes_fixed_len(), Some(b"012"));
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn milliseconds_bytes_fixed_len(&self) -> Option<&[u8; 3]> {
        self.0.get(MILLI_RANGE).map(|s| {
            debug_assert_eq!(s.len(), 3);
            debug_assert_safe_version_ok!(<&[u8; 3]>::try_from(s));
            let ptr = s.as_ptr() as *const [u8; 3];
            unsafe {
                // This is safe because the string consists of only ASCII digits.
                &*ptr
            }
        })
    }

    /// Retruns a microseconds value in integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1")?;
    /// assert_eq!(not_precise.microseconds(), 100_000);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345")?;
    /// assert_eq!(precise.microseconds(), 012_345);
    ///
    /// let more_precise = SecfracDigitsStr::from_str("123456999")?;
    /// assert_eq!(more_precise.microseconds(), 123_456);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn microseconds(&self) -> u32 {
        let bytes = &self.0;
        let len = bytes.len();
        let len6 = cmp::min(6, len);

        let mut buf: [u8; 8] = [b'0'; 8];
        // Note that the first two digits should be `0`.
        buf[2..(2 + len6)].copy_from_slice(&bytes[..len6]);
        parse_digits8(buf)
    }

    /// Returns a microseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(not_precise.microseconds_digits(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345")?;
    /// assert_eq!(precise.microseconds_digits().unwrap(), "012345");
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.microseconds_digits().unwrap(), "012345");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn microseconds_digits(&self) -> Option<&SecfracDigitsStr> {
        self.0.get(MICRO_RANGE).map(|s| unsafe {
            debug_assert_safe_version_ok!(Self::from_bytes(s));
            // This is safe because `self.0` consists of only ASCII digits,
            // and so is the substring.
            SecfracDigitsStr::from_bytes_maybe_unchecked(s)
        })
    }

    /// Returns a microseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "012345678901".to_owned();
    /// let digits = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(digits.as_str(), "012345678901");
    ///
    /// digits.microseconds_digits_mut().unwrap().fill_with_zero();
    /// assert_eq!(digits.as_str(), "000000678901");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn microseconds_digits_mut(&mut self) -> Option<&mut SecfracDigitsStr> {
        self.0.get_mut(MICRO_RANGE).map(|s| {
            unsafe {
                // This is safe because `self.0` consists of only ASCII digits,
                // and so is the substring.
                debug_assert_ok!(Self::from_bytes(s));
                SecfracDigitsStr::from_bytes_maybe_unchecked_mut(s)
            }
        })
    }

    /// Returns a microseconds digits as a fixed bytes slice, if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(not_precise.microseconds_bytes_fixed_len(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345")?;
    /// assert_eq!(precise.microseconds_bytes_fixed_len(), Some(b"012345"));
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.microseconds_bytes_fixed_len(), Some(b"012345"));
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn microseconds_bytes_fixed_len(&self) -> Option<&[u8; 6]> {
        self.0.get(MICRO_RANGE).map(|s| {
            debug_assert_eq!(s.len(), 6);
            debug_assert_safe_version_ok!(<&[u8; 6]>::try_from(s));
            let ptr = s.as_ptr() as *const [u8; 6];
            unsafe {
                // This is safe because the string consists of only ASCII digits.
                &*ptr
            }
        })
    }

    /// Retruns a nanoseconds value in integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1")?;
    /// assert_eq!(not_precise.nanoseconds(), 100_000_000);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345678")?;
    /// assert_eq!(precise.nanoseconds(), 012_345_678);
    ///
    /// let more_precise = SecfracDigitsStr::from_str("876543210999")?;
    /// assert_eq!(more_precise.nanoseconds(), 876_543_210);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn nanoseconds(&self) -> u32 {
        let bytes = &self.0;
        let len = bytes.len();
        let len8 = cmp::min(8, len);

        let mut buf: [u8; 8] = [b'0'; 8];
        buf[..len8].copy_from_slice(&bytes[..len8]);
        let upper8 = parse_digits8(buf) * 10;
        if len > 8 {
            upper8 + (bytes[8] - b'0') as u32
        } else {
            upper8
        }
    }

    /// Returns a nanoseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(not_precise.nanoseconds_digits(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345678")?;
    /// assert_eq!(precise.nanoseconds_digits().unwrap(), "012345678");
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.nanoseconds_digits().unwrap(), "012345678");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn nanoseconds_digits(&self) -> Option<&SecfracDigitsStr> {
        self.0.get(NANO_RANGE).map(|s| unsafe {
            debug_assert_safe_version_ok!(Self::from_bytes(s));
            // This is safe because `self.0` consists of only ASCII digits,
            // and so is the substring.
            SecfracDigitsStr::from_bytes_maybe_unchecked(s)
        })
    }

    /// Returns a nanoseconds precision substring if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "012345678901".to_owned();
    /// let digits = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(digits.as_str(), "012345678901");
    ///
    /// digits.nanoseconds_digits_mut().unwrap().fill_with_zero();
    /// assert_eq!(digits.as_str(), "000000000901");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn nanoseconds_digits_mut(&mut self) -> Option<&mut SecfracDigitsStr> {
        self.0.get_mut(NANO_RANGE).map(|s| {
            unsafe {
                // This is safe because `self.0` consists of only ASCII digits,
                // and so is the substring.
                debug_assert_ok!(Self::from_bytes(s));
                SecfracDigitsStr::from_bytes_maybe_unchecked_mut(s)
            }
        })
    }

    /// Returns a nanoseconds digits as a fixed bytes slice, if there are enough digits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let not_precise = SecfracDigitsStr::from_str("1234")?;
    /// assert_eq!(not_precise.nanoseconds_bytes_fixed_len(), None);
    ///
    /// let precise = SecfracDigitsStr::from_str("012345678")?;
    /// assert_eq!(precise.nanoseconds_bytes_fixed_len(), Some(b"012345678"));
    ///
    /// let more_precise = SecfracDigitsStr::from_str("012345678901")?;
    /// assert_eq!(more_precise.nanoseconds_bytes_fixed_len(), Some(b"012345678"));
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn nanoseconds_bytes_fixed_len(&self) -> Option<&[u8; 9]> {
        self.0.get(NANO_RANGE).map(|s| {
            debug_assert_eq!(s.len(), 9);
            debug_assert_safe_version_ok!(<&[u8; 9]>::try_from(s));
            let ptr = s.as_ptr() as *const [u8; 9];
            unsafe {
                // This is safe because the string consists of only ASCII digits.
                &*ptr
            }
        })
    }

    /// Fills the secfrac part with zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "1234".to_owned();
    /// let secfrac = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// secfrac.fill_with_zero();
    /// assert_eq!(secfrac.as_str(), "0000");
    ///
    /// assert_eq!(buf, "0000");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn fill_with_zero(&mut self) {
        // Use `slice::fill()` once rust-lang/rust#70758 is stabilized.
        // See <https://github.com/rust-lang/rust/issues/70758>.
        self.0.iter_mut().for_each(|digit| *digit = b'0');
        debug_assert!(
            validate_bytes(&self.0).is_ok(),
            "The secfrac digits string must be valid after the modification"
        );
    }

    /// Fills the secfrac part with zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::SecfracDigitsStr;
    /// let mut buf = "1234".to_owned();
    /// let secfrac = SecfracDigitsStr::from_mut_str(&mut buf)?;
    /// assert_eq!(secfrac.as_str(), "1234");
    ///
    /// secfrac.fill_with_nine();
    /// assert_eq!(secfrac.as_str(), "9999");
    ///
    /// assert_eq!(buf, "9999");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn fill_with_nine(&mut self) {
        // Use `slice::fill()` once rust-lang/rust#70758 is stabilized.
        // See <https://github.com/rust-lang/rust/issues/70758>.
        self.0.iter_mut().for_each(|digit| *digit = b'9');
        debug_assert!(
            validate_bytes(&self.0).is_ok(),
            "The secfrac digits string must be valid after the modification"
        );
    }
}

impl AsRef<[u8]> for SecfracDigitsStr {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl AsRef<str> for SecfracDigitsStr {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<SecfracDigitsStr> for SecfracDigitsStr {
    #[inline]
    fn as_ref(&self) -> &SecfracDigitsStr {
        self
    }
}

impl AsMut<SecfracDigitsStr> for SecfracDigitsStr {
    #[inline]
    fn as_mut(&mut self) -> &mut SecfracDigitsStr {
        self
    }
}

impl<'a> From<&'a SecfracDigitsStr> for &'a str {
    #[inline]
    fn from(v: &'a SecfracDigitsStr) -> Self {
        v.as_str()
    }
}

impl<'a> TryFrom<&'a [u8]> for &'a SecfracDigitsStr {
    type Error = Error;

    #[inline]
    fn try_from(v: &'a [u8]) -> Result<Self, Self::Error> {
        validate_bytes(v)?;
        Ok(unsafe {
            // This is safe because the string is already validated.
            SecfracDigitsStr::from_bytes_maybe_unchecked(v)
        })
    }
}

impl<'a> TryFrom<&'a mut [u8]> for &'a mut SecfracDigitsStr {
    type Error = Error;

    #[inline]
    fn try_from(v: &'a mut [u8]) -> Result<Self, Self::Error> {
        validate_bytes(v)?;
        Ok(unsafe {
            // This is safe because the string is already validated.
            SecfracDigitsStr::from_bytes_maybe_unchecked_mut(v)
        })
    }
}

impl<'a> TryFrom<&'a str> for &'a SecfracDigitsStr {
    type Error = Error;

    #[inline]
    fn try_from(v: &'a str) -> Result<Self, Self::Error> {
        Self::try_from(v.as_bytes())
    }
}

impl<'a> TryFrom<&'a mut str> for &'a mut SecfracDigitsStr {
    type Error = Error;

    #[inline]
    fn try_from(v: &'a mut str) -> Result<Self, Self::Error> {
        validate_bytes(v.as_bytes())?;
        Ok(unsafe {
            // This is safe because the string is already validated and
            // `SecfracDigitsStr` ensures that the underlying bytes are ASCII
            // string after modification.
            SecfracDigitsStr::from_str_maybe_unchecked_mut(v)
        })
    }
}

impl fmt::Display for SecfracDigitsStr {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl ops::Deref for SecfracDigitsStr {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl_cmp_symmetric!(str, SecfracDigitsStr, &SecfracDigitsStr);
impl_cmp_symmetric!([u8], SecfracDigitsStr, [u8]);
impl_cmp_symmetric!([u8], SecfracDigitsStr, &[u8]);
impl_cmp_symmetric!([u8], &SecfracDigitsStr, [u8]);
impl_cmp_symmetric!(str, SecfracDigitsStr, str);
impl_cmp_symmetric!(str, SecfracDigitsStr, &str);
impl_cmp_symmetric!(str, &SecfracDigitsStr, str);

#[cfg(feature = "serde")]
impl serde::Serialize for SecfracDigitsStr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

/// Items for serde support.
#[cfg(feature = "serde")]
mod serde_ {
    use super::*;

    use serde::de::{Deserialize, Deserializer, Visitor};

    /// Visitor for `&SecfracDigitsStr`.
    struct StrVisitor;

    impl<'de> Visitor<'de> for StrVisitor {
        type Value = &'de SecfracDigitsStr;

        #[inline]
        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("digits of fractions of a second")
        }

        #[inline]
        fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Self::Value::try_from(v).map_err(E::custom)
        }

        #[inline]
        fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Self::Value::try_from(v).map_err(E::custom)
        }
    }

    impl<'de> Deserialize<'de> for &'de SecfracDigitsStr {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_any(StrVisitor)
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "serde")]
    use super::*;

    use super::validate_bytes as s_validate;

    #[cfg(feature = "serde")]
    use serde_test::{assert_de_tokens, assert_tokens, Token};

    #[test]
    fn validate_bytes() {
        assert!(s_validate(b"0").is_ok());
        assert!(s_validate(b"9").is_ok());
        assert!(s_validate(b"1234").is_ok());
        assert!(s_validate(b"001200").is_ok());
        assert!(s_validate(b"0000000").is_ok());
        assert!(s_validate(b"9999999").is_ok());
        assert!(s_validate(b"00000000000000000000000000000000").is_ok());
        assert!(s_validate(b"99999999999999999999999999999999").is_ok());

        assert!(s_validate(b"").is_err());
        assert!(s_validate(b".0").is_err());
        assert!(s_validate(b"+0").is_err());
        assert!(s_validate(b"-0").is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn ser_de_str() {
        let raw: &'static str = "1234";
        assert_tokens(
            &SecfracDigitsStr::from_str(raw).unwrap(),
            &[Token::BorrowedStr(raw)],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn de_bytes_slice() {
        let raw: &'static [u8; 4] = b"1234";
        assert_de_tokens(
            &SecfracDigitsStr::from_bytes(raw).unwrap(),
            &[Token::BorrowedBytes(raw)],
        );
    }
}