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
//! Resource Records.
//!
//! This module defines types and traits related to DNS resource records. The
//! most complete type is [`Record`] which contains a complete record for a
//! certain record type. [`RecordHeader`] contains the data from a record’s
//! header, the first couple of octets common to all records. Finally,
//! [`ParsedRecord`] is similar to [`Record`] but contains the record data
//! in its raw, encoded form.
//!
//! The [`AsRecord`] trait is used by the message builder to consider
//! different representations of records.
//!
//! [`AsRecord`]: trait.AsRecord.html
//! [`Record`]: struct.Record.html
//! [`RecordHeader`]: struct.RecordHeader.html
//! [`ParsedRecord`]: struct.ParsedRecord.html

use super::cmp::CanonicalOrd;
use super::iana::{Class, Rtype};
use super::name::{FlattenInto, ParsedDname, ToDname};
use super::rdata::{ComposeRecordData, ParseRecordData, RecordData};
use super::wire::{Compose, Composer, FormError, Parse, ParseError};
use core::cmp::Ordering;
use core::time::Duration;
use core::{fmt, hash};
use octseq::builder::ShortBuf;
use octseq::octets::{Octets, OctetsFrom};
use octseq::parse::Parser;
use octseq::OctetsBuilder;

//------------ Record --------------------------------------------------------

/// A DNS resource record.
///
/// All information available through the DNS is stored in resource records.
/// They have a three part key of a domain name, resource record type, and
/// class. Data is arranged in a tree which is navigated using the domain
/// name. Each node in the tree carries a label, starting with the root
/// label as the top-most node. The tree is traversed by stepping through the
/// name from right to left, finding a child node carring the label of each
/// step. The domain name resulting from this traversal is part of the
/// record itself. It is called the *owner* of the record.
///
/// The record type describes the kind of data the record holds, such as IP
/// addresses. The class, finally, describes which sort of network the
/// information is for. The DNS was originally intended to be used for
/// networks other than the Internet as well. In practice, the only relevant
/// class is IN, the Internet. Note that each class has its own tree of nodes.
///
/// The payload of a resource record is its data. Its purpose, meaning, and
/// format is determined by the record type (technically, also its class).
/// For each unique three-part key there can be multiple resource records.
/// All these records for the same key are called *resource record sets,*
/// most often shortened to ‘RRset.’
///
/// There is one more piece of data: the TTL or time to live. This value
/// says how long a record remains valid before it should be refreshed from
/// its original source. The TTL is used to add caching
/// facilities to the DNS.
///
/// Values of the `Record` type represent one single resource record. Since
/// there are currently more than eighty record types—see [`Rtype`] for a
/// complete list—, the type is generic over a trait for record data. This
/// trait holds both the record type value and the record data as they are
/// inseparably entwined.
///
/// Because a record’s owner is a domain name, the `Record` type is
/// additionally generic over the domain name type is for it.
///
/// There is three ways to create a record value. First, you can make one
/// yourself using the [`new`] function. It will neatly take care of all
/// the generics through type inference. Secondly, you can parse a record
/// from an existing message. [`Message`] and its friends provide a way to
/// do that; see there for all the details. Finally, you can scan a record
/// from zone file format. See the crate’s
#[cfg_attr(feature = "zonefile", doc = "[zonefile][crate::zonefile]")]
#[cfg_attr(not(feature = "zonefile"), doc = "zonefile")]
/// module for that.
///
/// [`new`]: #method.new
/// [`Message`]: ../message/struct.Message.html
/// [`MessageBuilder`]: ../message_builder/struct.MessageBuilder.html
/// [`Rtype`]: ../../iana/enum.Rtype.html
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Record<Name, Data> {
    /// The owner of the record.
    owner: Name,

    /// The class of the record.
    class: Class,

    /// The time-to-live value of the record.
    ttl: Ttl,

    /// The record data. The value also specifies the record’s type.
    data: Data,
}

/// # Creation and Element Access
///
impl<Name, Data> Record<Name, Data> {
    /// Creates a new record from its parts.
    pub fn new(owner: Name, class: Class, ttl: Ttl, data: Data) -> Self {
        Record {
            owner,
            class,
            ttl,
            data,
        }
    }

    /// Creates a new record from a compatible record.
    ///
    /// This function only exists because the equivalent `From` implementation
    /// is currently not possible,
    pub fn from_record<NN, DD>(record: Record<NN, DD>) -> Self
    where
        Name: From<NN>,
        Data: From<DD>,
    {
        Self::new(
            record.owner.into(),
            record.class,
            record.ttl,
            record.data.into(),
        )
    }

    /// Returns a reference to the owner domain name.
    ///
    /// The owner of a record is the domain name that specifies the node in
    /// the DNS tree this record belongs to.
    pub fn owner(&self) -> &Name {
        &self.owner
    }

    /// Returns the record type.
    pub fn rtype(&self) -> Rtype
    where
        Data: RecordData,
    {
        self.data.rtype()
    }

    /// Returns the record class.
    pub fn class(&self) -> Class {
        self.class
    }

    /// Sets the record’s class.
    pub fn set_class(&mut self, class: Class) {
        self.class = class
    }

    /// Returns the record’s time-to-live.
    pub fn ttl(&self) -> Ttl {
        self.ttl
    }

    /// Sets the record’s time-to-live.
    pub fn set_ttl(&mut self, ttl: Ttl) {
        self.ttl = ttl
    }

    /// Return a reference to the record data.
    pub fn data(&self) -> &Data {
        &self.data
    }

    /// Returns a mutable reference to the record data.
    pub fn data_mut(&mut self) -> &mut Data {
        &mut self.data
    }

    /// Trades the record for its record data.
    pub fn into_data(self) -> Data {
        self.data
    }

    /// Trades the record for its owner name and data.
    pub fn into_owner_and_data(self) -> (Name, Data) {
        (self.owner, self.data)
    }
}

/// Parsing and Composing
///
impl<Octs, Data> Record<ParsedDname<Octs>, Data> {
    pub fn parse<'a, Src: Octets<Range<'a> = Octs> + 'a>(
        parser: &mut Parser<'a, Src>,
    ) -> Result<Option<Self>, ParseError>
    where
        Data: ParseRecordData<'a, Src>,
    {
        let header = RecordHeader::parse(parser)?;
        header.parse_into_record(parser)
    }
}

impl<N: ToDname, D: RecordData + ComposeRecordData> Record<N, D> {
    pub fn compose<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        target.append_compressed_dname(&self.owner)?;
        self.data.rtype().compose(target)?;
        self.class.compose(target)?;
        self.ttl.compose(target)?;
        self.data.compose_len_rdata(target)
    }

    pub fn compose_canonical<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        self.owner.compose_canonical(target)?;
        self.data.rtype().compose(target)?;
        self.class.compose(target)?;
        self.ttl.compose(target)?;
        self.data.compose_canonical_len_rdata(target)
    }
}

//--- From

impl<N, D> From<(N, Class, u32, D)> for Record<N, D> {
    fn from((owner, class, ttl, data): (N, Class, u32, D)) -> Self {
        Self::new(owner, class, Ttl::from_secs(ttl), data)
    }
}

impl<N, D> From<(N, Class, Ttl, D)> for Record<N, D> {
    fn from((owner, class, ttl, data): (N, Class, Ttl, D)) -> Self {
        Self::new(owner, class, ttl, data)
    }
}

impl<N, D> From<(N, u32, D)> for Record<N, D> {
    fn from((owner, ttl, data): (N, u32, D)) -> Self {
        Self::new(owner, Class::In, Ttl::from_secs(ttl), data)
    }
}

//--- OctetsFrom and FlattenInto
//
// XXX We don’t have blanket FromOctets for a type T into itself, so this may
//     not always work as expected. Not sure what we can do about it?

impl<Name, Data, SrcName, SrcData> OctetsFrom<Record<SrcName, SrcData>>
    for Record<Name, Data>
where
    Name: OctetsFrom<SrcName>,
    Data: OctetsFrom<SrcData>,
    Data::Error: From<Name::Error>,
{
    type Error = Data::Error;

    fn try_octets_from(
        source: Record<SrcName, SrcData>,
    ) -> Result<Self, Self::Error> {
        Ok(Record {
            owner: Name::try_octets_from(source.owner)?,
            class: source.class,
            ttl: source.ttl,
            data: Data::try_octets_from(source.data)?,
        })
    }
}

impl<Name, TName, Data, TData> FlattenInto<Record<TName, TData>>
    for Record<Name, Data>
where
    Name: FlattenInto<TName>,
    Data: FlattenInto<TData, AppendError = Name::AppendError>,
{
    type AppendError = Name::AppendError;

    fn try_flatten_into(
        self,
    ) -> Result<Record<TName, TData>, Name::AppendError> {
        Ok(Record::new(
            self.owner.try_flatten_into()?,
            self.class,
            self.ttl,
            self.data.try_flatten_into()?,
        ))
    }
}

//--- PartialEq and Eq

impl<N, NN, D, DD> PartialEq<Record<NN, DD>> for Record<N, D>
where
    N: PartialEq<NN>,
    D: RecordData + PartialEq<DD>,
    DD: RecordData,
{
    fn eq(&self, other: &Record<NN, DD>) -> bool {
        self.owner == other.owner
            && self.class == other.class
            && self.data == other.data
    }
}

impl<N: Eq, D: RecordData + Eq> Eq for Record<N, D> {}

//--- PartialOrd, Ord, and CanonicalOrd

impl<N, NN, D, DD> PartialOrd<Record<NN, DD>> for Record<N, D>
where
    N: PartialOrd<NN>,
    D: RecordData + PartialOrd<DD>,
    DD: RecordData,
{
    fn partial_cmp(&self, other: &Record<NN, DD>) -> Option<Ordering> {
        match self.owner.partial_cmp(&other.owner) {
            Some(Ordering::Equal) => {}
            res => return res,
        }
        match self.class.partial_cmp(&other.class) {
            Some(Ordering::Equal) => {}
            res => return res,
        }
        self.data.partial_cmp(&other.data)
    }
}

impl<N, D> Ord for Record<N, D>
where
    N: Ord,
    D: RecordData + Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        match self.owner.cmp(&other.owner) {
            Ordering::Equal => {}
            res => return res,
        }
        match self.class.cmp(&other.class) {
            Ordering::Equal => {}
            res => return res,
        }
        self.data.cmp(&other.data)
    }
}

impl<N, NN, D, DD> CanonicalOrd<Record<NN, DD>> for Record<N, D>
where
    N: ToDname,
    NN: ToDname,
    D: RecordData + CanonicalOrd<DD>,
    DD: RecordData,
{
    fn canonical_cmp(&self, other: &Record<NN, DD>) -> Ordering {
        // This sort order will keep all records of a zone together. Ie.,
        // all the records with the same zone and ending in a given name
        // form one sequence.
        match self.class.cmp(&other.class) {
            Ordering::Equal => {}
            res => return res,
        }
        match self.owner.name_cmp(&other.owner) {
            Ordering::Equal => {}
            res => return res,
        }
        match self.rtype().cmp(&other.rtype()) {
            Ordering::Equal => {}
            res => return res,
        }
        self.data.canonical_cmp(&other.data)
    }
}

//--- Hash

impl<Name, Data> hash::Hash for Record<Name, Data>
where
    Name: hash::Hash,
    Data: hash::Hash,
{
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.owner.hash(state);
        self.class.hash(state);
        self.ttl.hash(state);
        self.data.hash(state);
    }
}

//--- Display and Debug

impl<Name, Data> fmt::Display for Record<Name, Data>
where
    Name: fmt::Display,
    Data: RecordData + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}. {} {} {} {}",
            self.owner,
            self.ttl.as_secs(),
            self.class,
            self.data.rtype(),
            self.data
        )
    }
}

impl<Name, Data> fmt::Debug for Record<Name, Data>
where
    Name: fmt::Debug,
    Data: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Record")
            .field("owner", &self.owner)
            .field("class", &self.class)
            .field("ttl", &self.ttl)
            .field("data", &self.data)
            .finish()
    }
}

//------------ ComposeRecord -------------------------------------------------

/// A helper trait allowing construction of records on the fly.
///
/// The trait’s primary users arer the three record section buider type of
/// the [message builder] system. Their `push` methods accept anything that
/// implements this trait.
///
/// Implementations are provided for [`Record`] values and references. In
/// addition, a tuple of a domain name, class, TTL, and record data can be
/// used as this trait, saving the detour of constructing a record first.
/// Since the class is pretty much always `Class::In`, it can be left out in
/// this case.
///
/// [`Class::In`]: ../iana/class/enum.Class.html#variant.In
/// [`Record`]: struct.Record.html
pub trait ComposeRecord {
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError>;
}

impl<'a, T: ComposeRecord> ComposeRecord for &'a T {
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        (*self).compose_record(target)
    }
}

impl<Name, Data> ComposeRecord for Record<Name, Data>
where
    Name: ToDname,
    Data: ComposeRecordData,
{
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        self.compose(target)
    }
}

impl<Name, Data> ComposeRecord for (Name, Class, u32, Data)
where
    Name: ToDname,
    Data: ComposeRecordData,
{
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        Record::new(&self.0, self.1, Ttl::from_secs(self.2), &self.3)
            .compose(target)
    }
}

impl<Name, Data> ComposeRecord for (Name, Class, Ttl, Data)
where
    Name: ToDname,
    Data: ComposeRecordData,
{
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        Record::new(&self.0, self.1, self.2, &self.3).compose(target)
    }
}

impl<Name, Data> ComposeRecord for (Name, u32, Data)
where
    Name: ToDname,
    Data: ComposeRecordData,
{
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        Record::new(&self.0, Class::In, Ttl::from_secs(self.1), &self.2)
            .compose(target)
    }
}

impl<Name, Data> ComposeRecord for (Name, Ttl, Data)
where
    Name: ToDname,
    Data: ComposeRecordData,
{
    fn compose_record<Target: Composer + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        Record::new(&self.0, Class::In, self.1, &self.2).compose(target)
    }
}

//------------ RecordHeader --------------------------------------------------

/// The header of a resource record.
///
/// This type encapsulates the common header of a resource record. It consists
/// of the owner, record type, class, TTL, and the length of the record data.
/// It is effectively a helper type for dealing with resource records encoded
/// in a DNS message.
///
/// See [`Record`] for more details about resource records.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RecordHeader<Name> {
    owner: Name,
    rtype: Rtype,
    class: Class,
    ttl: Ttl,
    rdlen: u16,
}

impl<Name> RecordHeader<Name> {
    /// Creates a new record header from its components.
    pub fn new(
        owner: Name,
        rtype: Rtype,
        class: Class,
        ttl: Ttl,
        rdlen: u16,
    ) -> Self {
        RecordHeader {
            owner,
            rtype,
            class,
            ttl,
            rdlen,
        }
    }
}

impl<'a, Octs: Octets + ?Sized> RecordHeader<ParsedDname<&'a Octs>> {
    fn deref_owner(&self) -> RecordHeader<ParsedDname<Octs::Range<'a>>> {
        RecordHeader {
            owner: self.owner.deref_octets(),
            rtype: self.rtype,
            class: self.class,
            ttl: self.ttl,
            rdlen: self.rdlen,
        }
    }
}

impl<Name> RecordHeader<Name> {
    /// Returns a reference to the owner of the record.
    pub fn owner(&self) -> &Name {
        &self.owner
    }

    /// Returns the record type of the record.
    pub fn rtype(&self) -> Rtype {
        self.rtype
    }

    /// Returns the class of the record.
    pub fn class(&self) -> Class {
        self.class
    }

    /// Returns the TTL of the record.
    pub fn ttl(&self) -> Ttl {
        self.ttl
    }

    /// Returns the data length of the record.
    pub fn rdlen(&self) -> u16 {
        self.rdlen
    }

    /// Converts the header into an actual record.
    pub fn into_record<Data>(self, data: Data) -> Record<Name, Data> {
        Record::new(self.owner, self.class, self.ttl, data)
    }
}

/// # Parsing and Composing
///
impl<Octs> RecordHeader<ParsedDname<Octs>> {
    pub fn parse<'a, Src: Octets<Range<'a> = Octs>>(
        parser: &mut Parser<'a, Src>,
    ) -> Result<Self, ParseError> {
        RecordHeader::parse_ref(parser).map(|res| res.deref_owner())
    }
}

impl<'a, Octs: AsRef<[u8]> + ?Sized> RecordHeader<ParsedDname<&'a Octs>> {
    pub fn parse_ref(
        parser: &mut Parser<'a, Octs>,
    ) -> Result<Self, ParseError> {
        Ok(RecordHeader::new(
            ParsedDname::parse_ref(parser)?,
            Rtype::parse(parser)?,
            Class::parse(parser)?,
            Ttl::parse(parser)?,
            parser.parse_u16_be()?,
        ))
    }
}

impl<Name> RecordHeader<Name> {
    /// Parses a record header and then skips over the data.
    ///
    /// If the function succeeds, the parser will be positioned right behind
    /// the end of the record.
    pub fn parse_and_skip<'a, Octs>(
        parser: &mut Parser<'a, Octs>,
    ) -> Result<Self, ParseError>
    where
        Self: Parse<'a, Octs>,
        Octs: Octets,
    {
        let header = Self::parse(parser)?;
        match parser.advance(header.rdlen() as usize) {
            Ok(()) => Ok(header),
            Err(_) => Err(ParseError::ShortInput),
        }
    }
}

impl RecordHeader<()> {
    /// Parses only the record length and skips over all the other fields.
    fn parse_rdlen<Octs: Octets + ?Sized>(
        parser: &mut Parser<Octs>,
    ) -> Result<u16, ParseError> {
        ParsedDname::skip(parser)?;
        parser.advance(
            (Rtype::COMPOSE_LEN + Class::COMPOSE_LEN + u32::COMPOSE_LEN)
                .into(),
        )?;
        u16::parse(parser)
    }
}

impl<Octs> RecordHeader<ParsedDname<Octs>> {
    /// Parses the remainder of the record and returns it.
    ///
    /// The method assumes that the parsers is currently positioned right
    /// after the end of the record header. If the record data type `D`
    /// feels capable of parsing a record with a header of `self`, the
    /// method will parse the data and return a full `Record<D>`. Otherwise,
    /// it skips over the record data.
    pub fn parse_into_record<'a, Src, Data>(
        self,
        parser: &mut Parser<'a, Src>,
    ) -> Result<Option<Record<ParsedDname<Octs>, Data>>, ParseError>
    where
        Src: AsRef<[u8]> + ?Sized,
        Data: ParseRecordData<'a, Src>,
    {
        let mut parser = parser.parse_parser(self.rdlen as usize)?;
        let res = Data::parse_rdata(self.rtype, &mut parser)?
            .map(|data| Record::new(self.owner, self.class, self.ttl, data));
        if res.is_some() && parser.remaining() > 0 {
            return Err(ParseError::Form(FormError::new(
                "trailing data in option",
            )));
        }
        Ok(res)
    }
}

impl<Name: ToDname> RecordHeader<Name> {
    pub fn compose<Target: Composer + ?Sized>(
        &self,
        buf: &mut Target,
    ) -> Result<(), Target::AppendError> {
        buf.append_compressed_dname(&self.owner)?;
        self.rtype.compose(buf)?;
        self.class.compose(buf)?;
        self.ttl.compose(buf)?;
        self.rdlen.compose(buf)
    }

    pub fn compose_canonical<Target: Composer + ?Sized>(
        &self,
        buf: &mut Target,
    ) -> Result<(), Target::AppendError> {
        self.owner.compose_canonical(buf)?;
        self.rtype.compose(buf)?;
        self.class.compose(buf)?;
        self.ttl.compose(buf)?;
        self.rdlen.compose(buf)
    }
}

//--- PartialEq and Eq

impl<Name, NName> PartialEq<RecordHeader<NName>> for RecordHeader<Name>
where
    Name: ToDname,
    NName: ToDname,
{
    fn eq(&self, other: &RecordHeader<NName>) -> bool {
        self.owner.name_eq(&other.owner)
            && self.rtype == other.rtype
            && self.class == other.class
            && self.ttl == other.ttl
            && self.rdlen == other.rdlen
    }
}

impl<Name: ToDname> Eq for RecordHeader<Name> {}

//--- PartialOrd and Ord
//
// No CanonicalOrd because that doesn’t really make sense.

impl<Name, NName> PartialOrd<RecordHeader<NName>> for RecordHeader<Name>
where
    Name: ToDname,
    NName: ToDname,
{
    fn partial_cmp(&self, other: &RecordHeader<NName>) -> Option<Ordering> {
        match self.owner.name_cmp(&other.owner) {
            Ordering::Equal => {}
            other => return Some(other),
        }
        match self.rtype.partial_cmp(&other.rtype) {
            Some(Ordering::Equal) => {}
            other => return other,
        }
        match self.class.partial_cmp(&other.class) {
            Some(Ordering::Equal) => {}
            other => return other,
        }
        match self.ttl.partial_cmp(&other.ttl) {
            Some(Ordering::Equal) => {}
            other => return other,
        }
        self.rdlen.partial_cmp(&other.rdlen)
    }
}

impl<Name: ToDname> Ord for RecordHeader<Name> {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.owner.name_cmp(&other.owner) {
            Ordering::Equal => {}
            other => return other,
        }
        match self.rtype.cmp(&other.rtype) {
            Ordering::Equal => {}
            other => return other,
        }
        match self.class.cmp(&other.class) {
            Ordering::Equal => {}
            other => return other,
        }
        match self.ttl.cmp(&other.ttl) {
            Ordering::Equal => {}
            other => return other,
        }
        self.rdlen.cmp(&other.rdlen)
    }
}

//--- Hash

impl<Name: hash::Hash> hash::Hash for RecordHeader<Name> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.owner.hash(state);
        self.rtype.hash(state);
        self.class.hash(state);
        self.ttl.hash(state);
        self.rdlen.hash(state);
    }
}

//--- Debug

impl<Name: fmt::Debug> fmt::Debug for RecordHeader<Name> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("RecordHeader")
            .field("owner", &self.owner)
            .field("rtype", &self.rtype)
            .field("class", &self.class)
            .field("ttl", &self.ttl)
            .field("rdlen", &self.rdlen)
            .finish()
    }
}

//------------ ParsedRecord --------------------------------------------------

/// A raw record parsed from a message.
///
/// A value of this type contains the record header and the raw record data.
/// It is mainly used as an intermediary type when turning raw message data
/// into [`Record`]s.
///
/// It allows access to the header only but can be traded for a real record
/// of a specific type of [`ParseRecordData`] (i.e., some type that knowns
/// how to parse record data) via the [`to_record`] and [`into_record`]
/// methods.
///
/// [`Record`]: struct.Record.html
/// [`ParseRecordData`]: trait.ParseRecordData.html
/// [`to_record`]: #method.to_record
/// [`into_record`]: #method.into_record
#[derive(Clone)]
pub struct ParsedRecord<'a, Octs: Octets + ?Sized> {
    /// The record’s header.
    header: RecordHeader<ParsedDname<&'a Octs>>,

    /// A parser positioned at the beginning of the record’s data.
    data: Parser<'a, Octs>,
}

impl<'a, Octs: Octets + ?Sized> ParsedRecord<'a, Octs> {
    /// Creates a new parsed record from a header and the record data.
    ///
    /// The record data is provided via a parser that is positioned at the
    /// first byte of the record data.
    #[must_use]
    pub fn new(
        header: RecordHeader<ParsedDname<&'a Octs>>,
        data: Parser<'a, Octs>,
    ) -> Self {
        ParsedRecord { header, data }
    }

    /// Returns a reference to the owner of the record.
    #[must_use]
    pub fn owner(&self) -> ParsedDname<&'a Octs> {
        *self.header.owner()
    }

    /// Returns the record type of the record.
    #[must_use]
    pub fn rtype(&self) -> Rtype {
        self.header.rtype()
    }

    /// Returns the class of the record.
    #[must_use]
    pub fn class(&self) -> Class {
        self.header.class()
    }

    /// Returns the TTL of the record.
    #[must_use]
    pub fn ttl(&self) -> Ttl {
        self.header.ttl()
    }

    /// Returns the data length of the record.
    #[must_use]
    pub fn rdlen(&self) -> u16 {
        self.header.rdlen()
    }
}

impl<'a, Octs: Octets + ?Sized> ParsedRecord<'a, Octs> {
    /// Creates a real resource record from the parsed record.
    ///
    /// The method is generic over a type that knows how to parse record
    /// data via the [`ParseRecordData`] trait. The record data is given to
    /// this trait for parsing. If the trait feels capable of parsing this
    /// type of record (as indicated by the record type) and parsing succeeds,
    /// the method returns `Ok(Some(_))`. It returns `Ok(None)` if the trait
    /// doesn’t know how to parse this particular record type. It returns
    /// an error if parsing fails.
    ///
    /// [`ParseRecordData`]: ../rdata/trait.ParseRecordData.html
    #[allow(clippy::type_complexity)]
    pub fn to_record<Data>(
        &self,
    ) -> Result<Option<Record<ParsedDname<Octs::Range<'_>>, Data>>, ParseError>
    where
        Data: ParseRecordData<'a, Octs>,
    {
        self.header
            .deref_owner()
            .parse_into_record(&mut self.data.clone())
    }

    /// Trades the parsed record for a real resource record.
    ///
    /// The method is generic over a type that knows how to parse record
    /// data via the [`ParseRecordData`] trait. The record data is given to
    /// this trait for parsing. If the trait feels capable of parsing this
    /// type of record (as indicated by the record type) and parsing succeeds,
    /// the method returns `Ok(Some(_))`. It returns `Ok(None)` if the trait
    /// doesn’t know how to parse this particular record type. It returns
    /// an error if parsing fails.
    ///
    /// [`ParseRecordData`]: ../rdata/trait.ParseRecordData.html
    #[allow(clippy::type_complexity)]
    pub fn into_record<Data>(
        mut self,
    ) -> Result<Option<Record<ParsedDname<Octs::Range<'a>>, Data>>, ParseError>
    where
        Data: ParseRecordData<'a, Octs>,
    {
        self.header.deref_owner().parse_into_record(&mut self.data)
    }
}

impl<'a, Octs: Octets + ?Sized> ParsedRecord<'a, Octs> {
    pub fn parse(parser: &mut Parser<'a, Octs>) -> Result<Self, ParseError> {
        let header = RecordHeader::parse_ref(parser)?;
        let data = *parser;
        parser.advance(header.rdlen() as usize)?;
        Ok(Self::new(header, data))
    }

    pub fn skip(parser: &mut Parser<'a, Octs>) -> Result<(), ParseError> {
        let rdlen = RecordHeader::parse_rdlen(parser)?;
        //let rdlen = RecordHeader::parse(parser)?.rdlen();
        parser.advance(rdlen as usize)?;
        Ok(())
    }

    // No compose because the data may contain compressed domain
    // names.
}

//--- PartialEq and Eq

impl<'a, 'o, Octs, Other> PartialEq<ParsedRecord<'o, Other>>
    for ParsedRecord<'a, Octs>
where
    Octs: Octets + ?Sized,
    Other: Octets + ?Sized,
{
    fn eq(&self, other: &ParsedRecord<'o, Other>) -> bool {
        self.header == other.header
            && self
                .data
                .peek(self.header.rdlen() as usize)
                .eq(&other.data.peek(other.header.rdlen() as usize))
    }
}

impl<'a, Octs: Octets + ?Sized> Eq for ParsedRecord<'a, Octs> {}

//------------ RecordParseError ----------------------------------------------

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecordParseError<N, D> {
    Name(N),
    Data(D),
    ShortBuf,
}

impl<N, D> fmt::Display for RecordParseError<N, D>
where
    N: fmt::Display,
    D: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            RecordParseError::Name(ref name) => name.fmt(f),
            RecordParseError::Data(ref data) => data.fmt(f),
            RecordParseError::ShortBuf => {
                f.write_str("unexpected end of buffer")
            }
        }
    }
}

#[cfg(feature = "std")]
impl<N, D> std::error::Error for RecordParseError<N, D>
where
    N: std::error::Error,
    D: std::error::Error,
{
}

impl<N, D> From<ShortBuf> for RecordParseError<N, D> {
    fn from(_: ShortBuf) -> Self {
        RecordParseError::ShortBuf
    }
}

//------------ Ttl ----------------------------------------------

const SECS_PER_MINUTE: u32 = 60;
const SECS_PER_HOUR: u32 = 3600;
const SECS_PER_DAY: u32 = 86400;

/// A span of time, typically used to describe the time a given DNS record is valid.
///
/// `Ttl` implements many common traits, including [`core::ops::Add`], [`core::ops::Sub`], and other [`core::ops`] traits. It implements Default by returning a zero-length `Ttl`.
///
/// # Why not [`std::time::Duration`]?
///
/// Two reasons make [`std::time::Duration`] not suited for representing DNS TTL values:
/// 1. According to [RFC 2181](https://datatracker.ietf.org/doc/html/rfc2181#section-8) TTL values have second-level precision while [`std::time::Duration`] can represent time down to the nanosecond level.
///     This amount of precision is simply not needed and might cause confusion when sending `Duration`s over the network.
/// 2. When working with DNS TTL values it's common to want to know a time to live in minutes or hours. [`std::time::Duration`] does not expose easy to use methods for this purpose, while `Ttl` does.
///
/// `Ttl` provides two methods [`Ttl::from_duration_lossy`] and [`Ttl::into_duration`] to convert between `Duration` and `Ttl`.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ttl(u32);

impl Ttl {
    /// A time-to-live of one second.
    pub const SECOND: Ttl = Ttl::from_secs(1);

    /// A time-to-live of one minute.
    pub const MINUTE: Ttl = Ttl::from_mins(1);

    /// A time-to-live of one hour.
    pub const HOUR: Ttl = Ttl::from_hours(1);

    /// A time-to-live of one day.
    pub const DAY: Ttl = Ttl::from_days(1);

    /// A duration of zero time.
    pub const ZERO: Ttl = Ttl::from_secs(0);

    /// The maximum theoretical time to live.
    pub const MAX: Ttl = Ttl::from_secs(u32::MAX);

    /// The practical maximum time to live as recommended by [RFC 8767](https://datatracker.ietf.org/doc/html/rfc8767#section-4).
    pub const CAP: Ttl = Ttl::from_secs(604_800);

    /// The maximum number of minutes that a `Ttl` can represent.
    pub const MAX_MINUTES: u32 = 71582788;

    /// The maximum number of hours that a `Ttl` can represent.
    pub const MAX_HOURS: u32 = 1193046;

    /// The maximum number of days that a `Ttl` can represent.
    pub const MAX_DAYS: u16 = 49710;

    pub const COMPOSE_LEN: u16 = 4;

    /// Returns the total time to live in seconds.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// let ttl = Ttl::from_secs(120);
    /// assert_eq!(ttl.as_secs(), 120);
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_secs(&self) -> u32 {
        self.0
    }

    /// Returns the total time to live in minutes.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// let ttl = Ttl::from_secs(120);
    /// assert_eq!(ttl.as_minutes(), 2);
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_minutes(&self) -> u32 {
        self.0 / SECS_PER_MINUTE
    }

    /// Returns the total time to live in hours.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// let ttl = Ttl::from_secs(7200);
    /// assert_eq!(ttl.as_hours(), 2);
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_hours(&self) -> u32 {
        self.0 / SECS_PER_HOUR
    }

    /// Returns the total time to live in days.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// let ttl = Ttl::from_secs(172800);
    /// assert_eq!(ttl.as_days(), 2);
    /// ```
    #[must_use]
    #[inline]
    pub const fn as_days(&self) -> u16 {
        (self.0 / SECS_PER_DAY) as u16
    }

    /// Converts a `Ttl` into a [`std::time::Duration`].
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    /// use std::time::Duration;
    ///
    /// let ttl = Ttl::from_mins(2);
    /// let duration = ttl.into_duration();
    /// assert_eq!(duration.as_secs(), 120);
    /// ```
    #[must_use]
    #[inline]
    pub const fn into_duration(&self) -> Duration {
        Duration::from_secs(self.0 as u64)
    }

    /// Creates a new `Ttl` from the specified number of seconds.
    #[must_use]
    #[inline]
    pub const fn from_secs(secs: u32) -> Self {
        Self(secs)
    }

    /// Creates a new `Ttl` from the specified number of minutes.
    ///
    /// # Panics
    ///
    /// The maximum number of days that a `Ttl` can represent is `71582788`.
    /// This method will panic if it is being called with a value greater than that.
    #[must_use]
    #[inline]
    pub const fn from_mins(minutes: u32) -> Self {
        assert!(minutes <= 71582788);
        Self(minutes * SECS_PER_MINUTE)
    }

    /// Creates a new `Ttl` from the specified number of hours.
    ///
    /// # Panics
    ///
    /// The maximum number of hours that a `Ttl` can represent is `1193046`.
    /// This method will panic if it is being called with a value greater than that.
    #[must_use]
    #[inline]
    pub const fn from_hours(hours: u32) -> Self {
        assert!(hours <= 1193046);
        Self(hours * SECS_PER_HOUR)
    }

    /// Creates a new `Ttl` from the specified number of days.
    ///
    /// # Panics
    ///
    /// The maximum number of days that a `Ttl` can represent is `49710`.
    /// This method will panic if it is being called with a value greater than that.
    #[must_use]
    #[inline]
    pub const fn from_days(days: u16) -> Self {
        assert!(days <= 49710);
        Self(days as u32 * SECS_PER_DAY)
    }

    /// Creates a new `Ttl` from a [`std::time::Duration`].
    ///
    /// This operation is lossy as [`Duration`] stores seconds as `u64`, while `Ttl` stores seconds as `u32` to comply with the DNS specifications.
    /// [`Duration`] also represents time using sub-second precision, which is not kept when converting into a `Ttl`.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    /// use std::time::Duration;
    ///
    /// assert_eq!(Ttl::from_duration_lossy(Duration::new(1, 0)), Ttl::from_secs(1));
    /// assert_eq!(Ttl::from_duration_lossy(Duration::new(1, 6000)), Ttl::from_secs(1));
    /// ```
    #[must_use]
    #[inline]
    pub const fn from_duration_lossy(duration: Duration) -> Self {
        Self(duration.as_secs() as u32)
    }

    /// Returns true if this `Tll` spans no time.
    ///
    /// This usually indicates a given record should not be cached.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert!(Ttl::ZERO.is_zero());
    /// assert!(Ttl::from_secs(0).is_zero());
    /// assert!(Ttl::from_mins(0).is_zero());
    /// assert!(Ttl::from_hours(0).is_zero());
    /// assert!(Ttl::from_days(0).is_zero());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.0 == 0
    }

    /// Checked `Ttl` addition. Computes `self + other`, returning [`None`]
    /// if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(0).checked_add(Ttl::from_secs(1)), Some(Ttl::from_secs(1)));
    /// assert_eq!(Ttl::from_secs(1).checked_add(Ttl::MAX), None);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    #[inline]
    pub const fn checked_add(self, rhs: Ttl) -> Option<Ttl> {
        if let Some(secs) = self.0.checked_add(rhs.0) {
            Some(Ttl(secs))
        } else {
            None
        }
    }

    /// Saturating `Ttl` addition. Computes `self + other`, returning [`Ttl::MAX`]
    /// if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(0).saturating_add(Ttl::from_secs(1)), Ttl::from_secs(1));
    /// assert_eq!(Ttl::from_secs(1).saturating_add(Ttl::MAX), Ttl::MAX);
    /// ```
    #[must_use = "this returns the result of the operation, \
    without modifying the original"]
    #[inline]
    pub const fn saturating_add(self, rhs: Ttl) -> Ttl {
        match self.0.checked_add(rhs.0) {
            Some(secs) => Ttl(secs),
            None => Ttl::MAX,
        }
    }

    /// Checked `Ttl` subtraction. Computes `self - other`, returning [`None`]
    /// if the result would be negative or if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(1).checked_sub(Ttl::from_secs(0)), Some(Ttl::from_secs(1)));
    /// assert_eq!(Ttl::from_secs(0).checked_sub(Ttl::from_secs(1)), None);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    #[inline]
    pub const fn checked_sub(self, rhs: Ttl) -> Option<Ttl> {
        if let Some(secs) = self.0.checked_sub(rhs.0) {
            Some(Ttl(secs))
        } else {
            None
        }
    }

    /// Saturating `Ttl` subtraction. Computes `self - other`, returning [`Ttl::ZERO`]
    /// if the result would be negative or if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(1).saturating_sub(Ttl::from_secs(0)), Ttl::from_secs(1));
    /// assert_eq!(Ttl::from_secs(0).saturating_sub(Ttl::from_secs(1)), Ttl::ZERO);
    /// ```
    #[must_use = "this returns the result of the operation, \
    without modifying the original"]
    #[inline]
    pub const fn saturating_sub(self, rhs: Ttl) -> Ttl {
        match self.0.checked_sub(rhs.0) {
            Some(secs) => Ttl(secs),
            None => Ttl::ZERO,
        }
    }

    /// Checked `Ttl` multiplication. Computes `self * other`, returning
    /// [`None`] if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(5).checked_mul(2), Some(Ttl::from_secs(10)));
    /// assert_eq!(Ttl::from_secs(u32::MAX - 1).checked_mul(2), None);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    #[inline]
    pub const fn checked_mul(self, rhs: u32) -> Option<Ttl> {
        if let Some(secs) = self.0.checked_mul(rhs) {
            Some(Ttl(secs))
        } else {
            None
        }
    }

    /// Saturating `Duration` multiplication. Computes `self * other`, returning
    /// [`Duration::MAX`] if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(5).saturating_mul(2), Ttl::from_secs(10));
    /// assert_eq!(Ttl::from_secs(u32::MAX - 1).saturating_mul(2), Ttl::MAX);
    /// ```
    #[must_use = "this returns the result of the operation, \
    without modifying the original"]
    #[inline]
    pub const fn saturating_mul(self, rhs: u32) -> Ttl {
        match self.0.checked_mul(rhs) {
            Some(secs) => Ttl(secs),
            None => Ttl::MAX,
        }
    }

    /// Checked `Duration` division. Computes `self / other`, returning [`None`]
    /// if `other == 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_secs(10).checked_div(2), Some(Ttl::from_secs(5)));
    /// assert_eq!(Ttl::from_mins(1).checked_div(2), Some(Ttl::from_secs(30)));
    /// assert_eq!(Ttl::from_secs(2).checked_div(0), None);
    /// ```
    #[must_use = "this returns the result of the operation, \
    without modifying the original"]
    #[inline]
    pub const fn checked_div(self, rhs: u32) -> Option<Ttl> {
        if rhs != 0 {
            Some(Ttl(self.0 / rhs))
        } else {
            None
        }
    }

    /// Caps the value of `Ttl` at 7 days (604800 seconds) as recommended by [RFC 8767](https://datatracker.ietf.org/doc/html/rfc8767#name-standards-action).
    ///
    /// # Examples
    ///
    /// ```
    /// use domain::base::Ttl;
    ///
    /// assert_eq!(Ttl::from_mins(5).cap(), Ttl::from_mins(5));
    /// assert_eq!(Ttl::from_days(50).cap(), Ttl::from_days(7));
    /// ```
    #[must_use = "this returns the result of the operation, \
    without modifying the original"]
    #[inline]
    pub const fn cap(self) -> Ttl {
        if self.0 > Self::CAP.0 {
            Self::CAP
        } else {
            self
        }
    }

    pub fn compose<Target: OctetsBuilder + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        target.append_slice(&(self.as_secs()).to_be_bytes())
    }

    pub fn parse<Octs: AsRef<[u8]> + ?Sized>(
        parser: &mut Parser<'_, Octs>,
    ) -> Result<Self, ParseError> {
        parser
            .parse_u32_be()
            .map(Ttl::from_secs)
            .map_err(Into::into)
    }
}

impl core::ops::Add for Ttl {
    type Output = Ttl;

    fn add(self, rhs: Self) -> Self::Output {
        self.checked_add(rhs)
            .expect("overflow when adding durations")
    }
}

impl core::ops::AddAssign for Ttl {
    fn add_assign(&mut self, rhs: Ttl) {
        *self = *self + rhs;
    }
}

impl core::ops::Sub for Ttl {
    type Output = Ttl;

    fn sub(self, rhs: Self) -> Self::Output {
        self.checked_sub(rhs)
            .expect("overflow when subtracting durations")
    }
}

impl core::ops::SubAssign for Ttl {
    fn sub_assign(&mut self, rhs: Ttl) {
        *self = *self - rhs;
    }
}

impl core::ops::Mul<u32> for Ttl {
    type Output = Ttl;

    fn mul(self, rhs: u32) -> Self::Output {
        self.checked_mul(rhs)
            .expect("overflow when multiplying duration by scalar")
    }
}

impl core::ops::MulAssign<u32> for Ttl {
    fn mul_assign(&mut self, rhs: u32) {
        *self = *self * rhs;
    }
}

impl core::ops::Div<u32> for Ttl {
    type Output = Ttl;

    fn div(self, rhs: u32) -> Ttl {
        self.checked_div(rhs)
            .expect("divide by zero error when dividing duration by scalar")
    }
}

impl core::ops::DivAssign<u32> for Ttl {
    fn div_assign(&mut self, rhs: u32) {
        *self = *self / rhs;
    }
}

macro_rules! sum_durations {
    ($iter:expr) => {{
        let mut total_secs: u32 = 0;

        for entry in $iter {
            total_secs = total_secs
                .checked_add(entry.0)
                .expect("overflow in iter::sum over durations");
        }

        Ttl(total_secs)
    }};
}

impl core::iter::Sum for Ttl {
    fn sum<I: Iterator<Item = Ttl>>(iter: I) -> Ttl {
        sum_durations!(iter)
    }
}

impl<'a> core::iter::Sum<&'a Ttl> for Ttl {
    fn sum<I: Iterator<Item = &'a Ttl>>(iter: I) -> Ttl {
        sum_durations!(iter)
    }
}

// No From impl because conversion is lossy
#[allow(clippy::from_over_into)]
impl Into<Duration> for Ttl {
    fn into(self) -> Duration {
        Duration::from_secs(u64::from(self.0))
    }
}

//============ Testing ======================================================

#[cfg(test)]
mod test {
    #[test]
    #[cfg(feature = "bytes")]
    fn ds_octets_into() {
        use super::*;
        use crate::base::iana::{Class, DigestAlg, SecAlg};
        use crate::base::name::Dname;
        use crate::rdata::Ds;
        use bytes::Bytes;
        use octseq::octets::OctetsInto;

        let ds: Record<Dname<&[u8]>, Ds<&[u8]>> = Record::new(
            Dname::from_octets(b"\x01a\x07example\0".as_ref()).unwrap(),
            Class::In,
            Ttl::from_secs(86400),
            Ds::new(
                12,
                SecAlg::RsaSha256,
                DigestAlg::Sha256,
                b"something".as_ref(),
            )
            .unwrap(),
        );
        let ds_bytes: Record<Dname<Bytes>, Ds<Bytes>> =
            ds.clone().octets_into();
        assert_eq!(ds.owner(), ds_bytes.owner());
        assert_eq!(ds.data().digest(), ds_bytes.data().digest());
    }
}