datetime-string 0.2.2

Datetime string types
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
//! Date string in `%Y-%m-%d` (`YYYY-MM-DD`) format.
//!
//! This is also an RFC 3339 [`full-date`] string.
//!
//! [`full-date`]: https://tools.ietf.org/html/rfc3339#section-5.6

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

use crate::{
    datetime::{is_leap_year, validate_ym0d, validate_ym1d},
    parse::{parse_digits2, parse_digits4},
    str::{write_digit2, write_digit4},
};

#[cfg(feature = "alloc")]
use alloc::{string::String, vec::Vec};

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

/// Length of RFC 3339 `full-date` string (i.e. length of `YYYY-MM-DD`).
const FULL_DATE_LEN: usize = 10;
/// Range of the year in the string.
const YEAR_RANGE: Range<usize> = 0..4;
/// Range of the month in the string.
const MONTH_RANGE: Range<usize> = 5..7;
/// Range of the day of month in the string.
const MDAY_RANGE: Range<usize> = 8..10;

/// Validates the given string as an RFC 3339 [`full-date`] string.
///
/// [`full-date`]: https://tools.ietf.org/html/rfc3339#section-5.6
fn validate_bytes(s: &[u8]) -> Result<(), Error> {
    let s: &[u8; FULL_DATE_LEN] = TryFrom::try_from(s).map_err(|_| {
        if s.len() < FULL_DATE_LEN {
            ErrorKind::TooShort
        } else {
            ErrorKind::TooLong
        }
    })?;

    if (s[4] != b'-') || (s[7] != b'-') {
        return Err(ErrorKind::InvalidSeparator.into());
    }

    let year_s: [u8; 4] = [s[0], s[1], s[2], s[3]];
    let month_s: [u8; 2] = [s[5], s[6]];
    let mday_s: [u8; 2] = [s[8], s[9]];

    if !year_s.iter().all(u8::is_ascii_digit) {
        return Err(ErrorKind::InvalidComponentType(ComponentKind::Year).into());
    }
    if !month_s.iter().all(u8::is_ascii_digit) {
        return Err(ErrorKind::InvalidComponentType(ComponentKind::Month).into());
    }
    if !mday_s.iter().all(u8::is_ascii_digit) {
        return Err(ErrorKind::InvalidComponentType(ComponentKind::Mday).into());
    }

    let month1 = parse_digits2(month_s);
    if !(1..=12).contains(&month1) {
        return Err(ErrorKind::ComponentOutOfRange(ComponentKind::Month).into());
    }
    let mday = parse_digits2(mday_s);
    if mday < 1 {
        return Err(ErrorKind::ComponentOutOfRange(ComponentKind::Mday).into());
    }
    let year = parse_digits4(year_s);

    validate_ym1d(year, month1, mday).map_err(Into::into)
}

/// String slice for a date in `YYYY-MM-DD` format, such as `2001-12-31`.
///
/// This is also an RFC 3339 [`full-date`] string.
///
/// [`full-date`]: https://tools.ietf.org/html/rfc3339#section-5.6
#[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(unknown_lints, clippy::derive_ord_xor_partial_ord)]
pub struct Ymd8HyphenStr([u8]);

impl Ymd8HyphenStr {
    /// Creates a `&Ymd8HyphenStr` 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 Ymd8HyphenStr` 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 Ymd8HyphenStr` 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 `Hms6ColonStr` ensures that the underlying bytes
        // are ASCII string after modification.
        Self::from_bytes_maybe_unchecked_mut(s.as_bytes_mut())
    }

    /// Creates a new `&Ymd8HyphenStr` from a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// assert!(Ymd8HyphenStr::from_str("0000-01-01").is_ok());
    /// assert!(Ymd8HyphenStr::from_str("9999-12-31").is_ok());
    ///
    /// assert!(Ymd8HyphenStr::from_str("2004-02-29").is_ok(), "2004 is a leap year");
    /// assert!(Ymd8HyphenStr::from_str("2100-02-29").is_err(), "2100 is NOT a leap year");
    /// assert!(Ymd8HyphenStr::from_str("2000-02-29").is_ok(), "2000 is a leap year");
    /// # 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 Ymd8HyphenStr` from a mutable string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf = "2001-12-31".to_owned();
    /// let date = Ymd8HyphenStr::from_mut_str(&mut buf)?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// date.set_year(1999)?;
    /// assert_eq!(date.as_str(), "1999-12-31");
    ///
    /// assert_eq!(buf, "1999-12-31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_mut_str(s: &mut str) -> Result<&mut Self, Error> {
        TryFrom::try_from(s)
    }

    /// Creates a new `&Ymd8HyphenStr` from a byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_bytes(b"2001-12-31")?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// assert!(Ymd8HyphenStr::from_bytes(b"0000-01-01").is_ok());
    /// assert!(Ymd8HyphenStr::from_bytes(b"9999-12-31").is_ok());
    ///
    /// assert!(Ymd8HyphenStr::from_bytes(b"2004-02-29").is_ok(), "2004 is a leap year");
    /// assert!(Ymd8HyphenStr::from_bytes(b"2100-02-29").is_err(), "2100 is NOT a leap year");
    /// assert!(Ymd8HyphenStr::from_bytes(b"2000-02-29").is_ok(), "2000 is a leap year");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_bytes(s: &[u8]) -> Result<&Self, Error> {
        TryFrom::try_from(s)
    }

    /// Creates a new `&mut Ymd8HyphenStr` from a mutable byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-12-31";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// date.set_year(1999)?;
    /// assert_eq!(date.as_str(), "1999-12-31");
    ///
    /// assert_eq!(&buf[..], b"1999-12-31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn from_bytes_mut(s: &mut [u8]) -> Result<&mut Self, Error> {
        TryFrom::try_from(s)
    }

    /// Assigns the given value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"1999-12-31";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "1999-12-31");
    ///
    /// let newdate = Ymd8HyphenStr::from_str("2000-01-01")?;
    ///
    /// date.assign(newdate);
    /// assert_eq!(date.as_str(), "2000-01-01");
    /// assert_eq!(buf, *b"2000-01-01");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn assign(&mut self, v: &Self) {
        debug_assert_eq!(self.0.len(), v.0.len());
        self.0.copy_from_slice(&v.0);
    }

    /// Returns a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.as_str(), "2001-12-31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        unsafe {
            // This is safe because the `Ymd8HyphenStr` 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.
    ///
    /// If you want to use indexed access, prefer [`as_bytes_fixed_len`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.as_bytes(), b"2001-12-31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    ///
    /// [`as_bytes_fixed_len`]: #method.as_bytes_fixed_len
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Returns a fixed length byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// let fixed_len: &[u8; 10] = date.as_bytes_fixed_len();
    /// assert_eq!(fixed_len, b"2001-12-31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_bytes_fixed_len(&self) -> &[u8; 10] {
        debug_assert_eq!(
            self.len(),
            FULL_DATE_LEN,
            "Ymd8HyphenStr must always be 10 bytes"
        );

        debug_assert_safe_version_ok!(<&[u8; FULL_DATE_LEN]>::try_from(&self.0));
        let ptr = self.0.as_ptr() as *const [u8; FULL_DATE_LEN];
        // This must be always safe because the length is already checked.
        unsafe { &*ptr }
    }

    /// Returns the year as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.year_str(), "2001");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn year_str(&self) -> &str {
        unsafe {
            // This is safe because the string is ASCII string and `YEAR_RANGE`
            // is always inside the string.
            debug_assert_safe_version_ok!(str::from_utf8(&self.0[YEAR_RANGE]));
            str::from_utf8_unchecked(self.0.get_unchecked(YEAR_RANGE))
        }
    }

    /// Returns the year as a fixed length byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// let year_fixed_len: &[u8; 4] = date.year_bytes_fixed_len();
    /// assert_eq!(year_fixed_len, b"2001");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn year_bytes_fixed_len(&self) -> &[u8; 4] {
        unsafe {
            // This is safe because `YEAR_RANGE` fits inside the string.
            debug_assert_safe_version_ok!(<&[u8; 4]>::try_from(&self.0[YEAR_RANGE]));
            let ptr = self.0.as_ptr().add(YEAR_RANGE.start) as *const [u8; 4];
            &*ptr
        }
    }

    /// Returns the year as a fixed length mutable byte slice.
    ///
    /// # Safety
    ///
    /// The returned slice should have only ASCII digits.
    /// If non-ASCII digits are stored, it may lead to undefined behavior.
    #[inline]
    #[must_use]
    unsafe fn year_bytes_mut_fixed_len(&mut self) -> &mut [u8; 4] {
        // This is safe because `YEAR_RANGE` fits inside the string.
        debug_assert_ok!(<&[u8; 4]>::try_from(&self.0[YEAR_RANGE]));
        let ptr = self.0.as_mut_ptr().add(YEAR_RANGE.start) as *mut [u8; 4];
        &mut *ptr
    }

    /// Returns the year as an integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.year(), 2001);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn year(&self) -> u16 {
        parse_digits4(*self.year_bytes_fixed_len())
    }

    /// Returns the month as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.month_str(), "12");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn month_str(&self) -> &str {
        unsafe {
            // This is safe because the string is ASCII string and `MONTH_RANGE`
            // is always inside the string.
            debug_assert_safe_version_ok!(str::from_utf8(&self.0[MONTH_RANGE]));
            str::from_utf8_unchecked(self.0.get_unchecked(MONTH_RANGE))
        }
    }

    /// Returns the month as a fixed length byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// let month_fixed_len: &[u8; 2] = date.month_bytes_fixed_len();
    /// assert_eq!(month_fixed_len, b"12");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn month_bytes_fixed_len(&self) -> &[u8; 2] {
        unsafe {
            // This is safe because `MONTH_RANGE` fits inside the string.
            debug_assert_safe_version_ok!(<&[u8; 2]>::try_from(&self.0[MONTH_RANGE]));
            let ptr = self.0.as_ptr().add(MONTH_RANGE.start) as *const [u8; 2];
            &*ptr
        }
    }

    /// Returns the month as a fixed length mutable byte slice.
    ///
    /// # Safety
    ///
    /// The returned slice should have only ASCII digits.
    /// If non-ASCII digits are stored, it may lead to undefined behavior.
    #[inline]
    #[must_use]
    unsafe fn month_bytes_mut_fixed_len(&mut self) -> &mut [u8; 2] {
        // This is safe because `MONTH_RANGE` fits inside the string.
        debug_assert_ok!(<&[u8; 2]>::try_from(&self.0[MONTH_RANGE]));
        let ptr = self.0.as_mut_ptr().add(MONTH_RANGE.start) as *mut [u8; 2];
        &mut *ptr
    }

    /// Returns the 1-based month as an integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.month1(), 12);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn month1(&self) -> u8 {
        parse_digits2(*self.month_bytes_fixed_len())
    }

    /// Returns the 0-based month as an integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.month0(), 11);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn month0(&self) -> u8 {
        parse_digits2(*self.month_bytes_fixed_len()).wrapping_sub(1)
    }

    /// Returns the day of month as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.mday_str(), "31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn mday_str(&self) -> &str {
        unsafe {
            // This is safe because the string is ASCII string and `MDAY_RANGE`
            // is always inside the string.
            debug_assert_safe_version_ok!(str::from_utf8(&self.0[MDAY_RANGE]));
            str::from_utf8_unchecked(self.0.get_unchecked(MDAY_RANGE))
        }
    }

    /// Returns the day of month as a fixed length byte slice.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// let mday_fixed_len: &[u8; 2] = date.mday_bytes_fixed_len();
    /// assert_eq!(mday_fixed_len, b"31");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn mday_bytes_fixed_len(&self) -> &[u8; 2] {
        unsafe {
            // This is safe because `MDAY_RANGE` fits inside the string.
            debug_assert_safe_version_ok!(<&[u8; 2]>::try_from(&self.0[MDAY_RANGE]));
            let ptr = self.0.as_ptr().add(MDAY_RANGE.start) as *const [u8; 2];
            &*ptr
        }
    }

    /// Returns the day of month as a fixed length mutable byte slice.
    ///
    /// # Safety
    ///
    /// The returned slice should have only ASCII digits.
    /// If non-ASCII digits are stored, it may lead to undefined behavior.
    #[inline]
    #[must_use]
    unsafe fn mday_bytes_mut_fixed_len(&mut self) -> &mut [u8; 2] {
        // This is safe because `MDAY_RANGE` fits inside the string.
        debug_assert_ok!(<&[u8; 2]>::try_from(&self.0[MDAY_RANGE]));
        let ptr = self.0.as_mut_ptr().add(MDAY_RANGE.start) as *mut [u8; 2];
        &mut *ptr
    }

    /// Returns the day of month as an integer.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("2001-12-31")?;
    ///
    /// assert_eq!(date.mday(), 31);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn mday(&self) -> u8 {
        parse_digits2(*self.mday_bytes_fixed_len())
    }

    /// Sets the given year to the string.
    ///
    /// # Failures
    ///
    /// * Fails if `year` is greater than 9999.
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2000-02-29";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2000-02-29");
    ///
    /// date.set_year(2004)?;
    /// assert_eq!(date.as_str(), "2004-02-29");
    ///
    /// assert!(date.set_year(2001).is_err(), "2001-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_year(&mut self, year: u16) -> Result<(), Error> {
        if year > 9999 {
            return Err(ErrorKind::ComponentOutOfRange(ComponentKind::Year).into());
        }
        validate_ym1d(year, self.month1(), self.mday())?;
        unsafe {
            // This is safe because `write_digit4()` fills the slice with ASCII digits.
            write_digit4(self.year_bytes_mut_fixed_len(), year);
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 0-based month value to the string.
    ///
    /// # Failures
    ///
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-12-31";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// date.set_month0(7)?;
    /// assert_eq!(date.as_str(), "2001-08-31");
    ///
    /// assert!(date.set_month0(8).is_err(), "2001-09-31 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_month0(&mut self, month0: u8) -> Result<(), Error> {
        if month0 >= 12 {
            return Err(ErrorKind::ComponentOutOfRange(ComponentKind::Month).into());
        }
        validate_ym0d(self.year(), month0, self.mday())?;
        unsafe {
            // This is safe because `write_digit2()` fills the slice with ASCII digits.
            write_digit2(self.month_bytes_mut_fixed_len(), month0.wrapping_add(1));
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 1-based month value to the string.
    ///
    /// # Failures
    ///
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-12-31";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// date.set_month1(8)?;
    /// assert_eq!(date.as_str(), "2001-08-31");
    ///
    /// assert!(date.set_month1(9).is_err(), "2001-09-31 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn set_month1(&mut self, month1: u8) -> Result<(), Error> {
        self.set_month0(month1.wrapping_sub(1))
    }

    /// Sets the given day of month value to the string.
    ///
    /// # Failures
    ///
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-02-28";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-02-28");
    ///
    /// date.set_mday(3)?;
    /// assert_eq!(date.as_str(), "2001-02-03");
    ///
    /// assert!(date.set_mday(29).is_err(), "2001-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_mday(&mut self, mday: u8) -> Result<(), Error> {
        validate_ym1d(self.year(), self.month1(), mday)?;
        unsafe {
            // This is safe because `write_digit2()` fills the slice with ASCII digits.
            write_digit2(self.mday_bytes_mut_fixed_len(), mday);
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 0-based month and 1-based day of month values to the string.
    ///
    /// # Failures
    ///
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-02-28";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-02-28");
    ///
    /// date.set_month0_mday(3, 23)?;
    /// assert_eq!(date.as_str(), "2001-04-23");
    ///
    /// assert!(date.set_month0_mday(1, 29).is_err(), "2001-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_month0_mday(&mut self, month0: u8, mday: u8) -> Result<(), Error> {
        validate_ym0d(self.year(), month0, mday)?;
        unsafe {
            // This is safe because `write_digit2()` fills the slices with ASCII digits.
            write_digit2(self.month_bytes_mut_fixed_len(), month0.wrapping_add(1));
            write_digit2(self.mday_bytes_mut_fixed_len(), mday);
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 1-based month and day of month values to the string.
    ///
    /// # Failures
    ///
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-02-28";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-02-28");
    ///
    /// date.set_month1_mday(4, 23)?;
    /// assert_eq!(date.as_str(), "2001-04-23");
    ///
    /// assert!(date.set_month1_mday(2, 29).is_err(), "2001-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_month1_mday(&mut self, month1: u8, mday: u8) -> Result<(), Error> {
        validate_ym1d(self.year(), month1, mday)?;
        unsafe {
            // This is safe because `write_digit2()` fills the slices with ASCII digits.
            write_digit2(self.month_bytes_mut_fixed_len(), month1);
            write_digit2(self.mday_bytes_mut_fixed_len(), mday);
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 1-based year, 0-based month, and 1-based day of month values to the string.
    ///
    /// # Failures
    ///
    /// * Fails if `year` is greater than 9999.
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-02-28";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-02-28");
    ///
    /// date.set_ym0d(1999, 3, 23)?;
    /// assert_eq!(date.as_str(), "1999-04-23");
    ///
    /// assert!(date.set_ym0d(1999, 1, 29).is_err(), "1999-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn set_ym0d(&mut self, year: u16, month0: u8, mday: u8) -> Result<(), Error> {
        validate_ym0d(year, month0, mday)?;
        unsafe {
            // This is safe because `write_digit2()` and `write_digit4()` fill
            // the slices with ASCII digits.
            write_digit4(self.year_bytes_mut_fixed_len(), year);
            write_digit2(self.month_bytes_mut_fixed_len(), month0.wrapping_add(1));
            write_digit2(self.mday_bytes_mut_fixed_len(), mday);
        }

        debug_assert_ok!(validate_bytes(&self.0));
        debug_assert_ok!(
            validate_ym1d(self.year(), self.month1(), self.mday()),
            "Date should be valid after modification"
        );
        Ok(())
    }

    /// Sets the given 1-based year, month, and day of month values to the string.
    ///
    /// # Failures
    ///
    /// * Fails if `year` is greater than 9999.
    /// * Fails if the datetime after modification is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let mut buf: [u8; 10] = *b"2001-02-28";
    /// let date = Ymd8HyphenStr::from_bytes_mut(&mut buf[..])?;
    /// assert_eq!(date.as_str(), "2001-02-28");
    ///
    /// date.set_ym1d(1999, 4, 23)?;
    /// assert_eq!(date.as_str(), "1999-04-23");
    ///
    /// assert!(date.set_ym1d(1999, 2, 29).is_err(), "1999-02-29 is invalid");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn set_ym1d(&mut self, year: u16, month1: u8, mday: u8) -> Result<(), Error> {
        self.set_ym0d(year, month1.wrapping_sub(1), mday)
    }

    /// Returns the 0-based day of the year, i.e. days since January 1 of the year.
    ///
    /// Note that this value is 0-based.
    /// January 1 is 0 days since January 1 of the year.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("1970-01-01")?;
    /// assert_eq!(date.yday0(), 0, "0 for the 1st day of the year, because this is 0-based value");
    ///
    /// let date2 = Ymd8HyphenStr::from_str("1970-12-31")?;
    /// assert_eq!(date2.yday0(), 364);
    ///
    /// let leap_last = Ymd8HyphenStr::from_str("2000-12-31")?;
    /// assert_eq!(leap_last.yday0(), 365, "2000-02-29 exists");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    pub fn yday0(&self) -> u16 {
        self.yday1() - 1
    }

    /// Returns the 1-based day of the year.
    ///
    /// Note that this value is 1-based.
    /// January 1 is 1st day of the year.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("1970-01-01")?;
    /// assert_eq!(date.yday1(), 1, "1 for the 1st day of the year, because this is 1-based value");
    ///
    /// let date2 = Ymd8HyphenStr::from_str("1970-12-31")?;
    /// assert_eq!(date2.yday1(), 365);
    ///
    /// let leap_last = Ymd8HyphenStr::from_str("2000-12-31")?;
    /// assert_eq!(leap_last.yday1(), 366, "2000-02-29 exists");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn yday1(&self) -> u16 {
        /// `yday`s of 0th day for each months of non-leap year.
        const BASE_YDAYS: [u16; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];

        let month0 = self.month0();
        let non_leap_yday = BASE_YDAYS[usize::from(month0)] + u16::from(self.mday());

        if month0 > 1 && is_leap_year(self.year()) {
            non_leap_yday + 1
        } else {
            non_leap_yday
        }
    }

    /// Returns the days from the epoch (1970-01-01).
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenStr;
    /// let date = Ymd8HyphenStr::from_str("1971-01-01")?;
    /// assert_eq!(date.days_since_epoch(), 365);
    ///
    /// let date2 = Ymd8HyphenStr::from_str("1969-01-01")?;
    /// assert_eq!(date2.days_since_epoch(), -365);
    ///
    /// let epoch = Ymd8HyphenStr::from_str("1970-01-01")?;
    /// assert_eq!(epoch.days_since_epoch(), 0);
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn days_since_epoch(&self) -> i32 {
        let tm_year = i32::from(self.year()) - 1900;

        // See "4.16. Seconds Since the Epoch" section of POSIX
        // (<https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16>).
        //
        // > If the year is \<1970 or the value is negative, the relationship is
        // > undefined. If the year is >=1970 and the value is non-negative, the
        // > value is related to a Coordinated Universal Time name according to
        // > the C-language expression, where `tm_sec`, `tm_min`, `tm_hour`,
        // > `tm_yday`, and `tm_year` are all integer types:
        // >
        // > ```
        // > tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
        // >     (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
        // >     ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
        // > ```
        (i32::from(self.yday1()) - 1) + (tm_year - 70) * 365 + (tm_year - 69) / 4
            - (tm_year - 1) / 100
            + (tm_year + 299) / 400
    }

    /// Returns `Month` value for `time` crate v0.3.
    #[cfg(feature = "time03")]
    #[cfg_attr(docsrs, doc(cfg(feature = "time03")))]
    #[inline]
    #[must_use]
    fn time03_month(&self) -> time03::Month {
        unsafe {
            // SAFETY: `month1()` returns the value in `1..=12`, and
            // `time03::Month` is `#[repr(u8)]` and the value is also in `1..=12`.
            debug_assert!(
                ((time03::Month::January as u8)..=(time03::Month::December as u8))
                    .contains(&self.month1())
            );
            core::mem::transmute::<u8, time03::Month>(self.month1())
        }
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl alloc::borrow::ToOwned for Ymd8HyphenStr {
    type Owned = Ymd8HyphenString;

    #[inline]
    fn to_owned(&self) -> Self::Owned {
        self.into()
    }
}

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

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

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

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

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

#[cfg(feature = "chrono04")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono04")))]
impl From<&Ymd8HyphenStr> for chrono04::NaiveDate {
    fn from(v: &Ymd8HyphenStr) -> Self {
        let year = i32::from(v.year());
        let month1 = u32::from(v.month1());
        let mday = u32::from(v.mday());

        Self::from_ymd(year, month1, mday)
    }
}

#[cfg(feature = "time03")]
#[cfg_attr(docsrs, doc(cfg(feature = "time03")))]
impl From<&Ymd8HyphenStr> for time03::Date {
    fn from(v: &Ymd8HyphenStr) -> Self {
        let year = i32::from(v.year());
        let month = v.time03_month();
        let mday = v.mday();

        Self::from_calendar_date(year, month, mday).expect("[validity] the date must be valid")
    }
}

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

    #[inline]
    fn try_from(v: &'a [u8]) -> Result<Self, Self::Error> {
        validate_bytes(v)?;
        Ok(unsafe {
            // This is safe because a valid RFC 3339 `full-date` string is also an ASCII string.
            Ymd8HyphenStr::from_bytes_maybe_unchecked(v)
        })
    }
}

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

    #[inline]
    fn try_from(v: &'a mut [u8]) -> Result<Self, Self::Error> {
        validate_bytes(v)?;
        Ok(unsafe {
            // This is safe because a valid RFC 3339 `full-date` string is also an ASCII string.
            Ymd8HyphenStr::from_bytes_maybe_unchecked_mut(v)
        })
    }
}

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

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

impl<'a> TryFrom<&'a mut str> for &'a mut Ymd8HyphenStr {
    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 value is successfully validated, and
            // `Ymd8HyphenStr` ensures the value after modification is an ASCII string.
            Ymd8HyphenStr::from_str_maybe_unchecked_mut(v)
        })
    }
}

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

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

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

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

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

/// Owned string for a date in `YYYY-MM-DD` format, such as `2001-12-31`.
///
/// This is also an RFC 3339 [`full-date`] string.
///
/// This is a fixed length string, and implements [`Copy`] trait.
///
/// To create a value of this type, use [`str::parse`] method or
/// [`std::convert::TryFrom`] trait, or convert from `&Ymd8HyphenStr`.
///
/// # Examples
///
/// ```
/// # use datetime_string::common::Ymd8HyphenString;
/// use datetime_string::common::Ymd8HyphenStr;
/// use std::convert::TryFrom;
///
/// let try_from = Ymd8HyphenString::try_from("2001-12-31")?;
///
/// let parse = "2001-12-31".parse::<Ymd8HyphenString>()?;
/// let parse2: Ymd8HyphenString = "2001-12-31".parse()?;
///
/// let to_owned = Ymd8HyphenStr::from_str("2001-12-31")?.to_owned();
/// let into: Ymd8HyphenString = Ymd8HyphenStr::from_str("2001-12-31")?.into();
/// # Ok::<_, datetime_string::Error>(())
/// ```
///
/// [`full-date`]: https://tools.ietf.org/html/rfc3339#section-5.6
// Note that `derive(Serialize)` cannot used here, because it encodes this as
// `[u8; 10]` rather than as a string.
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
// 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(unknown_lints, clippy::derive_ord_xor_partial_ord)]
pub struct Ymd8HyphenString([u8; FULL_DATE_LEN]);

impl Ymd8HyphenString {
    /// Creates a `Ymd8HyphenString` from the given bytes.
    ///
    /// # Safety
    ///
    /// `validate_bytes(&s)` should return `Ok(())`.
    #[inline]
    #[must_use]
    unsafe fn new_maybe_unchecked(s: [u8; 10]) -> Self {
        debug_assert_ok!(validate_bytes(&s));
        Self(s)
    }

    /// Returns the minimum date.
    #[inline]
    #[must_use]
    fn min() -> Self {
        unsafe {
            // This is safe because `0000-01-01` is valid.
            debug_assert_safe_version_ok!(Self::try_from(*b"0000-01-01"));
            Self::new_maybe_unchecked(*b"0000-01-01")
        }
    }

    /// Creates a new `Ymd8HyphenString` from the given date.
    ///
    /// Note that `month0` is 0-based, i.e. January is 0, February is 1, and so on.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenString;
    /// let date = Ymd8HyphenString::from_ym0d(2001, 11, 31)?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// assert!(Ymd8HyphenString::from_ym0d(2001, 1, 29).is_err(), "2001-02-29 is invaild date");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn from_ym0d(year: u16, month0: u8, mday: u8) -> Result<Self, Error> {
        let mut v = Self::min();
        v.set_ym0d(year, month0, mday)?;
        Ok(v)
    }

    /// Creates a new `Ymd8HyphenString` from the given date.
    ///
    /// Note that `month1` is 1-based, i.e. January is 1, February is 2, and so on.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenString;
    /// let date = Ymd8HyphenString::from_ym1d(2001, 12, 31)?;
    /// assert_eq!(date.as_str(), "2001-12-31");
    ///
    /// assert!(Ymd8HyphenString::from_ym1d(2001, 2, 29).is_err(), "2001-02-29 is invaild date");
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    pub fn from_ym1d(year: u16, month1: u8, mday: u8) -> Result<Self, Error> {
        let mut v = Self::min();
        v.set_ym1d(year, month1, mday)?;
        Ok(v)
    }

    /// Returns a `&Ymd8HyphenStr` for the string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenString;
    /// use datetime_string::common::Ymd8HyphenStr;
    ///
    /// let date = "2001-12-31".parse::<Ymd8HyphenString>()?;
    ///
    /// // Usually you don't need to call `as_deref()` explicitly, because
    /// // `Deref<Target = Ymd8HyphenStr>` trait is implemented.
    /// let _: &Ymd8HyphenStr = date.as_deref();
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_deref(&self) -> &Ymd8HyphenStr {
        unsafe {
            // This is safe because `self.0` is valid RFC 3339 `full-date` string.
            debug_assert_ok!(Ymd8HyphenStr::from_bytes(&self.0));
            Ymd8HyphenStr::from_bytes_maybe_unchecked(&self.0)
        }
    }

    /// Returns a `&mut Ymd8HyphenStr` for the string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use datetime_string::common::Ymd8HyphenString;
    /// use datetime_string::common::Ymd8HyphenStr;
    ///
    /// let mut date = "2001-12-31".parse::<Ymd8HyphenString>()?;
    ///
    /// // Usually you don't need to call `as_deref_mut()` explicitly, because
    /// // `DerefMut` trait is implemented.
    /// let _: &mut Ymd8HyphenStr = date.as_deref_mut();
    /// # Ok::<_, datetime_string::Error>(())
    /// ```
    #[inline]
    #[must_use]
    pub fn as_deref_mut(&mut self) -> &mut Ymd8HyphenStr {
        unsafe {
            // This is safe because `self.0` is valid RFC 3339 `full-date` string.
            debug_assert_ok!(Ymd8HyphenStr::from_bytes(&self.0));
            Ymd8HyphenStr::from_bytes_maybe_unchecked_mut(&mut self.0)
        }
    }
}

impl core::borrow::Borrow<Ymd8HyphenStr> for Ymd8HyphenString {
    #[inline]
    fn borrow(&self) -> &Ymd8HyphenStr {
        self.as_deref()
    }
}

impl core::borrow::BorrowMut<Ymd8HyphenStr> for Ymd8HyphenString {
    #[inline]
    fn borrow_mut(&mut self) -> &mut Ymd8HyphenStr {
        self.as_deref_mut()
    }
}

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

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

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

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

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<Ymd8HyphenString> for Vec<u8> {
    #[inline]
    fn from(v: Ymd8HyphenString) -> Vec<u8> {
        (*v.as_bytes_fixed_len()).into()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<Ymd8HyphenString> for String {
    #[inline]
    fn from(v: Ymd8HyphenString) -> String {
        let vec: Vec<u8> = (*v.as_bytes_fixed_len()).into();
        unsafe {
            // This is safe because a valid RFC 3339 `full-date` string is also an ASCII string.
            String::from_utf8_unchecked(vec)
        }
    }
}

impl From<&Ymd8HyphenStr> for Ymd8HyphenString {
    fn from(v: &Ymd8HyphenStr) -> Self {
        unsafe {
            // This is safe because the value is already validated.
            Self::new_maybe_unchecked(*v.as_bytes_fixed_len())
        }
    }
}

#[cfg(feature = "chrono04")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono04")))]
impl TryFrom<&chrono04::NaiveDate> for Ymd8HyphenString {
    type Error = Error;

    /// Converts the given date into `Ymd8HyphenString`.
    ///
    /// # Failures
    ///
    /// Fails if the year is less than 0 or greater than 9999.
    fn try_from(v: &chrono04::NaiveDate) -> Result<Self, Self::Error> {
        use chrono04::Datelike;

        let year = v.year();
        if (0..=9999).contains(&year) {
            return Err(ErrorKind::ComponentOutOfRange(ComponentKind::Year).into());
        }
        Ok(
            Self::from_ym1d(v.year() as u16, v.month() as u8, v.day() as u8)
                .expect("`chrono04::NaiveTime` must always have a valid date"),
        )
    }
}

impl TryFrom<&[u8]> for Ymd8HyphenString {
    type Error = Error;

    #[inline]
    fn try_from(v: &[u8]) -> Result<Self, Self::Error> {
        Ymd8HyphenStr::from_bytes(v).map(Into::into)
    }
}

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

    #[inline]
    fn try_from(v: &str) -> Result<Self, Self::Error> {
        Ymd8HyphenStr::from_str(v).map(Into::into)
    }
}

impl TryFrom<[u8; 10]> for Ymd8HyphenString {
    type Error = Error;

    #[inline]
    fn try_from(v: [u8; 10]) -> Result<Self, Self::Error> {
        validate_bytes(&v)?;
        Ok(unsafe {
            // This is safe because the value is successfully validated.
            Self::new_maybe_unchecked(v)
        })
    }
}

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

impl ops::Deref for Ymd8HyphenString {
    type Target = Ymd8HyphenStr;

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

impl ops::DerefMut for Ymd8HyphenString {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_deref_mut()
    }
}

impl str::FromStr for Ymd8HyphenString {
    type Err = Error;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl_cmp_symmetric!(Ymd8HyphenStr, Ymd8HyphenString, &Ymd8HyphenString);
impl_cmp_symmetric!(Ymd8HyphenStr, Ymd8HyphenString, Ymd8HyphenStr);
impl_cmp_symmetric!(Ymd8HyphenStr, Ymd8HyphenString, &Ymd8HyphenStr);
impl_cmp_symmetric!(str, Ymd8HyphenString, str);
impl_cmp_symmetric!(str, Ymd8HyphenString, &str);
impl_cmp_symmetric!(str, &Ymd8HyphenString, str);
impl_cmp_symmetric!([u8], Ymd8HyphenString, [u8]);
impl_cmp_symmetric!([u8], Ymd8HyphenString, &[u8]);
impl_cmp_symmetric!([u8], &Ymd8HyphenString, [u8]);

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl serde::Serialize for Ymd8HyphenString {
    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 `&Ymd8HyphenStr`.
    struct StrVisitor;

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

        #[inline]
        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("YYYY-MM-DD date string")
        }

        #[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 Ymd8HyphenStr {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_any(StrVisitor)
        }
    }

    /// Visitor for `Ymd8HyphenString`.
    struct StringVisitor;

    impl<'de> Visitor<'de> for StringVisitor {
        type Value = Ymd8HyphenString;

        #[inline]
        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("YYYY-MM-DD date string")
        }

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

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

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

#[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"0000-01-01").is_ok());
        assert!(s_validate(b"9999-12-31").is_ok());

        assert!(s_validate(b"2001-01-01").is_ok());
        assert!(s_validate(b"2001-01-31").is_ok());
        assert!(s_validate(b"2001-03-31").is_ok());
        assert!(s_validate(b"2001-04-30").is_ok());
        assert!(s_validate(b"2001-05-31").is_ok());
        assert!(s_validate(b"2001-06-30").is_ok());
        assert!(s_validate(b"2001-07-31").is_ok());
        assert!(s_validate(b"2001-08-31").is_ok());
        assert!(s_validate(b"2001-09-30").is_ok());
        assert!(s_validate(b"2001-10-31").is_ok());
        assert!(s_validate(b"2001-11-30").is_ok());
        assert!(s_validate(b"2001-12-31").is_ok());

        assert!(s_validate(b"2001-00-01").is_err());
        assert!(s_validate(b"2001-13-01").is_err());
        assert!(s_validate(b"2001-01-00").is_err());
        assert!(s_validate(b"2001-01-32").is_err());
        assert!(s_validate(b"2001-03-32").is_err());
        assert!(s_validate(b"2001-04-31").is_err());
        assert!(s_validate(b"2001-05-32").is_err());
        assert!(s_validate(b"2001-06-31").is_err());
        assert!(s_validate(b"2001-07-32").is_err());
        assert!(s_validate(b"2001-08-32").is_err());
        assert!(s_validate(b"2001-09-31").is_err());
        assert!(s_validate(b"2001-10-32").is_err());
        assert!(s_validate(b"2001-11-31").is_err());
        assert!(s_validate(b"2001-12-32").is_err());

        // 2001 is not a leap year.
        assert!(s_validate(b"2001-02-28").is_ok());
        assert!(s_validate(b"2001-02-29").is_err());
        // 2000 is a leap year.
        assert!(s_validate(b"2000-02-28").is_ok());
        assert!(s_validate(b"2000-02-29").is_ok());
        assert!(s_validate(b"2000-02-30").is_err());
        // 2004 is a leap year.
        assert!(s_validate(b"2004-02-28").is_ok());
        assert!(s_validate(b"2004-02-29").is_ok());
        assert!(s_validate(b"2004-02-30").is_err());
        // 2100 is not a leap year.
        assert!(s_validate(b"2100-02-28").is_ok());
        assert!(s_validate(b"2100-02-29").is_err());

        assert!(s_validate(b"2001+01-01").is_err());
        assert!(s_validate(b"2001-01+01").is_err());
        assert!(s_validate(b"01-01-01").is_err());
        assert!(s_validate(b"+001-01-01").is_err());
        assert!(s_validate(b"-001-01-01").is_err());
    }

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

    #[cfg(feature = "serde")]
    #[test]
    fn ser_de_string() {
        let raw: &'static str = "2001-12-31";
        assert_tokens(
            &Ymd8HyphenString::try_from(raw).unwrap(),
            &[Token::Str(raw)],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn de_bytes_slice() {
        let raw: &'static [u8; 10] = b"2001-12-31";
        assert_de_tokens(
            &Ymd8HyphenStr::from_bytes(raw).unwrap(),
            &[Token::BorrowedBytes(raw)],
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn de_bytes() {
        let raw: &'static [u8; 10] = b"2001-12-31";
        assert_de_tokens(
            &Ymd8HyphenString::try_from(&raw[..]).unwrap(),
            &[Token::Bytes(raw)],
        );
    }
}