sacn 0.11.1

A Rust implementation of the ANSI E1.31 Streaming ACN protocol, tested against protocol version ANSI E1.31-2018.
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
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
// Copyright 2020 sacn Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
// This file was modified as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.

#![warn(missing_docs)]

//! Parsing of sacn network packets.
//!
//! The packets live within the scope of the ACN protocol suite.
//!
//! # Examples
//!
//! ```
//! # extern crate uuid;
//! # extern crate sacn;
//! # use uuid::Uuid;
//! # use sacn::packet::{AcnRootLayerProtocol, E131RootLayer, E131RootLayerData, DataPacketFramingLayer, DataPacketDmpLayer};
//! # fn main() {
//! #[cfg(feature = "std")]
//! # {
//! let packet = AcnRootLayerProtocol {
//!     pdu: E131RootLayer {
//!         cid: Uuid::new_v4(),
//!         data: E131RootLayerData::DataPacket(DataPacketFramingLayer {
//!             source_name: "Source_A".into(),
//!             priority: 100,
//!             synchronization_address: 7962,
//!             sequence_number: 154,
//!             preview_data: false,
//!             stream_terminated: false,
//!             force_synchronization: false,
//!             universe: 1,
//!             data: DataPacketDmpLayer {
//!                 property_values: vec![0, 1, 2, 3].into(),
//!             },
//!         }),
//!     },
//! };
//!
//! let mut buf = [0; 638];
//! packet.pack(&mut buf).unwrap();
//!
//! assert_eq!(
//!     AcnRootLayerProtocol::parse(&buf).unwrap(),
//!     packet
//! );
//! # }}
//! ```

/// Uses the sACN errors.
use crate::error::errors::{Result, SacnError};
use crate::sacn_parse_pack_error::ParsePacketError;

/// The core crate is used for string processing during packet parsing/packing as well as to provide access to the Hash trait.
use core::hash::{self, Hash};
use core::str;

use std::borrow::Cow;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::vec::Vec;
use std::{time, time::Duration};

use socket2::SockAddr;

/// The byteorder crate is used for marshalling data on/off the network in Network Byte Order.
use byteorder::{ByteOrder, NetworkEndian};

/// The uuid crate is used for working with/generating UUIDs which sACN uses as part of the cid field in the protocol.
use uuid::Uuid;

/// The maximum number of universes per page in a universe discovery packet.
pub const DISCOVERY_UNI_PER_PAGE: usize = 512;

/// The universe used for universe discovery as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative)
pub const E131_DISCOVERY_UNIVERSE: u16 = 64214;

/// The default priority used for the E1.31 packet priority field, as per ANSI E1.31-2018 Section 4.1 Table 4-1
pub const E131_DEFAULT_PRIORITY: u8 = 100;

/// The maximum allowed priority for a E1.31 packet, as per ANSI E1.31-2018 Section 6.2.3
pub const E131_MAX_PRIORITY: u8 = 200;

/// Value of the highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
pub const E131_MULTICAST_IPV4_HIGHEST_BYTE: u8 = 239;

/// Value of the second highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
pub const E131_MULTICAST_IPV4_SECOND_BYTE: u8 = 255;

/// The maximum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
pub const E131_MAX_MULTICAST_UNIVERSE: u16 = 63999;

/// The lowest / minimum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
pub const E131_MIN_MULTICAST_UNIVERSE: u16 = 1;

/// The synchronisation address used to indicate that there is no synchronisation required for the data packet.
/// As defined in ANSI E1.31-2018 Section 6.2.4.1
pub const E131_NO_SYNC_ADDR: u16 = 0;

/// The interval between universe discovery packets (adverts) as defined by ANSI E1.31-2018 Appendix A.
pub const E131_UNIVERSE_DISCOVERY_INTERVAL: Duration = time::Duration::from_secs(10);

/// The exclusive lower bound on the different between the received and expected sequence numbers within which a
/// packet will be discarded. Outside of the range specified by (E131_SEQ_DIFF_DISCARD_LOWER_BOUND, E131_SEQ_DIFF_DISCARD_UPPER_BOUND]
/// the packet won't be discarded.
///
/// Having a range allows receivers to catch up if packets are lost.
/// Value as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
pub const E131_SEQ_DIFF_DISCARD_LOWER_BOUND: isize = -20;

/// The inclusive upper bound on the different between the received and expected sequence numbers within which a
/// packet will be discarded. Outside of the range specified by (E131_SEQ_DIFF_DISCARD_LOWER_BOUND, E131_SEQ_DIFF_DISCARD_UPPER_BOUND]
/// the packet won't be discarded.
///
/// Having a range allows receivers to catch up if packets are lost.
/// Value as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
pub const E131_SEQ_DIFF_DISCARD_UPPER_BOUND: isize = 0;

/// The bit mask used to get the preview-data option within the packet option field as per
/// ANSI E1.31-2018 Section 6.2.6
pub const E131_PREVIEW_DATA_OPTION_BIT_MASK: u8 = 0b1000_0000;

/// The bit mask used to get the stream-termination option within the packet option field as per
/// ANSI E1.31-2018 Section 6.2.6
pub const E131_STREAM_TERMINATION_OPTION_BIT_MASK: u8 = 0b0100_0000;

/// The bit mask used to get the force-synchronisation option within the packet option field as per
/// ANSI E1.31-2018 Section 6.2.6
pub const E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK: u8 = 0b0010_0000;

/// The minimum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
/// As per ANSI E1.31-2018 Section 8 Table 8-9.
pub const E131_UNIVERSE_DISCOVERY_LAYER_MIN_LENGTH: usize = 8;

/// The maximum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
/// As per ANSI E1.31-2018 Section 8 Table 8-9.
pub const E131_UNIVERSE_DISCOVERY_LAYER_MAX_LENGTH: usize = 1032;

/// The expected value of the root layer length field for a synchronisation packet.
/// 33 bytes as per ANSI E1.31-2018 Section 4.2 Table 4-2.
pub const E131_UNIVERSE_SYNC_PACKET_ROOT_LENGTH: usize = 33;

/// The expected value of the framing layer length field for a synchronisation packet.
/// 11 bytes as per ANSI E1.31-2018 Section 4.2 Table 4-2.
pub const E131_UNIVERSE_SYNC_PACKET_FRAMING_LAYER_LENGTH: usize = 11;

/// The minimum expected value of the framing layer length field for a discovery packet.
/// 84 bytes as per ANSI E1.31-2018 Section 4.3 Table 4-3.
pub const E131_UNIVERSE_DISCOVERY_FRAMING_LAYER_MIN_LENGTH: usize = 82;

/// The number of stream termination packets sent when a source terminates a stream.
/// Set to 3 as per section 6.2.6 , Stream_Terminated: Bit 6 of ANSI E1.31-2018.
pub const E131_TERMINATE_STREAM_PACKET_COUNT: usize = 3;

/// The length of the pdu flags and length field in bytes.
pub const E131_PDU_LENGTH_FLAGS_LENGTH: usize = 2;

/// The pdu flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
pub const E131_PDU_FLAGS: u8 = 0x70;

/// The length in bytes of the root layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
pub const E131_ROOT_LAYER_VECTOR_LENGTH: usize = 4;

/// The length in bytes of the E1.31 framing layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
pub const E131_FRAMING_LAYER_VECTOR_LENGTH: usize = 4;

/// The length in bytes of the priority field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
const E131_PRIORITY_FIELD_LENGTH: usize = 1;

/// The length in bytes of the sequence number field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-2.
const E131_SEQ_NUM_FIELD_LENGTH: usize = 1;

/// The length in bytes of the options field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
const E131_OPTIONS_FIELD_LENGTH: usize = 1;

/// The length in bytes of a universe field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-3.
const E131_UNIVERSE_FIELD_LENGTH: usize = 2;

/// The length in bytes of the Vector field within the DMP layer of an ANSI E1.31-2018 data packet as per ANSI E1.31-2018
/// Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH: usize = 1;

/// The length in bytes of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per
/// ANSI E1.31-2018 Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH: usize = 1;

/// The length in bytes of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per
/// ANSI E1.31-2018 Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH: usize = 2;

/// The length in bytes of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per
/// ANSI E1.31-2018 Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH: usize = 2;

/// The length in bytes of the "Property value count" field within an ANSI E1.31-2018 data packet DMP layer as per
/// ANSI E1.31-2018 Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH: usize = 2;

/// The length in bytes of the Vector field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// 4 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
const E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH: usize = 4;

/// The length in bytes of the Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// 1 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
const E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH: usize = 1;

/// The length in bytes of the Last Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// 1 bytes as per ANSI E1.31-2018 Section 4, Table 4-3.
const E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH: usize = 1;

/// The value of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// Section 4, Table 4-1.
const E131_DMP_LAYER_ADDRESS_DATA_FIELD: u8 = 0xa1;

/// The value of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_FIELD: u16 = 0x0000;

/// The value of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// Section 4, Table 4-1.
const E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT: u16 = 0x0001;

/// The size of the ACN root layer preamble, must be 0x0010 bytes as per ANSI E1.31-2018 Section 5.1.
/// Often treated as a usize for comparison or use with arrays however stored as u16 as this represents its field size
/// within a packet and converting u16 -> usize is always safe as len(usize) is always greater than len(u16), usize -> u16 is unsafe.
const E131_PREAMBLE_SIZE: u16 = 0x0010;

/// The size of the ACN root layer postamble, must be 0x0 bytes as per ANSI E1.31-2018 Section 5.2.
const E131_POSTAMBLE_SIZE: u16 = 0x0;

/// The E131 ACN packet identifier field value. Must be 0x41 0x53 0x43 0x2d 0x45 0x31 0x2e 0x31 0x37 0x00 0x00 0x00 as per
/// ANSI E1.31-2018 Section 5.3.
const E131_ACN_PACKET_IDENTIFIER: [u8; 12] = [
    0x41, 0x53, 0x43, 0x2d, 0x45, 0x31, 0x2e, 0x31, 0x37, 0x00, 0x00, 0x00,
];

/// The E131 CID field length in bytes as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
pub const E131_CID_FIELD_LENGTH: usize = 16;

// The exclusive end index of the CID field. Calculated based on previous values defined in ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
const E131_CID_END_INDEX: usize =
    E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH + E131_CID_FIELD_LENGTH;

/// The length of the Source Name field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
pub const E131_SOURCE_NAME_FIELD_LENGTH: usize = 64;

/// The length of the Synchronisation Address field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
pub const E131_SYNC_ADDR_FIELD_LENGTH: usize = 2;

/// The length in bytes of the sequence number field within the framing layer of an E1.31 synchronisation packet.
/// AS per ANSI E1.31-2018 Section 4, Table 4-2.
const E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH: usize = 1;

/// The length in bytes of the reserved field within the framing layer of an E1.31 synchronisation packet.
/// AS per ANSI E1.31-2018 Section 4, Table 4-2.
const E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH: usize = 2;

// The length in bytes of the reserve field in the universe discovery framing layer of an ANSI E1.31-2018 Universe Discovery Packet.
// Length as per ANSI E1.31-2018 Section 4, Table 4-3.
const E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH: usize = 4;

/// The initial/starting sequence number used.
pub const STARTING_SEQUENCE_NUMBER: u8 = 0;

/// The vector field value used to identify the ACN packet as an ANSI E1.31 data packet.
/// This is used at the ACN packet layer not the E1.31 layer.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_ROOT_E131_DATA: u32 = 0x0000_0004;

/// The vector field value used to identify the packet as an ANSI E1.31 universe discovery or synchronisation packet.
/// This is used at the ACN packet layer not the E1.31 layer.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_ROOT_E131_EXTENDED: u32 = 0x0000_0008;

/// The E1.31 packet vector field value used to identify the E1.31 packet as a synchronisation packet.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. VECTOR_ROOT_E131_DATA and VECTOR_ROOT_E131_EXTENDED).
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_E131_EXTENDED_SYNCHRONIZATION: u32 = 0x0000_0001;

/// The E1.31 packet vector field value used to identify the E1.31 packet as a universe discovery packet.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. VECTOR_ROOT_E131_DATA and VECTOR_ROOT_E131_EXTENDED).
/// This VECTOR value is shared by E1.31 data packets, distinguished by the value of the ACN ROOT_VECTOR.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_E131_EXTENDED_DISCOVERY: u32 = 0x0000_0002;

/// The E1.31 packet vector field value used to identify the E1.31 packet as a data packet.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. VECTOR_ROOT_E131_DATA and VECTOR_ROOT_E131_EXTENDED).
/// This VECTOR value is shared by E1.31 universe discovery packets, distinguished by the value of the ACN ROOT_VECTOR.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_E131_DATA_PACKET: u32 = 0x0000_0002;

/// Used at the DMP layer in E1.31 data packets to identify the packet as a set property message.
/// Not to be confused with the other VECTOR values used at the E1.31, ACN etc. layers.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_DMP_SET_PROPERTY: u8 = 0x02;

/// Used at the universe discovery packet universe discovery layer to identify the packet as a universe discovery list of universes.
/// Not to be confused with the other VECTOR values used at the E1.31, ACN, DMP, etc. layers.
/// Value as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
pub const VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST: u32 = 0x0000_0001;

/// The port number used for the ACN family of protocols and therefore the sACN protocol.
/// As defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative)
pub const ACN_SDT_MULTICAST_PORT: u16 = 5568;

/// The payload capacity for a sacn packet, for DMX data this would translate to 512 frames + a startcode byte.
pub const UNIVERSE_CHANNEL_CAPACITY: usize = 513;

/// The synchronisation universe/address of packets which do not require synchronisation as specified in section 6.2.4.1 of ANSI E1.31-2018.
pub const NO_SYNC_UNIVERSE: u16 = 0;

/// The timeout before data loss is assumed for an E131 source, as defined in Appendix A of ANSI E1.31-2018.
pub const E131_NETWORK_DATA_LOSS_TIMEOUT: Duration = Duration::from_millis(2500);

/// The timeout before a discovered source is assumed to be lost as defined in section 12.2 of ANSI E1.31-2018.
pub const UNIVERSE_DISCOVERY_SOURCE_TIMEOUT: Duration = E131_NETWORK_DATA_LOSS_TIMEOUT;

/// Converts the given ANSI E1.31-2018 universe into an Ipv4 multicast address with the port set to the acn multicast port as defined
/// in packet::ACN_SDT_MULTICAST_PORT.
///
/// Conversion done as specified in section 9.3.1 of ANSI E1.31-2018
///
/// Returns the multicast address.
///
/// # Errors
/// IllegalUniverse: Returned if the given universe is outwith the allowed range of universes,
///     see (is_universe_in_range)[fn.is_universe_in_range.packet].
pub fn universe_to_ipv4_multicast_addr(universe: u16) -> Result<SockAddr> {
    is_universe_in_range(universe)?;

    let high_byte: u8 = ((universe >> 8) & 0xff) as u8;
    let low_byte: u8 = (universe & 0xff) as u8;

    // As per ANSI E1.31-2018 Section 9.3.1 Table 9-10.
    Ok(SocketAddr::new(
        IpAddr::V4(Ipv4Addr::new(239, 255, high_byte, low_byte)),
        ACN_SDT_MULTICAST_PORT,
    )
    .into())
}

/// Converts the given ANSI E1.31-2018 universe into an Ipv6 multicast address with the port set to the acn multicast port as defined
/// in packet::ACN_SDT_MULTICAST_PORT.
///
/// Conversion done as specified in section 9.3.2 of ANSI E1.31-2018
///
/// Returns the multicast address.
///
/// # Errors
/// IllegalUniverse: Returned if the given universe is outwith the allowed range of universes,
///     see (is_universe_in_range)[fn.is_universe_in_range.packet].
pub fn universe_to_ipv6_multicast_addr(universe: u16) -> Result<SockAddr> {
    is_universe_in_range(universe)?;

    // As per ANSI E1.31-2018 Section 9.3.2 Table 9-12.
    Ok(SocketAddr::new(
        IpAddr::V6(Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, universe)),
        ACN_SDT_MULTICAST_PORT,
    )
    .into())
}

/// Checks if the given universe is a valid universe to send on (within allowed range).
///
/// # Errors
/// IllegalUniverse: Returned if the universe is outwith the allowed range of universes
///     [E131_MIN_MULTICAST_UNIVERSE, E131_MAX_MULTICAST_UNIVERSE] + E131_DISCOVERY_UNIVERSE.
pub fn is_universe_in_range(universe: u16) -> Result<()> {
    if (universe != E131_DISCOVERY_UNIVERSE)
        && !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE).contains(&universe)
    {
        return Err(SacnError::IllegalUniverse(universe));
    }
    Ok(())
}

/// Fills the given array of bytes with the given length n with bytes of value 0.
#[inline]
fn zeros(buf: &mut [u8], n: usize) {
    for b in buf.iter_mut().take(n) {
        *b = 0;
    }
}

/// Takes the given byte buffer (e.g. a c char array) and parses it into a rust &str.
///
/// # Arguments
/// buf: The byte buffer to parse into a str.
///
/// # Errors
/// SourceNameNotNullTerminated: Returned if the source name is not null terminated as required by ANSI E1.31-2018 Section 6.2.2
#[inline]
fn parse_source_name_str(buf: &[u8]) -> Result<&str> {
    let mut source_name_length = buf.len();
    for (i, b) in buf.iter().enumerate() {
        if *b == 0 {
            source_name_length = i;
            break;
        }
    }

    if source_name_length == buf.len() && buf[buf.len() - 1] != 0 {
        return Err(SacnError::SacnParsePackError(
            ParsePacketError::SourceNameNotNullTerminated(),
        ));
    }

    Ok(str::from_utf8(&buf[..source_name_length])?)
}

macro_rules! impl_acn_root_layer_protocol {
    ( $( $lt:tt )* ) => {
        /// Root layer protocol of the Architecture for Control Networks (ACN) protocol.
        #[derive(Clone, Eq, PartialEq, Hash, Debug)]
        pub struct AcnRootLayerProtocol$( $lt )* {
            /// The PDU this packet carries.
            pub pdu: E131RootLayer$( $lt )*,
        }

        impl$( $lt )* AcnRootLayerProtocol$( $lt )* {
            /// Parse the packet from the given buffer.
            pub fn parse(buf: &[u8]) -> Result<AcnRootLayerProtocol<'_>> {
                if buf.len() <  (E131_PREAMBLE_SIZE as usize) {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInsufficientData(
                            "Insufficient data for ACN root layer preamble".to_string(),
                        ),
                    ));
                }

                // Preamble Size
                if NetworkEndian::read_u16(&buf[0..2]) != E131_PREAMBLE_SIZE {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidData("invalid Preamble Size".to_string()),
                    ));
                }

                // Post-amble Size
                if NetworkEndian::read_u16(&buf[2..4]) != E131_POSTAMBLE_SIZE {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidData("invalid Post-amble Size".to_string()),
                    ));
                }

                // ACN Packet Identifier
                if &buf[4 .. (E131_PREAMBLE_SIZE as usize)] != E131_ACN_PACKET_IDENTIFIER {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidData("invalid ACN packet identifier".to_string()),
                    ));
                }

                // PDU block
                Ok(AcnRootLayerProtocol {
                    pdu: E131RootLayer::parse(&buf[(E131_PREAMBLE_SIZE as usize) ..])?,
                })
            }

            /// Packs the packet into heap allocated memory.
            pub fn pack_alloc(&self) -> Result<Vec<u8>> {
                let mut buf = Vec::with_capacity(self.len());
                self.pack_vec(&mut buf)?;
                Ok(buf)
            }

            /// Packs the packet into the given vector.
            ///
            /// Grows the vector `buf` if necessary.
            pub fn pack_vec(&self, buf: &mut Vec<u8>) -> Result<()> {
                buf.clear();
                buf.resize(self.len(), 0);
                self.pack(buf)
            }

            /// Packs the packet into the given buffer.
            pub fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidData("Invalid ACN packet identifier".to_string())
                    ));
                }

                // Preamble Size
                NetworkEndian::write_u16(&mut buf[0..2], 0x0010);

                // Post-amble Size
                zeros(&mut buf[2..4], 2);

                // ACN Packet Identifier
                buf[4..16].copy_from_slice(b"ASC-E1.17\x00\x00\x00");

                // PDU block
                self.pdu.pack(&mut buf[16..])
            }

            #[allow(clippy::len_without_is_empty)]
            /// The length of the packet when packed.
            pub fn len(&self) -> usize {
                // Preamble Field Size (Bytes)
                2 +
                // Post-amble Field Size (Bytes)
                2 +
                // ACN Packet Identifier Field Size (Bytes)
                E131_ACN_PACKET_IDENTIFIER.len() +
                // PDU block
                self.pdu.len()
            }
        }
    };
}

impl_acn_root_layer_protocol!(<'a>);

/// Represents the data contained with the PduInfo section that appears at the start of a layer in an sACN packet.
struct PduInfo {
    /// The length in bytes of this layer inclusive of the PduInfo.
    length: usize,
    /// The vector which indicates what the layer is, context dependent.
    vector: u32,
}

/// Takes the given byte buffer and parses the flags, length and vector fields into a PduInfo struct.
///
/// # Arguments
/// buf: The raw byte buffer.
///
/// vector_length: The length of the vectorfield in bytes.
///
/// # Errors
/// ParseInsufficientData: If the length of the buffer is less than the flag, length and vector fields (E131_PDU_LENGTH_FLAGS_LENGTH + vector_length).
///
/// ParsePduInvalidFlags: If the flags parsed don't match the flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
fn pdu_info(buf: &[u8], vector_length: usize) -> Result<PduInfo> {
    if buf.len() < E131_PDU_LENGTH_FLAGS_LENGTH + vector_length {
        return Err(SacnError::SacnParsePackError(
            ParsePacketError::ParseInsufficientData(
                "Insufficient data when parsing pdu_info, no flags or length field".to_string(),
            ),
        ));
    }

    // Flags
    let flags = buf[0] & 0xf0; // Flags are stored in the top 4 bits.
    if flags != E131_PDU_FLAGS {
        return Err(SacnError::SacnParsePackError(
            ParsePacketError::ParsePduInvalidFlags(flags),
        ));
    }
    // Length
    let length = (NetworkEndian::read_u16(&buf[0..E131_PDU_LENGTH_FLAGS_LENGTH]) & 0x0fff) as usize;

    // Vector
    let vector =
        NetworkEndian::read_uint(&buf[E131_PDU_LENGTH_FLAGS_LENGTH..], vector_length) as u32;

    Ok(PduInfo { length, vector })
}

trait Pdu: Sized {
    fn parse(buf: &[u8]) -> Result<Self>;

    fn pack(&self, buf: &mut [u8]) -> Result<()>;

    fn len(&self) -> usize;
}

macro_rules! impl_e131_root_layer {
    ( $( $lt:tt )* ) => {
        /// Payload of the Root Layer PDU.
        #[derive(Clone, Eq, PartialEq, Hash, Debug)]
        pub enum E131RootLayerData$( $lt )* {
            /// DMX data packet.
            DataPacket(DataPacketFramingLayer$( $lt )*),

            /// Synchronization packet.
            SynchronizationPacket(SynchronizationPacketFramingLayer),

            /// Universe discovery packet.
            UniverseDiscoveryPacket(UniverseDiscoveryPacketFramingLayer$( $lt )*),
        }

        /// Root layer protocol data unit (PDU).
        #[derive(Clone, Eq, PartialEq, Hash, Debug)]
        pub struct E131RootLayer$( $lt )* {
            /// Sender UUID.
            pub cid: Uuid,
            /// Data carried by the Root Layer PDU.
            pub data: E131RootLayerData$( $lt )*,
        }

        impl$( $lt )* Pdu for E131RootLayer$( $lt )* {
            fn parse(buf: &[u8]) -> Result<E131RootLayer$( $lt )*> {
                // Length and Vector
                let PduInfo { length, vector } = pdu_info(&buf, E131_ROOT_LAYER_VECTOR_LENGTH)?;
                if buf.len() < length {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInsufficientData(
                            "Buffer contains insufficient data based on ACN root layer pdu length field".to_string(),
                        ),
                    ));
                }

                if vector != VECTOR_ROOT_E131_DATA && vector != VECTOR_ROOT_E131_EXTENDED {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::PduInvalidVector(vector),
                    ));
                }

                // CID
                let cid = Uuid::from_slice(&buf[E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH .. E131_CID_END_INDEX])?;

                // Data
                let data = match vector {
                    VECTOR_ROOT_E131_DATA => {
                        E131RootLayerData::DataPacket(DataPacketFramingLayer::parse(&buf[E131_CID_END_INDEX .. length])?)
                    }
                    VECTOR_ROOT_E131_EXTENDED => {
                        let data_buf = &buf[E131_CID_END_INDEX .. length];
                        let PduInfo { length, vector} = pdu_info(&data_buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
                        if buf.len() < length {
                            return Err(SacnError::SacnParsePackError(
                                ParsePacketError::ParseInsufficientData(
                                    "Buffer contains insufficient data based on E131 framing layer pdu length field".to_string(),
                                ),
                            ));
                        }

                        match vector {
                            VECTOR_E131_EXTENDED_SYNCHRONIZATION => {
                                E131RootLayerData::SynchronizationPacket(
                                    SynchronizationPacketFramingLayer::parse(data_buf)?,
                                )
                            }
                            VECTOR_E131_EXTENDED_DISCOVERY => {
                                E131RootLayerData::UniverseDiscoveryPacket(
                                    UniverseDiscoveryPacketFramingLayer::parse(data_buf)?,
                                )
                            }
                            vector => return Err(SacnError::SacnParsePackError(
                                ParsePacketError::PduInvalidVector(vector),
                            )),
                        }
                    }
                    vector => return Err(SacnError::SacnParsePackError(
                                ParsePacketError::PduInvalidVector(vector),
                            )),
                };

                Ok(E131RootLayer {
                    cid,
                    data,
                })
            }

            fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::PackBufferInsufficient("".to_string())
                    ));
                }

                // Flags and Length, flags are stored in the top 4 bits.
                let flags_and_length = NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
                NetworkEndian::write_u16(&mut buf[0 .. E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);

                // Vector
                match self.data {
                    E131RootLayerData::DataPacket(_) => {
                        NetworkEndian::write_u32(&mut buf[E131_PDU_LENGTH_FLAGS_LENGTH .. E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH], VECTOR_ROOT_E131_DATA)
                    }
                    E131RootLayerData::SynchronizationPacket(_)
                    | E131RootLayerData::UniverseDiscoveryPacket(_) => {
                        NetworkEndian::write_u32(&mut buf[E131_PDU_LENGTH_FLAGS_LENGTH .. E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH], VECTOR_ROOT_E131_EXTENDED)
                    }
                }

                // CID
                buf[E131_PDU_LENGTH_FLAGS_LENGTH + E131_ROOT_LAYER_VECTOR_LENGTH .. E131_CID_END_INDEX].copy_from_slice(self.cid.as_bytes());

                // Data
                match self.data {
                    E131RootLayerData::DataPacket(ref data) => Ok(data.pack(&mut buf[E131_CID_END_INDEX .. ])?),
                    E131RootLayerData::SynchronizationPacket(ref data) => Ok(data.pack(&mut buf[E131_CID_END_INDEX .. ])?),
                    E131RootLayerData::UniverseDiscoveryPacket(ref data) => Ok(data.pack(&mut buf[E131_CID_END_INDEX .. ])?),
                }
            }

            fn len(&self) -> usize {
                // Length and Flags
                E131_PDU_LENGTH_FLAGS_LENGTH +
                // Vector
                E131_ROOT_LAYER_VECTOR_LENGTH +
                // CID
                E131_CID_FIELD_LENGTH +
                // Data
                match self.data {
                    E131RootLayerData::DataPacket(ref data) => data.len(),
                    E131RootLayerData::SynchronizationPacket(ref data) => data.len(),
                    E131RootLayerData::UniverseDiscoveryPacket(ref data) => data.len(),
                }
            }
        }
    };
}

impl_e131_root_layer!(<'a>);

macro_rules! impl_data_packet_framing_layer {
    ( $( $lt:tt )* ) => {
        /// Framing layer PDU for sACN data packets.
        #[derive(Eq, PartialEq, Debug)]
        pub struct DataPacketFramingLayer$( $lt )* {
            /// The name of the source.
            pub source_name: Cow<'a, str>,

            /// Priority of this data packet.
            pub priority: u8,

            /// Synchronization address.
            pub synchronization_address: u16,

            /// The sequence number of this packet.
            pub sequence_number: u8,

            /// If this packets data is preview data.
            pub preview_data: bool,

            /// If transmission on this universe is terminated.
            pub stream_terminated: bool,

            /// Force synchronization if no synchronization packets are received.
            pub force_synchronization: bool,

            /// The universe DMX data is transmitted for.
            pub universe: u16,

            /// DMP layer containing the DMX data.
            pub data: DataPacketDmpLayer$( $lt )*,
        }

        // Calculate the indexes of the fields within the buffer based on the size of the fields previous.
        // Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
        // Theses indexes are only valid within the scope of this part of the protocol (DataPacketFramingLayer).
        const SOURCE_NAME_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH + E131_FRAMING_LAYER_VECTOR_LENGTH;
        const PRIORITY_INDEX: usize = SOURCE_NAME_INDEX + E131_SOURCE_NAME_FIELD_LENGTH;
        const SYNC_ADDR_INDEX: usize = PRIORITY_INDEX + E131_PRIORITY_FIELD_LENGTH;
        const SEQ_NUM_INDEX: usize = SYNC_ADDR_INDEX + E131_SYNC_ADDR_FIELD_LENGTH;
        const OPTIONS_FIELD_INDEX: usize = SEQ_NUM_INDEX + E131_SEQ_NUM_FIELD_LENGTH;
        const UNIVERSE_INDEX: usize = OPTIONS_FIELD_INDEX + E131_OPTIONS_FIELD_LENGTH;
        const DATA_INDEX: usize = UNIVERSE_INDEX + E131_UNIVERSE_FIELD_LENGTH;

        impl$( $lt )* Pdu for DataPacketFramingLayer$( $lt )* {
            fn parse(buf: &[u8]) -> Result<DataPacketFramingLayer$( $lt )*> {
                // Length and Vector
                let PduInfo { length, vector } = pdu_info(&buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
                if buf.len() < length {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet framing layer pdu length field".to_string())));
                }

                if vector != VECTOR_E131_DATA_PACKET {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidVector(vector)));
                }

                // Source Name
                let source_name = String::from(
                    parse_source_name_str(
                        &buf[SOURCE_NAME_INDEX .. PRIORITY_INDEX]
                    )?
                );

                // Priority
                let priority = buf[PRIORITY_INDEX];
                if priority > E131_MAX_PRIORITY {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidPriority(priority),
                    ));
                }

                // Synchronization Address
                let synchronization_address = NetworkEndian::read_u16(&buf[SYNC_ADDR_INDEX .. SEQ_NUM_INDEX]);
                if synchronization_address > E131_MAX_MULTICAST_UNIVERSE {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidSyncAddr(synchronization_address),
                    ));
                }

                // Sequence Number
                let sequence_number = buf[SEQ_NUM_INDEX];

                // Options, Stored as bit flag.
                let preview_data = buf[OPTIONS_FIELD_INDEX] & E131_PREVIEW_DATA_OPTION_BIT_MASK != 0;
                let stream_terminated = buf[OPTIONS_FIELD_INDEX] & E131_STREAM_TERMINATION_OPTION_BIT_MASK != 0;
                let force_synchronization = buf[OPTIONS_FIELD_INDEX] & E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK != 0;

                // Universe
                let universe = NetworkEndian::read_u16(&buf[UNIVERSE_INDEX .. DATA_INDEX]);

                if !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE).contains(&universe) {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInvalidUniverse(universe),
                    ));
                }

                // Data layer.
                let data = DataPacketDmpLayer::parse(&buf[DATA_INDEX .. length])?;

                Ok(DataPacketFramingLayer {
                    source_name: source_name.into(),
                    priority,
                    synchronization_address,
                    sequence_number,
                    preview_data,
                    stream_terminated,
                    force_synchronization,
                    universe,
                    data,
                })
            }

            fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PackBufferInsufficient("".to_string())));
                }

                // Flags and Length
                let flags_and_length = NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
                NetworkEndian::write_u16(&mut buf[0.. E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);

                // Vector
                NetworkEndian::write_u32(&mut buf[E131_PDU_LENGTH_FLAGS_LENGTH .. SOURCE_NAME_INDEX], VECTOR_E131_DATA_PACKET);

                // Source Name, padded with 0's up to the required 64 byte length.
                zeros(&mut buf[SOURCE_NAME_INDEX .. PRIORITY_INDEX], E131_SOURCE_NAME_FIELD_LENGTH);
                buf[SOURCE_NAME_INDEX .. SOURCE_NAME_INDEX + self.source_name.len()].copy_from_slice(self.source_name.as_bytes());

                // Priority
                buf[PRIORITY_INDEX] = self.priority;

                // Synchronization Address
                NetworkEndian::write_u16(&mut buf[SYNC_ADDR_INDEX .. SEQ_NUM_INDEX], self.synchronization_address);

                // Sequence Number
                buf[SEQ_NUM_INDEX] = self.sequence_number;

                // Options, zero out all the bits to start including bits 0-4 as per ANSI E1.31-2018 Section 6.2.6.
                buf[OPTIONS_FIELD_INDEX] = 0;

                // Preview Data
                if self.preview_data {
                    buf[OPTIONS_FIELD_INDEX] = E131_PREVIEW_DATA_OPTION_BIT_MASK;
                }

                // Stream Terminated
                if self.stream_terminated {
                    buf[OPTIONS_FIELD_INDEX] |= E131_STREAM_TERMINATION_OPTION_BIT_MASK;
                }

                // Force Synchronization
                if self.force_synchronization {
                    buf[OPTIONS_FIELD_INDEX] |= E131_FORCE_SYNCHRONISATION_OPTION_BIT_MASK;
                }

                // Universe
                NetworkEndian::write_u16(&mut buf[UNIVERSE_INDEX .. DATA_INDEX], self.universe);

                // Data
                self.data.pack(&mut buf[DATA_INDEX .. ])
            }

            fn len(&self) -> usize {
                // Length and Flags
                E131_PDU_LENGTH_FLAGS_LENGTH +
                // Vector
                E131_FRAMING_LAYER_VECTOR_LENGTH +
                // Source Name
                E131_SOURCE_NAME_FIELD_LENGTH +
                // Priority
                E131_PRIORITY_FIELD_LENGTH +
                // Synchronization Address
                E131_SYNC_ADDR_FIELD_LENGTH +
                // Sequence Number
                E131_SEQ_NUM_FIELD_LENGTH +
                // Options
                E131_OPTIONS_FIELD_LENGTH +
                // Universe
                E131_UNIVERSE_FIELD_LENGTH +
                // Data
                self.data.len()
            }
        }

        impl$( $lt )* Clone for DataPacketFramingLayer$( $lt )* {
            fn clone(&self) -> Self {
                DataPacketFramingLayer {
                    source_name: self.source_name.clone(),
                    priority: self.priority,
                    synchronization_address: self.synchronization_address,
                    sequence_number: self.sequence_number,
                    preview_data: self.preview_data,
                    stream_terminated: self.stream_terminated,
                    force_synchronization: self.force_synchronization,
                    universe: self.universe,
                    data: self.data.clone(),
                }
            }
        }

        impl$( $lt )* Hash for DataPacketFramingLayer$( $lt )* {
            #[inline]
            fn hash<H: hash::Hasher>(&self, state: &mut H) {
                (&*self.source_name).hash(state);
                self.priority.hash(state);
                self.synchronization_address.hash(state);
                self.sequence_number.hash(state);
                self.preview_data.hash(state);
                self.stream_terminated.hash(state);
                self.force_synchronization.hash(state);
                self.universe.hash(state);
                self.data.hash(state);
            }
        }
    };
}

impl_data_packet_framing_layer!(<'a>);

macro_rules! impl_data_packet_dmp_layer {
    ( $( $lt:tt )* ) => {
        /// Device Management Protocol PDU with SET PROPERTY vector.
        ///
        /// Used for sACN data packets.
        #[derive(Eq, PartialEq, Debug)]
        pub struct DataPacketDmpLayer$( $lt )* {
            /// DMX data property values (DMX start coder + 512 slots).
            pub property_values: Cow<'a, [u8]>,
        }

        // Calculate the indexes of the fields within the buffer based on the size of the fields previous.
        // Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
        // Theses indexes are only valid within the scope of this part of the protocol (DataPacketDmpLayer).
        const VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
        const ADDRESS_DATA_FIELD_INDEX: usize = VECTOR_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH;
        const FIRST_PRIORITY_FIELD_INDEX: usize = ADDRESS_DATA_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH;
        const ADDRESS_INCREMENT_FIELD_INDEX: usize = FIRST_PRIORITY_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH;
        const PROPERTY_VALUE_COUNT_FIELD_INDEX: usize = ADDRESS_INCREMENT_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH;
        const PROPERTY_VALUES_FIELD_INDEX: usize = PROPERTY_VALUE_COUNT_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH;

        impl$( $lt )* Pdu for DataPacketDmpLayer$( $lt )* {

            fn parse(buf: &[u8]) -> Result<DataPacketDmpLayer$( $lt )*> {
                // Length and Vector
                let PduInfo { length, vector } = pdu_info(&buf, E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH)?;
                if buf.len() < length {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet dmp layer pdu length field".to_string())));
                }

                if vector != u32::from(VECTOR_DMP_SET_PROPERTY) {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidVector(vector)));
                }

                // Address and Data Type
                if buf[ADDRESS_DATA_FIELD_INDEX] != E131_DMP_LAYER_ADDRESS_DATA_FIELD {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInvalidData("invalid Address and Data Type".to_string())));
                }

                // First Property Address
                if NetworkEndian::read_u16(&buf[FIRST_PRIORITY_FIELD_INDEX .. ADDRESS_INCREMENT_FIELD_INDEX]) != E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_FIELD {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInvalidData("invalid First Property Address".to_string())));
                }

                // Address Increment
                if NetworkEndian::read_u16(&buf[ADDRESS_INCREMENT_FIELD_INDEX .. PROPERTY_VALUE_COUNT_FIELD_INDEX]) != E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInvalidData("invalid Address Increment".to_string())));
                }

                // Property value count
                let property_value_count = NetworkEndian::read_u16(&buf[PROPERTY_VALUE_COUNT_FIELD_INDEX .. PROPERTY_VALUES_FIELD_INDEX]);

                // Check that the property value count matches the expected count based on the pdu length given previously.
                if property_value_count as usize + PROPERTY_VALUES_FIELD_INDEX != length {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::ParseInsufficientData(
                            format!("Invalid data packet dmp layer property value count, pdu length indicates {} property values, property value count field indicates {} property values",
                                length , property_value_count)
                            .to_string()
                        )
                    ));
                }

                // Property values
                // The property value length is only of the property values and not the headers so start counting at the index that the property values start.
                let property_values_length = length - PROPERTY_VALUES_FIELD_INDEX;
                if property_values_length > UNIVERSE_CHANNEL_CAPACITY {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInvalidData("only 512 DMX slots allowed".to_string())));
                }

                let mut property_values = Vec::with_capacity(property_values_length);

                property_values.extend_from_slice(&buf[PROPERTY_VALUES_FIELD_INDEX .. length]);

                Ok(DataPacketDmpLayer {
                    property_values: property_values.into(),
                })
            }

            fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if self.property_values.len() > UNIVERSE_CHANNEL_CAPACITY {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PackInvalidData("only 512 DMX values allowed".to_string())));
                }

                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PackBufferInsufficient("DataPacketDmpLayer pack buffer length insufficient".to_string())));
                }

                // Flags and Length
                let flags_and_length = NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
                NetworkEndian::write_u16(&mut buf[0.. E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);

                // Vector
                buf[VECTOR_FIELD_INDEX] = VECTOR_DMP_SET_PROPERTY;

                // Address and Data Type
                buf[ADDRESS_DATA_FIELD_INDEX] = E131_DMP_LAYER_ADDRESS_DATA_FIELD;

                // First Property Address
                zeros(&mut buf[FIRST_PRIORITY_FIELD_INDEX .. ADDRESS_INCREMENT_FIELD_INDEX], E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH);

                // Address Increment
                NetworkEndian::write_u16(&mut buf[ADDRESS_INCREMENT_FIELD_INDEX .. PROPERTY_VALUE_COUNT_FIELD_INDEX], E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT);

                // Property value count
                NetworkEndian::write_u16(&mut buf[PROPERTY_VALUE_COUNT_FIELD_INDEX .. PROPERTY_VALUES_FIELD_INDEX], self.property_values.len() as u16);

                // Property values
                buf[PROPERTY_VALUES_FIELD_INDEX .. PROPERTY_VALUES_FIELD_INDEX + self.property_values.len()].copy_from_slice(&self.property_values);

                Ok(())
            }

            fn len(&self) -> usize {
                // Length and Flags
                E131_PDU_LENGTH_FLAGS_LENGTH +
                // Vector
                E131_DATA_PACKET_DMP_LAYER_VECTOR_FIELD_LENGTH +
                // Address and Data Type
                E131_DATA_PACKET_DMP_LAYER_ADDRESS_DATA_FIELD_LENGTH +
                // First Property Address
                E131_DATA_PACKET_DMP_LAYER_FIRST_PROPERTY_ADDRESS_FIELD_LENGTH +
                // Address Increment
                E131_DATA_PACKET_DMP_LAYER_ADDRESS_INCREMENT_FIELD_LENGTH +
                // Property value count
                E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH +
                // Property values
                self.property_values.len()
            }
        }

        impl$( $lt )* Clone for DataPacketDmpLayer$( $lt )* {
            fn clone(&self) -> Self {
                DataPacketDmpLayer {
                    property_values: self.property_values.clone(),
                }
            }
        }

        impl$( $lt )* Hash for DataPacketDmpLayer$( $lt )* {
            #[inline]
            fn hash<H: hash::Hasher>(&self, state: &mut H) {
                (&*self.property_values).hash(state);
            }
        }
    };
}

impl_data_packet_dmp_layer!(<'a>);

/// sACN synchronization packet PDU.
#[derive(Clone, Eq, PartialEq, Hash, Debug, Copy)]
pub struct SynchronizationPacketFramingLayer {
    /// The sequence number of the packet.
    pub sequence_number: u8,

    /// The address to synchronize.
    pub synchronization_address: u16,
}

// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (SynchronisationPacketFramingLayer).
const E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
const E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX + E131_FRAMING_LAYER_VECTOR_LENGTH;
const E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX + E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH;
const E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX + E131_SYNC_ADDR_FIELD_LENGTH;
const E131_SYNC_FRAMING_LAYER_END_INDEX: usize =
    E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX + E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH;

impl Pdu for SynchronizationPacketFramingLayer {
    fn parse(buf: &[u8]) -> Result<SynchronizationPacketFramingLayer> {
        // Length and Vector
        let PduInfo { length, vector } = pdu_info(buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
        if buf.len() < length {
            return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on synchronisation packet framing layer pdu length field".to_string())));
        }

        if vector != VECTOR_E131_EXTENDED_SYNCHRONIZATION {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PduInvalidVector(vector),
            ));
        }

        if length != E131_UNIVERSE_SYNC_PACKET_FRAMING_LAYER_LENGTH {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PduInvalidLength(length),
            ));
        }

        // Sequence Number
        let sequence_number = buf[E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX];

        // Synchronization Address
        let synchronization_address = NetworkEndian::read_u16(
            &buf[E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX
                ..E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX],
        );

        if !(E131_MIN_MULTICAST_UNIVERSE..=E131_MAX_MULTICAST_UNIVERSE)
            .contains(&synchronization_address)
        {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::ParseInvalidSyncAddr(synchronization_address),
            ));
        }

        // Reserved fields (2 bytes right immediately after the synchronisation address) should be ignored by receivers as per
        // ANSI E1.31-2018 Section 6.3.4.

        Ok(SynchronizationPacketFramingLayer {
            sequence_number,
            synchronization_address,
        })
    }

    fn pack(&self, buf: &mut [u8]) -> Result<()> {
        if buf.len() < self.len() {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::PackBufferInsufficient(
                    "SynchronizationPacketFramingLayer pack buffer length insufficient".to_string(),
                ),
            ));
        }

        // Flags and Length
        let flags_and_length =
            NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
        NetworkEndian::write_u16(&mut buf[0..E131_PDU_LENGTH_FLAGS_LENGTH], flags_and_length);

        // Vector
        NetworkEndian::write_u32(
            &mut buf[E131_SYNC_FRAMING_LAYER_VECTOR_FIELD_INDEX
                ..E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX],
            VECTOR_E131_EXTENDED_SYNCHRONIZATION,
        );

        // Sequence Number
        buf[E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_INDEX] = self.sequence_number;

        // Synchronization Address
        NetworkEndian::write_u16(
            &mut buf[E131_SYNC_FRAMING_LAYER_SYNC_ADDRESS_FIELD_INDEX
                ..E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX],
            self.synchronization_address,
        );

        // Reserved, transmitted as zeros as per ANSI E1.31-2018 Section 6.3.4.
        zeros(
            &mut buf
                [E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_INDEX..E131_SYNC_FRAMING_LAYER_END_INDEX],
            E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH,
        );

        Ok(())
    }

    fn len(&self) -> usize {
        // Length and Flags
        E131_PDU_LENGTH_FLAGS_LENGTH +
        // Vector
        E131_FRAMING_LAYER_VECTOR_LENGTH +
        // Sequence Number
        E131_SYNC_FRAMING_LAYER_SEQ_NUM_FIELD_LENGTH +
        // Synchronization Address
        E131_SYNC_ADDR_FIELD_LENGTH +
        // Reserved
        E131_SYNC_FRAMING_LAYER_RESERVE_FIELD_LENGTH
    }
}

macro_rules! impl_universe_discovery_packet_framing_layer {
    ( $( $lt:tt )* ) => {
        /// Framing layer PDU for sACN universe discovery packets.
        #[derive(Eq, PartialEq, Debug)]
        pub struct UniverseDiscoveryPacketFramingLayer$( $lt )* {
            /// Name of the source.
            pub source_name: Cow<'a, str>,

            /// Universe discovery layer.
            pub data: UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )*,
        }

        // Calculate the indexes of the fields within the buffer based on the size of the fields previous.
        // Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
        // Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketFramingLayer).
        const E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
        const E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX: usize = E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX + E131_FRAMING_LAYER_VECTOR_LENGTH;
        const E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX: usize = E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX + E131_SOURCE_NAME_FIELD_LENGTH;
        const E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX: usize = E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX + E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH;

        impl$( $lt )* Pdu for UniverseDiscoveryPacketFramingLayer$( $lt )* {
            fn parse(buf: &[u8]) -> Result<UniverseDiscoveryPacketFramingLayer$( $lt )*> {
                // Length and Vector
                let PduInfo { length, vector } = pdu_info(&buf, E131_FRAMING_LAYER_VECTOR_LENGTH)?;
                if buf.len() < length {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on universe discovery packet framing layer pdu length field".to_string())));
                }

                if vector != VECTOR_E131_EXTENDED_DISCOVERY {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidVector(vector)));
                }

                if length < E131_UNIVERSE_DISCOVERY_FRAMING_LAYER_MIN_LENGTH {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidLength(length)));
                }

                // Source Name
                let source_name = String::from(parse_source_name_str(&buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX .. E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX])?);

                // Reserved data (immediately after source_name) ignored as per ANSI E1.31-2018 Section 6.4.3.

                // The universe discovery data.
                let data = UniverseDiscoveryPacketUniverseDiscoveryLayer::parse(&buf[E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX .. length])?;

                Ok(UniverseDiscoveryPacketFramingLayer {
                    source_name: source_name.into(),
                    data,
                })
            }

            fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PackBufferInsufficient("UniverseDiscoveryPacketFramingLayer pack buffer length insufficient".to_string())));
                }

                // Flags and Length
                let flags_and_length = NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
                NetworkEndian::write_u16(&mut buf[0 .. E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX], flags_and_length);

                // Vector
                NetworkEndian::write_u32(&mut buf[E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX .. E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX], VECTOR_E131_EXTENDED_DISCOVERY);

                // Source Name
                zeros(&mut buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX .. E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX], E131_SOURCE_NAME_FIELD_LENGTH);
                buf[E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX  .. E131_DISCOVERY_FRAMING_LAYER_SOURCE_NAME_FIELD_INDEX  + self.source_name.len()].copy_from_slice(self.source_name.as_bytes());

                // Reserved
                zeros(&mut buf[E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_INDEX .. E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX], E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH);

                // Data
                self.data.pack(&mut buf[E131_DISCOVERY_FRAMING_LAYER_DATA_INDEX .. ])
            }

            fn len(&self) -> usize {
                // Length and Flags
                E131_PDU_LENGTH_FLAGS_LENGTH +
                // Vector
                E131_FRAMING_LAYER_VECTOR_LENGTH +
                // Source Name
                E131_SOURCE_NAME_FIELD_LENGTH +
                // Reserved
                E131_DISCOVERY_FRAMING_LAYER_RESERVE_FIELD_LENGTH +
                // Data
                self.data.len()
            }
        }

        impl$( $lt )* Clone for UniverseDiscoveryPacketFramingLayer$( $lt )* {
            fn clone(&self) -> Self {
                UniverseDiscoveryPacketFramingLayer {
                    source_name: self.source_name.clone(),
                    data: self.data.clone(),
                }
            }
        }

        impl$( $lt )* Hash for UniverseDiscoveryPacketFramingLayer$( $lt )* {
            #[inline]
            fn hash<H: hash::Hasher>(&self, state: &mut H) {
                (&*self.source_name).hash(state);
                self.data.hash(state);
            }
        }
    };
}

impl_universe_discovery_packet_framing_layer!(<'a>);

macro_rules! impl_universe_discovery_packet_universe_discovery_layer {
    ( $( $lt:tt )* ) => {
        /// Universe discovery layer PDU.
        #[derive(Eq, PartialEq, Debug)]
        pub struct UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )* {
            /// Current page of the discovery packet.
            pub page: u8,

            /// The number of the final page.
            pub last_page: u8,

            /// List of universes.
            pub universes: Cow<'a, [u16]>,
        }

        // Calculate the indexes of the fields within the buffer based on the size of the fields previous.
        // Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
        // Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketUniverseDiscoveryLayer).
        const E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH;
        const E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX: usize = E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX + E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH;
        const E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX: usize = E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX + E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH;
        const E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX: usize = E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX + E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH;

        impl$( $lt )* Pdu for UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )* {
            fn parse(buf: &[u8]) -> Result<UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )*> {
                // Length and Vector
                let PduInfo { length, vector } = pdu_info(&buf, E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH)?;
                if buf.len() != length {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData(
                        format!("Buffer contains incorrect amount of data ({} bytes) based on universe discovery packet universe discovery layer pdu length field ({} bytes)"
                        , buf.len() ,length).to_string())));
                }

                if vector != VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidVector(vector)));
                }

                if !(E131_UNIVERSE_DISCOVERY_LAYER_MIN_LENGTH..=E131_UNIVERSE_DISCOVERY_LAYER_MAX_LENGTH).contains(&length) {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::PduInvalidLength(length)));
                }

                // Page
                let page = buf[E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX];

                // Last Page
                let last_page = buf[E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX];

                if page > last_page {
                    return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInvalidPage("Page value higher than last_page".to_string())));
                }

                // The number of universes, calculated by dividing the remaining space in the packet by the size of a single universe.
                let universes_length = (length - E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX) / E131_UNIVERSE_FIELD_LENGTH;
                let universes: Cow<'a, [u16]> = parse_universe_list(&buf[E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX ..], universes_length)?;

                Ok(UniverseDiscoveryPacketUniverseDiscoveryLayer {
                    page,
                    last_page,
                    universes,
                })
            }

            fn pack(&self, buf: &mut [u8]) -> Result<()> {
                if self.universes.len() > DISCOVERY_UNI_PER_PAGE {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::PackInvalidData(
                            format!("Maximum {} universes allowed per discovery page", DISCOVERY_UNI_PER_PAGE).to_string())));
                }

                if buf.len() < self.len() {
                    return Err(SacnError::SacnParsePackError(
                        ParsePacketError::PackBufferInsufficient("UniverseDiscoveryPacketUniverseDiscoveryLayer pack buffer insufficient".to_string())));
                }

                // Flags and Length
                let flags_and_length = NetworkEndian::read_u16(&[E131_PDU_FLAGS, 0x0]) | (self.len() as u16) & 0x0fff;
                NetworkEndian::write_u16(&mut buf[0 .. E131_DISCOVERY_FRAMING_LAYER_VECTOR_FIELD_INDEX], flags_and_length);

                // Vector
                NetworkEndian::write_u32(&mut buf[E131_DISCOVERY_LAYER_VECTOR_FIELD_INDEX .. E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX], VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST);

                // Page
                buf[E131_DISCOVERY_LAYER_PAGE_FIELD_INDEX] = self.page;

                // Last Page
                buf[E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_INDEX] = self.last_page;

                // Universes
                for i in 1..self.universes.len() {
                    if self.universes[i] == self.universes[i - 1] {
                        return Err(SacnError::SacnParsePackError(ParsePacketError::PackInvalidData("Universes are not unique".to_string())));
                    }
                    if self.universes[i] <= self.universes[i - 1] {
                        return Err(SacnError::SacnParsePackError(ParsePacketError::PackInvalidData("Universes are not sorted".to_string())));
                    }
                }
                NetworkEndian::write_u16_into(
                    &self.universes[..self.universes.len()],
                    &mut buf[E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX .. E131_DISCOVERY_LAYER_UNIVERSE_LIST_FIELD_INDEX + self.universes.len() * E131_UNIVERSE_FIELD_LENGTH],
                );

                Ok(())
            }

            fn len(&self) -> usize {
                // Length and Flags
                E131_PDU_LENGTH_FLAGS_LENGTH +
                // Vector
                E131_DISCOVERY_LAYER_VECTOR_FIELD_LENGTH +
                // Page
                E131_DISCOVERY_LAYER_PAGE_FIELD_LENGTH +
                // Last Page
                E131_DISCOVERY_LAYER_LAST_PAGE_FIELD_LENGTH +
                // Universes
                self.universes.len() * E131_UNIVERSE_FIELD_LENGTH
            }
        }

        impl$( $lt )* Clone for UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )* {
            fn clone(&self) -> Self {
                UniverseDiscoveryPacketUniverseDiscoveryLayer {
                    page: self.page,
                    last_page: self.last_page,
                    universes: self.universes.clone(),
                }
            }
        }

        impl$( $lt )* Hash for UniverseDiscoveryPacketUniverseDiscoveryLayer$( $lt )* {
            #[inline]
            fn hash<H: hash::Hasher>(&self, state: &mut H) {
                self.page.hash(state);
                self.last_page.hash(state);
                (&*self.universes).hash(state);
            }
        }
    };
}

/// Takes the given buffer representing the "List of Universe" field in an ANSI E1.31-2018 discovery packet and parses it into the universe values.
///
/// This enforces the requirement from ANSI E1.31-2018 Section 8.5 that the universes must be numerically sorted.
///
/// # Arguments
/// buf: The byte buffer to parse into the universe.
/// length: The number of universes to attempt to parse from the buffer.
///
/// # Errors
/// ParseInvalidUniverseOrder: If the universes are not sorted in ascending order with no duplicates.
///
/// ParseInsufficientData: If the buffer doesn't contain sufficient bytes and so cannot be parsed into the specified number of u16 universes.
fn parse_universe_list<'a>(buf: &[u8], length: usize) -> Result<Cow<'a, [u16]>> {
    let mut universes: Vec<u16> = Vec::with_capacity(length);
    let mut i = 0;

    // Last_universe starts as a placeholder value that is guaranteed to be less than the lowest possible advertised universe.
    // Cannot use 0 even though under ANSI E1.31-2018 it cannot be used for data or as a sync_address as it is reserved for future use
    // so may be used in future.
    let mut last_universe: i32 = -1;

    if buf.len() < length * E131_UNIVERSE_FIELD_LENGTH {
        return Err(SacnError::SacnParsePackError(
            ParsePacketError::ParseInsufficientData(
                format!("The given buffer of length {} bytes cannot be parsed into the given number of universes {}", buf.len(), length).to_string())));
    }

    while i < (length * E131_UNIVERSE_FIELD_LENGTH) {
        let u = NetworkEndian::read_u16(&buf[i..i + E131_UNIVERSE_FIELD_LENGTH]);

        if (u as i32) > last_universe {
            // Enforce assending ordering of universes as per ANSI E1.31-2018 Section 8.5.
            universes.push(u);
            last_universe = u as i32;
            i += E131_UNIVERSE_FIELD_LENGTH; // Jump to the next universe.
        } else {
            return Err(SacnError::SacnParsePackError(
                ParsePacketError::ParseInvalidUniverseOrder(
                    format!("Universe {u} is out of order, discovery packet universe list must be in accending order!").to_string())));
        }
    }

    Ok(universes.into())
}

impl_universe_discovery_packet_universe_discovery_layer!(<'a>);

#[cfg(test)]
mod test {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};

    /// The universe_to tests below check that the conversion from a universe to an IPv6 or IPv4 multicast address is done as
    /// per ANSI E1.31-2018 Section 9.3.1 Table 9-10 (IPv4) and ANSI E1.31-2018 Section 9.3.2 Table 9-11 + Table 9-12.
    #[test]
    fn test_universe_to_ipv4_lowest_byte_normal() {
        let val: u16 = 119;
        let res = universe_to_ipv4_multicast_addr(val).unwrap();
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());

        assert_eq!(
            res.as_socket_ipv4().unwrap(),
            SocketAddrV4::new(
                Ipv4Addr::new(239, 255, (val / 256) as u8, (val % 256) as u8),
                ACN_SDT_MULTICAST_PORT
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv4_both_bytes_normal() {
        let val: u16 = 300;
        let res = universe_to_ipv4_multicast_addr(val).unwrap();
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());

        assert_eq!(
            res.as_socket_ipv4().unwrap(),
            SocketAddrV4::new(
                Ipv4Addr::new(239, 255, (val / 256) as u8, (val % 256) as u8),
                ACN_SDT_MULTICAST_PORT
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv4_limit_high() {
        let res = universe_to_ipv4_multicast_addr(E131_MAX_MULTICAST_UNIVERSE).unwrap();
        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());

        assert_eq!(
            res.as_socket_ipv4().unwrap(),
            SocketAddrV4::new(
                Ipv4Addr::new(
                    239,
                    255,
                    (E131_MAX_MULTICAST_UNIVERSE / 256) as u8,
                    (E131_MAX_MULTICAST_UNIVERSE % 256) as u8
                ),
                ACN_SDT_MULTICAST_PORT
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv4_limit_low() {
        let res = universe_to_ipv4_multicast_addr(E131_MIN_MULTICAST_UNIVERSE).unwrap();

        assert!(res.as_socket_ipv4().unwrap().ip().is_multicast());

        assert_eq!(
            res.as_socket_ipv4().unwrap(),
            SocketAddrV4::new(
                Ipv4Addr::new(
                    239,
                    255,
                    (E131_MIN_MULTICAST_UNIVERSE / 256) as u8,
                    (E131_MIN_MULTICAST_UNIVERSE % 256) as u8
                ),
                ACN_SDT_MULTICAST_PORT
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv4_out_range_low() {
        match universe_to_ipv4_multicast_addr(0) {
            Ok(_) => assert!(
                false,
                "Universe to ipv4 multicast allowed below minimum allowed universe"
            ),
            Err(e) => match e {
                SacnError::IllegalUniverse(_) => assert!(true),
                _ => assert!(false, "Unexpected error type returned"),
            },
        }
    }

    #[test]
    fn test_universe_to_ip_ipv4_out_range_high() {
        match universe_to_ipv4_multicast_addr(E131_MAX_MULTICAST_UNIVERSE + 10) {
            Ok(_) => assert!(
                false,
                "Universe to ipv4 multicast allowed above maximum allowed universe"
            ),
            Err(e) => match e {
                SacnError::IllegalUniverse(_) => assert!(true),
                _ => assert!(false, "Unexpected error type returned"),
            },
        }
    }

    #[test]
    fn test_universe_to_ipv6_lowest_byte_normal() {
        let val: u16 = 119;
        let res = universe_to_ipv6_multicast_addr(val).unwrap();

        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());

        let low_16: u16 = (((val / 256) as u16) << 8) | ((val % 256) as u16);

        assert_eq!(
            res.as_socket_ipv6().unwrap(),
            SocketAddrV6::new(
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
                ACN_SDT_MULTICAST_PORT,
                0,
                0
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv6_both_bytes_normal() {
        let val: u16 = 300;
        let res = universe_to_ipv6_multicast_addr(val).unwrap();

        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());

        let low_16: u16 = (((val / 256) as u16) << 8) | ((val % 256) as u16);

        assert_eq!(
            res.as_socket_ipv6().unwrap(),
            SocketAddrV6::new(
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
                ACN_SDT_MULTICAST_PORT,
                0,
                0
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv6_limit_high() {
        let res = universe_to_ipv6_multicast_addr(E131_MAX_MULTICAST_UNIVERSE).unwrap();

        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());

        let low_16: u16 = (((E131_MAX_MULTICAST_UNIVERSE / 256) as u16) << 8)
            | ((E131_MAX_MULTICAST_UNIVERSE % 256) as u16);

        assert_eq!(
            res.as_socket_ipv6().unwrap(),
            SocketAddrV6::new(
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
                ACN_SDT_MULTICAST_PORT,
                0,
                0
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv6_limit_low() {
        let res = universe_to_ipv6_multicast_addr(E131_MIN_MULTICAST_UNIVERSE).unwrap();

        assert!(res.as_socket_ipv6().unwrap().ip().is_multicast());

        let low_16: u16 = (((E131_MIN_MULTICAST_UNIVERSE / 256) as u16) << 8)
            | ((E131_MIN_MULTICAST_UNIVERSE % 256) as u16);

        assert_eq!(
            res.as_socket_ipv6().unwrap(),
            SocketAddrV6::new(
                Ipv6Addr::new(0xFF18, 0, 0, 0, 0, 0, 0x8300, low_16),
                ACN_SDT_MULTICAST_PORT,
                0,
                0
            )
        );
    }

    #[test]
    fn test_universe_to_ip_ipv6_out_range_low() {
        match universe_to_ipv6_multicast_addr(0) {
            Ok(_) => assert!(
                false,
                "Universe to ipv4 multicast allowed below minimum allowed universe"
            ),
            Err(e) => match e {
                SacnError::IllegalUniverse(_) => assert!(true),
                _ => assert!(false, "Unexpected error type returned"),
            },
        }
    }

    #[test]
    fn test_universe_to_ip_ipv6_out_range_high() {
        match universe_to_ipv6_multicast_addr(E131_MAX_MULTICAST_UNIVERSE + 10) {
            Ok(_) => assert!(
                false,
                "Universe to ipv4 multicast allowed above maximum allowed universe"
            ),
            Err(e) => match e {
                SacnError::IllegalUniverse(_) => assert!(true),
                _ => assert!(false, "Unexpected error type returned"),
            },
        }
    }

    /// Verifies that the parameters are set correctly as per ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
    /// This test is particularly useful at the maintenance stage as it will flag up if any protocol defined constant is changed.
    #[test]
    fn check_ansi_e131_2018_parameter_values() {
        assert_eq!(VECTOR_ROOT_E131_DATA, 0x0000_0004);
        assert_eq!(VECTOR_ROOT_E131_EXTENDED, 0x0000_0008);
        assert_eq!(VECTOR_DMP_SET_PROPERTY, 0x02);
        assert_eq!(VECTOR_E131_DATA_PACKET, 0x0000_0002);
        assert_eq!(VECTOR_E131_EXTENDED_SYNCHRONIZATION, 0x0000_0001);
        assert_eq!(VECTOR_E131_EXTENDED_DISCOVERY, 0x0000_0002);
        assert_eq!(VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST, 0x0000_0001);
        assert_eq!(E131_UNIVERSE_DISCOVERY_INTERVAL, Duration::from_secs(10));
        assert_eq!(E131_NETWORK_DATA_LOSS_TIMEOUT, Duration::from_millis(2500));
        assert_eq!(E131_DISCOVERY_UNIVERSE, 64214);
        assert_eq!(ACN_SDT_MULTICAST_PORT, 5568);
    }
}