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
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
// Copyright (C) 2020 Matthew Waters <matthew@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.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.

//! STUN Attributes
//!
//! Provides for generating, parsing and manipulating STUN attributes as specified in one of
//! [RFC8489], [RFC5389], or [RFC3489].
//!
//! [RFC8489]: https://tools.ietf.org/html/rfc8489
//! [RFC5389]: https://tools.ietf.org/html/rfc5389
//! [RFC3489]: https://tools.ietf.org/html/rfc3489

use std::convert::TryFrom;
use std::convert::TryInto;

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};

use crate::stun::agent::StunError;
use crate::stun::message::{TransactionId, MAGIC_COOKIE};

use byteorder::{BigEndian, ByteOrder};

// 0x0000 is reserved
pub const MAPPED_ADDRESS: AttributeType = AttributeType(0x0001);
// 0x0002 is reserved, was RESPONSE-ADDRESS
// 0x0003 is reserved, was CHANGE-ADDRESS
// 0x0004 is reserved, was SOURCE-ADDRESS
// 0x0005 is reserved, was CHANGED-ADDRESS
pub const USERNAME: AttributeType = AttributeType(0x0006);
// 0x0007 is reserved, was PASSWORD
pub const MESSAGE_INTEGRITY: AttributeType = AttributeType(0x0008);
pub const ERROR_CODE: AttributeType = AttributeType(0x0009);
pub const UNKNOWN_ATTRIBUTES: AttributeType = AttributeType(0x000A);
// 0x000B is reserved, was REFLECTED_FROM
pub const REALM: AttributeType = AttributeType(0x0014);
pub const NONCE: AttributeType = AttributeType(0x0015);
pub const XOR_MAPPED_ADDRESS: AttributeType = AttributeType(0x0020);

pub const SOFTWARE: AttributeType = AttributeType(0x8022);
pub const ALTERNATE_SERVER: AttributeType = AttributeType(0x8023);
pub const FINGERPRINT: AttributeType = AttributeType(0x8028);

// RFC 8445
pub const PRIORITY: AttributeType = AttributeType(0x0024);
pub const USE_CANDIDATE: AttributeType = AttributeType(0x0025);

pub const ICE_CONTROLLED: AttributeType = AttributeType(0x0029);
pub const ICE_CONTROLLING: AttributeType = AttributeType(0x002A);

#[derive(Debug)]
pub enum StunParseError {
    Failed,
    WrongImplementation,
    NotEnoughData,
    TooBig,
    InvalidData,
    OutOfRange,
}

impl std::error::Error for StunParseError {}

impl std::fmt::Display for StunParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// The type of an [`Attribute`] in a STUN [`Message`](crate::stun::message::Message)
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AttributeType(u16);

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

impl AttributeType {
    /// Create a new AttributeType from an existing value
    ///
    /// Note: the value passed in is not encoded as in a stun message
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::AttributeType;
    /// assert_eq!(AttributeType::new(0x123).value(), 0x123);
    /// ```
    pub fn new(val: u16) -> Self {
        Self(val)
    }

    /// Return the integer value of this AttributeType
    ///
    /// Note: the value returned is not encoded as in a stun message
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::AttributeType;
    /// assert_eq!(AttributeType::new(0x123).value(), 0x123);
    /// ```
    pub fn value(&self) -> u16 {
        self.0
    }

    /// Returns a human readable name of this `AttributeType` or "unknown"
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::XOR_MAPPED_ADDRESS;
    /// assert_eq!(XOR_MAPPED_ADDRESS.name(), "XOR-MAPPED-ADDRESS");
    /// ```
    pub fn name(self) -> &'static str {
        match self {
            MAPPED_ADDRESS => "MAPPED-ADDRESS",
            USERNAME => "USERNAME",
            MESSAGE_INTEGRITY => "MESSAGE-INTEGRITY",
            ERROR_CODE => "ERROR-CODE",
            UNKNOWN_ATTRIBUTES => "UNKNOWN-ATTRIBUTES",
            REALM => "REALM",
            NONCE => "NONCE",
            XOR_MAPPED_ADDRESS => "XOR-MAPPED-ADDRESS",
            SOFTWARE => "SOFTWARE",
            ALTERNATE_SERVER => "ALTERNATE-SERVER",
            FINGERPRINT => "FINGERPRINT",
            PRIORITY => "PRIORITY",
            USE_CANDIDATE => "USE-CANDIDATE",
            ICE_CONTROLLED => "ICE-CONTROLLED",
            ICE_CONTROLLING => "ICE-CONTROLLING",
            _ => "unknown",
        }
    }

    /// Check if comprehension is required for an `AttributeType`.  All integer attribute
    /// values < 0x800 require comprehension.
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::AttributeType;
    /// assert_eq!(AttributeType::new(0x0).comprehension_required(), true);
    /// assert_eq!(AttributeType::new(0x8000).comprehension_required(), false);
    /// ```
    pub fn comprehension_required(self) -> bool {
        self.0 < 0x8000
    }
}
impl From<u16> for AttributeType {
    fn from(f: u16) -> Self {
        Self::new(f)
    }
}
impl From<AttributeType> for u16 {
    fn from(f: AttributeType) -> Self {
        f.0
    }
}

/// Structure for holding the header of a STUN attribute.  Contains the type and the length
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct AttributeHeader {
    pub atype: AttributeType,
    pub length: u16,
}

impl AttributeHeader {
    fn parse(data: &[u8]) -> Result<Self, StunParseError> {
        if data.len() < 4 {
            return Err(StunParseError::NotEnoughData);
        }
        let ret = Self {
            atype: BigEndian::read_u16(&data[0..2]).into(),
            length: BigEndian::read_u16(&data[2..4]),
        };
        //trace!("parsed {:?} into {:?}", data, ret);
        Ok(ret)
    }

    fn to_bytes(self) -> Vec<u8> {
        let mut ret = vec![0; 4];
        BigEndian::write_u16(&mut ret[0..2], self.atype.into());
        BigEndian::write_u16(&mut ret[2..4], self.length);
        ret
    }
}
impl From<AttributeHeader> for Vec<u8> {
    fn from(f: AttributeHeader) -> Self {
        f.to_bytes()
    }
}
impl TryFrom<&[u8]> for AttributeHeader {
    type Error = StunParseError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        AttributeHeader::parse(value)
    }
}

/// A STUN attribute for use in [`Message`](crate::stun::message::Message)s
pub trait Attribute: std::fmt::Debug {
    /// Retrieve the `AttributeType` of an `Attribute`
    fn get_type(&self) -> AttributeType;

    /// Retrieve the length of an `Attribute`.  This is not the padded length as stored in a
    /// `Message`
    fn length(&self) -> u16;

    /// Convert an `Attribute` to a `RawAttribute`
    fn to_raw(&self) -> RawAttribute;

    /// Convert an `Attribute` from a `RawAttribute`
    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError>
    where
        Self: Sized;
}

/// The header and raw bytes of an unparsed [`Attribute`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawAttribute {
    /// The [`AttributeHeader`] of this [`RawAttribute`]
    pub header: AttributeHeader,
    /// The raw bytes of this [`RawAttribute`]
    pub value: Vec<u8>,
}

macro_rules! display_attr {
    ($this:ident, $CamelType:ty, $default:ident) => {{
        if let Ok(attr) = <$CamelType>::from_raw($this) {
            format!("{}", attr)
        } else {
            $default
        }
    }};
}

impl std::fmt::Display for RawAttribute {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // try to get a more specialised display
        let malformed_str = format!(
            "{}(Malformed): len: {}, data: {:?})",
            self.get_type(),
            self.header.length,
            self.value
        );
        let display_str = if self.get_type() == SOFTWARE {
            display_attr!(self, Software, malformed_str)
        } else if self.get_type() == UNKNOWN_ATTRIBUTES {
            display_attr!(self, UnknownAttributes, malformed_str)
        } else if self.get_type() == ERROR_CODE {
            display_attr!(self, ErrorCode, malformed_str)
        } else if self.get_type() == USERNAME {
            display_attr!(self, Username, malformed_str)
        } else if self.get_type() == XOR_MAPPED_ADDRESS {
            display_attr!(self, XorMappedAddress, malformed_str)
        } else if self.get_type() == PRIORITY {
            display_attr!(self, Priority, malformed_str)
        } else if self.get_type() == USE_CANDIDATE {
            display_attr!(self, UseCandidate, malformed_str)
        } else if self.get_type() == ICE_CONTROLLED {
            display_attr!(self, IceControlled, malformed_str)
        } else if self.get_type() == ICE_CONTROLLING {
            display_attr!(self, IceControlling, malformed_str)
        } else if self.get_type() == MESSAGE_INTEGRITY {
            display_attr!(self, MessageIntegrity, malformed_str)
        } else if self.get_type() == FINGERPRINT {
            display_attr!(self, Fingerprint, malformed_str)
        } else {
            format!(
                "RawAttribute (type: {:?}, len: {}, data: {:?})",
                self.header.atype, self.header.length, &self.value
            )
        };
        write!(f, "{}", display_str)
    }
}

impl Attribute for RawAttribute {
    fn length(&self) -> u16 {
        self.header.length
    }

    fn get_type(&self) -> AttributeType {
        self.header.atype
    }

    fn to_raw(&self) -> RawAttribute {
        self.clone()
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        Ok(raw.clone())
    }
}

impl RawAttribute {
    pub fn new(atype: AttributeType, data: &[u8]) -> Self {
        Self {
            header: AttributeHeader {
                atype,
                length: data.len() as u16,
            },
            value: data.to_vec(),
        }
    }

    /// Deserialize a `RawAttribute` from bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::{RawAttribute, Attribute, AttributeType};
    /// let data = &[0, 1, 0, 2, 5, 6, 0, 0];
    /// let attr = RawAttribute::from_bytes(data).unwrap();
    /// assert_eq!(attr.get_type(), AttributeType::new(1));
    /// assert_eq!(attr.length(), 2);
    /// ```
    pub fn from_bytes(data: &[u8]) -> Result<Self, StunParseError> {
        let header = AttributeHeader::parse(data)?;
        // the advertised length is larger than actual data -> error
        if header.length > (data.len() - 4) as u16 {
            return Err(StunParseError::NotEnoughData);
        }
        let mut data = data[4..].to_vec();
        data.truncate(header.length as usize);
        //trace!("parsed into {:?} {:?}", header, data);
        Ok(Self {
            header,
            value: data,
        })
    }

    /// Serialize a `RawAttribute` to bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::{RawAttribute, Attribute, AttributeType};
    /// let attr = RawAttribute::new(AttributeType::new(1), &[5, 6]);
    /// assert_eq!(attr.to_bytes(), &[0, 1, 0, 2, 5, 6, 0, 0]);
    /// ```
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut ret: Vec<u8> = self.header.into();
        ret.extend(&self.value);
        let len = ret.len();
        if len % 4 != 0 {
            // pad to 4 bytes
            ret.resize(len + 4 - (len % 4), 0);
        }
        ret
    }
}
impl From<RawAttribute> for Vec<u8> {
    fn from(f: RawAttribute) -> Self {
        f.to_bytes()
    }
}

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

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        RawAttribute::from_bytes(value)
    }
}

/// The username [`Attribute`]
#[derive(Debug, Clone)]
pub struct Username {
    user: String,
}
impl Attribute for Username {
    fn get_type(&self) -> AttributeType {
        USERNAME
    }

    fn length(&self) -> u16 {
        self.user.len() as u16
    }

    fn to_raw(&self) -> RawAttribute {
        RawAttribute::new(self.get_type(), self.user.as_bytes())
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != USERNAME {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() > 513 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            user: std::str::from_utf8(&raw.value)
                .map_err(|_| StunParseError::InvalidData)?
                .to_owned(),
        })
    }
}

impl Username {
    /// Create a new [`Username`] [`Attribute`]
    ///
    /// # Errors
    ///
    /// - When the length of the username is longer than allowed in a STUN
    /// [`Message`](crate::stun::message::Message)
    /// - TODO: If converting through SASLPrep fails
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let username = Username::new ("user").unwrap();
    /// assert_eq!(username.username(), "user");
    /// ```
    pub fn new(user: &str) -> Result<Self, StunParseError> {
        if user.len() > 513 {
            return Err(StunParseError::TooBig);
        }
        // TODO: SASLPrep RFC4013 requirements
        Ok(Self {
            user: user.to_owned(),
        })
    }

    /// The username stored in a [`Username`] [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let username = Username::new ("user").unwrap();
    /// assert_eq!(username.username(), "user");
    /// ```
    pub fn username(&self) -> &str {
        &self.user
    }
}

impl std::fmt::Display for Username {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: '{}'", self.get_type(), self.user)
    }
}
impl TryFrom<&RawAttribute> for Username {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        Username::from_raw(value)
    }
}

impl From<Username> for RawAttribute {
    fn from(f: Username) -> Self {
        f.to_raw()
    }
}

/// The ErrorCode [`Attribute`]
#[derive(Debug, Clone)]
pub struct ErrorCode {
    code: u16,
    reason: String,
}
impl Attribute for ErrorCode {
    fn get_type(&self) -> AttributeType {
        ERROR_CODE
    }

    fn length(&self) -> u16 {
        self.reason.len() as u16 + 4
    }

    fn to_raw(&self) -> RawAttribute {
        let mut data = Vec::with_capacity(self.length() as usize);
        data.push(0u8);
        data.push(0u8);
        data.push((self.code / 100) as u8);
        data.push((self.code % 100) as u8);
        data.extend(self.reason.as_bytes());
        RawAttribute::new(self.get_type(), &data)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != ERROR_CODE {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 4 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 763 + 4 {
            return Err(StunParseError::TooBig);
        }
        let code_h = (raw.value[2] & 0x7) as u16;
        let code_tens = raw.value[3] as u16;
        if !(3..7).contains(&code_h) || code_tens > 99 {
            return Err(StunParseError::OutOfRange);
        }
        let code = code_h * 100 + code_tens;
        Ok(Self {
            code,
            reason: std::str::from_utf8(&raw.value[4..])
                .map_err(|_| StunParseError::InvalidData)?
                .to_owned(),
        })
    }
}

pub struct ErrorCodeBuilder<'reason> {
    code: u16,
    reason: Option<&'reason str>,
}

impl<'reason> ErrorCodeBuilder<'reason> {
    fn new(code: u16) -> Self {
        Self { code, reason: None }
    }

    /// Set the custom reason for this [`ErrorCode`]
    pub fn reason(mut self, reason: &'reason str) -> Self {
        self.reason = Some(reason);
        self
    }

    /// Create the [`ErrorCode`] with the configured paramaters
    ///
    /// # Errors
    ///
    /// - When the code value is out of range [300, 699]
    pub fn build(self) -> Result<ErrorCode, StunParseError> {
        if !(300..700).contains(&self.code) {
            return Err(StunParseError::OutOfRange);
        }
        let reason = self
            .reason
            .unwrap_or_else(|| ErrorCode::default_reason_for_code(self.code))
            .to_owned();
        Ok(ErrorCode {
            code: self.code,
            reason,
        })
    }
}

impl ErrorCode {
    pub const TRY_ALTERNATE: u16 = 301;
    pub const BAD_REQUEST: u16 = 400;
    pub const UNAUTHORIZED: u16 = 401;
    pub const UNKNOWN_ATRIBUTE: u16 = 420;
    pub const STALE_NONCE: u16 = 438;
    pub const SERVER_ERROR: u16 = 500;
    pub const ROLE_CONFLICT: u16 = 487;

    /// Create a builder for creating a new [`ErrorCode`] [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let error = ErrorCode::builder (400).reason("bad error").build().unwrap();
    /// assert_eq!(error.code(), 400);
    /// assert_eq!(error.reason(), "bad error");
    /// ```
    pub fn builder<'reason>(code: u16) -> ErrorCodeBuilder<'reason> {
        ErrorCodeBuilder::new(code)
    }

    /// Create a new [`ErrorCode`] [`Attribute`]
    ///
    /// # Errors
    ///
    /// - When the code value is out of range [300, 699]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let error = ErrorCode::new (400, "bad error").unwrap();
    /// assert_eq!(error.code(), 400);
    /// assert_eq!(error.reason(), "bad error");
    /// ```
    pub fn new(code: u16, reason: &str) -> Result<Self, StunParseError> {
        if !(300..700).contains(&code) {
            return Err(StunParseError::OutOfRange);
        }
        Ok(Self {
            code,
            reason: reason.to_owned(),
        })
    }

    /// The error code value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let error = ErrorCode::new (400, "bad error").unwrap();
    /// assert_eq!(error.code(), 400);
    /// ```
    pub fn code(&self) -> u16 {
        self.code
    }

    /// The error code reason string
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let error = ErrorCode::new (400, "bad error").unwrap();
    /// assert_eq!(error.reason(), "bad error");
    /// ```
    pub fn reason(&self) -> &str {
        &self.reason
    }

    /// Return some default reason strings for some error code values
    ///
    /// Currently the following are supported.
    ///
    ///  - 301 -> Try Alternate
    ///  - 400 -> Bad Request
    ///  - 401 -> Unauthorized
    ///  - 420 -> Unknown Attribute
    ///  - 438 -> Stale Nonce
    ///  - 500 -> Server Error
    ///  - 487 -> Role Conflict
    pub fn default_reason_for_code(code: u16) -> &'static str {
        match code {
            Self::TRY_ALTERNATE => "Try Alternate",
            Self::BAD_REQUEST => "Bad Request",
            Self::UNAUTHORIZED => "Unauthorized",
            Self::UNKNOWN_ATRIBUTE => "Unknown Attribute",
            Self::STALE_NONCE => "Stale Nonce",
            Self::SERVER_ERROR => "Server Error",
            // RFC 8445
            Self::ROLE_CONFLICT => "Role Conflict",
            _ => "Unknown",
        }
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {} '{}'", self.get_type(), self.code, self.reason)
    }
}

impl TryFrom<&RawAttribute> for ErrorCode {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        ErrorCode::from_raw(value)
    }
}

impl From<ErrorCode> for RawAttribute {
    fn from(f: ErrorCode) -> Self {
        f.to_raw()
    }
}

/// The UnknownAttributes [`Attribute`]
#[derive(Debug, Clone)]
pub struct UnknownAttributes {
    attributes: Vec<AttributeType>,
}
impl Attribute for UnknownAttributes {
    fn get_type(&self) -> AttributeType {
        UNKNOWN_ATTRIBUTES
    }

    fn length(&self) -> u16 {
        (self.attributes.len() as u16) * 2
    }

    fn to_raw(&self) -> RawAttribute {
        let mut data = Vec::with_capacity(self.length() as usize);
        for attr in &self.attributes {
            let mut encoded = vec![0; 2];
            BigEndian::write_u16(&mut encoded, (*attr).into());
            data.extend(encoded);
        }
        RawAttribute::new(self.get_type(), &data)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != UNKNOWN_ATTRIBUTES {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() % 2 != 0 {
            /* all attributes are 16-bits */
            return Err(StunParseError::InvalidData);
        }
        let mut attrs = vec![];
        for attr in raw.value.chunks_exact(2) {
            attrs.push(BigEndian::read_u16(attr).into());
        }
        Ok(Self { attributes: attrs })
    }
}
impl UnknownAttributes {
    /// Create a new unknown attributes [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let unknown = UnknownAttributes::new(&[USERNAME]);
    /// assert!(unknown.has_attribute(USERNAME));
    /// ```
    pub fn new(attrs: &[AttributeType]) -> Self {
        Self {
            attributes: attrs.to_vec(),
        }
    }

    /// Add an [`AttributeType`] that is unsupported
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let mut unknown = UnknownAttributes::new(&[]);
    /// unknown.add_attribute(USERNAME);
    /// assert!(unknown.has_attribute(USERNAME));
    /// ```
    pub fn add_attribute(&mut self, attr: AttributeType) {
        if !self.has_attribute(attr) {
            self.attributes.push(attr);
        }
    }

    /// Check if an [`AttributeType`] is present
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let unknown = UnknownAttributes::new(&[USERNAME]);
    /// assert!(unknown.has_attribute(USERNAME));
    /// ```
    pub fn has_attribute(&self, attr: AttributeType) -> bool {
        self.attributes.iter().any(|&a| a == attr)
    }
}

impl std::fmt::Display for UnknownAttributes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {:?}", self.get_type(), self.attributes)
    }
}

impl TryFrom<&RawAttribute> for UnknownAttributes {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        UnknownAttributes::from_raw(value)
    }
}

impl From<UnknownAttributes> for RawAttribute {
    fn from(f: UnknownAttributes) -> Self {
        f.to_raw()
    }
}

/// The Software [`Attribute`]
#[derive(Debug, Clone)]
pub struct Software {
    software: String,
}
impl Attribute for Software {
    fn get_type(&self) -> AttributeType {
        SOFTWARE
    }

    fn length(&self) -> u16 {
        self.software.len() as u16
    }

    fn to_raw(&self) -> RawAttribute {
        RawAttribute::new(self.get_type(), self.software.as_bytes())
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != SOFTWARE {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() > 763 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            software: std::str::from_utf8(&raw.value)
                .map_err(|_| StunParseError::InvalidData)?
                .to_owned(),
        })
    }
}

impl Software {
    /// Create a new unknown attributes [`Attribute`]
    ///
    /// # Errors
    ///
    /// If the length of the provided string is too long for the [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let software = Software::new("librice 0.1").unwrap();
    /// assert_eq!(software.software(), "librice 0.1");
    /// ```
    pub fn new(software: &str) -> Result<Self, StunParseError> {
        if software.len() > 768 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            software: software.to_owned(),
        })
    }

    /// The value of the software field
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let software = Software::new("librice 0.1").unwrap();
    /// assert_eq!(software.software(), "librice 0.1");
    /// ```
    pub fn software(&self) -> &str {
        &self.software
    }
}

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

impl TryFrom<&RawAttribute> for Software {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        Software::from_raw(value)
    }
}

impl From<Software> for RawAttribute {
    fn from(f: Software) -> Self {
        f.to_raw()
    }
}

macro_rules! bytewise_xor {
    ($size:literal, $a:expr, $b:expr, $default:literal) => {{
        let mut arr = [$default; $size];
        for (i, item) in arr.iter_mut().enumerate() {
            *item = $a[i] ^ $b[i];
        }
        arr
    }};
}

/// The XorMappedAddress [`Attribute`]
#[derive(Debug, Clone)]
pub struct XorMappedAddress {
    // stored XOR-ed as we need the transaction id to get the original value
    addr: SocketAddr,
}
impl Attribute for XorMappedAddress {
    fn get_type(&self) -> AttributeType {
        XOR_MAPPED_ADDRESS
    }

    fn length(&self) -> u16 {
        match self.addr {
            SocketAddr::V4(_) => 8,
            SocketAddr::V6(_) => 20,
        }
    }

    fn to_raw(&self) -> RawAttribute {
        match self.addr {
            SocketAddr::V4(addr) => {
                let mut buf = [0; 8];
                buf[1] = 0x1;
                BigEndian::write_u16(&mut buf[2..4], addr.port());
                let octets = u32::from(*addr.ip());
                BigEndian::write_u32(&mut buf[4..8], octets);
                RawAttribute::new(self.get_type(), &buf)
            }
            SocketAddr::V6(addr) => {
                let mut buf = [0; 20];
                buf[1] = 0x2;
                BigEndian::write_u16(&mut buf[2..4], addr.port());
                let octets = u128::from(*addr.ip());
                BigEndian::write_u128(&mut buf[4..20], octets);
                RawAttribute::new(self.get_type(), &buf)
            }
        }
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != XOR_MAPPED_ADDRESS {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 4 {
            return Err(StunParseError::NotEnoughData);
        }
        let port = BigEndian::read_u16(&raw.value[2..4]);
        let addr = match raw.value[1] {
            0x1 => {
                // ipv4
                if raw.value.len() < 8 {
                    return Err(StunParseError::NotEnoughData);
                }
                if raw.value.len() > 8 {
                    return Err(StunParseError::TooBig);
                }
                IpAddr::V4(Ipv4Addr::from(BigEndian::read_u32(&raw.value[4..8])))
            }
            0x2 => {
                // ipv6
                if raw.value.len() < 20 {
                    return Err(StunParseError::NotEnoughData);
                }
                if raw.value.len() > 20 {
                    return Err(StunParseError::TooBig);
                }
                let mut octets = [0; 16];
                octets.clone_from_slice(&raw.value[4..]);
                IpAddr::V6(Ipv6Addr::from(octets))
            }
            _ => return Err(StunParseError::InvalidData),
        };
        Ok(Self {
            addr: SocketAddr::new(addr, port),
        })
    }
}

impl XorMappedAddress {
    /// Create a new XorMappedAddress [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// # use std::net::SocketAddr;
    /// let addr = "127.0.0.1:1234".parse().unwrap();
    /// let mapped_addr = XorMappedAddress::new(addr, 0x5678.into());
    /// assert_eq!(mapped_addr.addr(0x5678.into()), addr);
    /// ```
    pub fn new(addr: SocketAddr, transaction: TransactionId) -> Self {
        Self {
            addr: XorMappedAddress::xor_addr(addr, transaction),
        }
    }

    fn xor_addr(addr: SocketAddr, transaction: TransactionId) -> SocketAddr {
        match addr {
            SocketAddr::V4(addr) => {
                let port = addr.port() ^ (MAGIC_COOKIE >> 16) as u16;
                let const_octets = MAGIC_COOKIE.to_be_bytes();
                let addr_octets = addr.ip().octets();
                let octets = bytewise_xor!(4, const_octets, addr_octets, 0);
                SocketAddr::new(IpAddr::V4(Ipv4Addr::from(octets)), port)
            }
            SocketAddr::V6(addr) => {
                let port = addr.port() ^ (MAGIC_COOKIE >> 16) as u16;
                let transaction: u128 = transaction.into();
                let const_octets = ((MAGIC_COOKIE as u128) << 96
                    | (transaction & 0x0000_0000_ffff_ffff_ffff_ffff_ffff_ffff))
                    .to_be_bytes();
                let addr_octets = addr.ip().octets();
                let octets = bytewise_xor!(16, const_octets, addr_octets, 0);
                SocketAddr::new(IpAddr::V6(Ipv6Addr::from(octets)), port)
            }
        }
    }

    /// Retrieve the address stored in a XorMappedAddress
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// # use std::net::SocketAddr;
    /// let addr = "[::1]:1234".parse().unwrap();
    /// let mapped_addr = XorMappedAddress::new(addr, 0x5678.into());
    /// assert_eq!(mapped_addr.addr(0x5678.into()), addr);
    /// ```
    pub fn addr(&self, transaction: TransactionId) -> SocketAddr {
        XorMappedAddress::xor_addr(self.addr, transaction)
    }
}

impl std::fmt::Display for XorMappedAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.addr {
            SocketAddr::V4(_) => write!(f, "{}: {:?}", self.get_type(), self.addr(0x0.into())),
            SocketAddr::V6(addr) => write!(f, "{}: XOR({:?})", self.get_type(), addr),
        }
    }
}

impl TryFrom<&RawAttribute> for XorMappedAddress {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        XorMappedAddress::from_raw(value)
    }
}

impl From<XorMappedAddress> for RawAttribute {
    fn from(f: XorMappedAddress) -> Self {
        f.to_raw()
    }
}

/// The Priority [`Attribute`]
#[derive(Debug)]
pub struct Priority {
    priority: u32,
}

impl Attribute for Priority {
    fn get_type(&self) -> AttributeType {
        PRIORITY
    }

    fn length(&self) -> u16 {
        4
    }

    fn to_raw(&self) -> RawAttribute {
        let mut buf = [0; 4];
        BigEndian::write_u32(&mut buf[0..4], self.priority);
        RawAttribute::new(self.get_type(), &buf)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != PRIORITY {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 4 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 4 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            priority: BigEndian::read_u32(&raw.value[..4]),
        })
    }
}

impl Priority {
    /// Create a new Priority [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let priority = Priority::new(1234);
    /// assert_eq!(priority.priority(), 1234);
    /// ```
    pub fn new(priority: u32) -> Self {
        Self { priority }
    }

    /// Retrieve the priority value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let priority = Priority::new(1234);
    /// assert_eq!(priority.priority(), 1234);
    /// ```
    pub fn priority(&self) -> u32 {
        self.priority
    }
}

impl TryFrom<&RawAttribute> for Priority {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        Priority::from_raw(value)
    }
}

impl From<Priority> for RawAttribute {
    fn from(f: Priority) -> Self {
        f.to_raw()
    }
}

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

/// The UseCandidate [`Attribute`]
#[derive(Debug)]
pub struct UseCandidate {}

impl Attribute for UseCandidate {
    fn get_type(&self) -> AttributeType {
        USE_CANDIDATE
    }

    fn length(&self) -> u16 {
        0
    }

    fn to_raw(&self) -> RawAttribute {
        let buf = [0; 0];
        RawAttribute::new(self.get_type(), &buf)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != USE_CANDIDATE {
            return Err(StunParseError::WrongImplementation);
        }
        if !raw.value.is_empty() {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {})
    }
}

impl Default for UseCandidate {
    fn default() -> Self {
        UseCandidate::new()
    }
}

impl UseCandidate {
    /// Create a new UseCandidate [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let _use_candidate = UseCandidate::new();
    /// ```
    pub fn new() -> Self {
        Self {}
    }
}

impl TryFrom<&RawAttribute> for UseCandidate {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        UseCandidate::from_raw(value)
    }
}

impl From<UseCandidate> for RawAttribute {
    fn from(f: UseCandidate) -> Self {
        f.to_raw()
    }
}

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

/// The IceControlled [`Attribute`]
#[derive(Debug)]
pub struct IceControlled {
    tie_breaker: u64,
}

impl Attribute for IceControlled {
    fn get_type(&self) -> AttributeType {
        ICE_CONTROLLED
    }

    fn length(&self) -> u16 {
        8
    }

    fn to_raw(&self) -> RawAttribute {
        let mut buf = [0; 8];
        BigEndian::write_u64(&mut buf[..8], self.tie_breaker);
        RawAttribute::new(self.get_type(), &buf)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != ICE_CONTROLLED {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 8 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 8 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            tie_breaker: BigEndian::read_u64(&raw.value),
        })
    }
}

impl IceControlled {
    /// Create a new IceControlled [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let ice_controlled = IceControlled::new(1234);
    /// assert_eq!(ice_controlled.tie_breaker(), 1234);
    /// ```
    pub fn new(tie_breaker: u64) -> Self {
        Self { tie_breaker }
    }

    /// Retrieve the tie breaker value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let ice_controlled = IceControlled::new(1234);
    /// assert_eq!(ice_controlled.tie_breaker(), 1234);
    /// ```
    pub fn tie_breaker(&self) -> u64 {
        self.tie_breaker
    }
}

impl TryFrom<&RawAttribute> for IceControlled {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        IceControlled::from_raw(value)
    }
}

impl From<IceControlled> for RawAttribute {
    fn from(f: IceControlled) -> Self {
        f.to_raw()
    }
}

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

/// The IceControlling [`Attribute`]
#[derive(Debug)]
pub struct IceControlling {
    tie_breaker: u64,
}

impl Attribute for IceControlling {
    fn get_type(&self) -> AttributeType {
        ICE_CONTROLLING
    }

    fn length(&self) -> u16 {
        8
    }

    fn to_raw(&self) -> RawAttribute {
        let mut buf = [0; 8];
        BigEndian::write_u64(&mut buf[..8], self.tie_breaker);
        RawAttribute::new(self.get_type(), &buf)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != ICE_CONTROLLING {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 8 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 8 {
            return Err(StunParseError::TooBig);
        }
        Ok(Self {
            tie_breaker: BigEndian::read_u64(&raw.value),
        })
    }
}

impl IceControlling {
    /// Create a new IceControlling [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let ice_controlling = IceControlling::new(1234);
    /// assert_eq!(ice_controlling.tie_breaker(), 1234);
    /// ```
    pub fn new(tie_breaker: u64) -> Self {
        Self { tie_breaker }
    }

    /// Create a new IceControlling [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let ice_controlling = IceControlling::new(1234);
    /// assert_eq!(ice_controlling.tie_breaker(), 1234);
    /// ```
    pub fn tie_breaker(&self) -> u64 {
        self.tie_breaker
    }
}

impl TryFrom<&RawAttribute> for IceControlling {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        IceControlling::from_raw(value)
    }
}

impl From<IceControlling> for RawAttribute {
    fn from(f: IceControlling) -> Self {
        f.to_raw()
    }
}

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

/// The MessageIntegrity [`Attribute`]
#[derive(Debug)]
pub struct MessageIntegrity {
    hmac: [u8; 20],
}

impl Attribute for MessageIntegrity {
    fn get_type(&self) -> AttributeType {
        MESSAGE_INTEGRITY
    }

    fn length(&self) -> u16 {
        20
    }

    fn to_raw(&self) -> RawAttribute {
        RawAttribute::new(self.get_type(), &self.hmac)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != MESSAGE_INTEGRITY {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 20 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 20 {
            return Err(StunParseError::TooBig);
        }
        // sized checked earlier
        let boxed: Box<[u8; 20]> = raw.value.clone().into_boxed_slice().try_into().unwrap();
        Ok(Self { hmac: *boxed })
    }
}

impl MessageIntegrity {
    /// Create a new MessageIntegrity [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let hmac = [0;20];
    /// let integrity = MessageIntegrity::new(hmac);
    /// assert_eq!(integrity.hmac(), &hmac);
    /// ```
    pub fn new(hmac: [u8; 20]) -> Self {
        Self { hmac }
    }

    /// Retrieve the value of the hmac
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let hmac = [0; 20];
    /// let integrity = MessageIntegrity::new(hmac);
    /// assert_eq!(integrity.hmac(), &hmac);
    /// ```
    pub fn hmac(&self) -> &[u8; 20] {
        &self.hmac
    }

    /// Compute the Message Integrity value of a chunk of data using a key
    ///
    /// Note: use `MessageIntegrity::verify` for the actual verification to ensure constant time
    /// checks of the values to defeat certain types of timing attacks.
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::*;
    /// let key = [40; 10];
    /// let data = [10; 30];
    /// let expected = [209, 217, 210, 15, 124, 78, 87, 181, 211, 233, 165, 180, 44, 142, 81, 233, 138, 186, 184, 97];
    /// let integrity = MessageIntegrity::compute(&data, &key).unwrap();
    /// assert_eq!(integrity, expected);
    /// ```
    #[tracing::instrument(
        name = "MessageIntegrity::compute",
        level = "trace",
        err,
        ret,
        skip(data, key)
    )]
    pub fn compute(data: &[u8], key: &[u8]) -> Result<[u8; 20], StunError> {
        use hmac::{Hmac, Mac};
        let mut hmac = Hmac::<sha1::Sha1>::new_from_slice(key)
            .map_err(|_| StunError::ParseError(StunParseError::InvalidData))?;
        hmac.update(data);
        let ret = hmac.finalize().into_bytes();
        ret.try_into()
            .map_err(|_| StunError::ParseError(StunParseError::InvalidData))
    }

    /// Compute the Message Integrity value of a chunk of data using a key
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::*;
    /// let key = [40; 10];
    /// let data = [10; 30];
    /// let expected = [209, 217, 210, 15, 124, 78, 87, 181, 211, 233, 165, 180, 44, 142, 81, 233, 138, 186, 184, 97];
    /// assert_eq!(MessageIntegrity::verify(&data, &key, &expected).unwrap(), ());
    /// ```
    #[tracing::instrument(
        name = "MessageIntegrity::verify",
        level = "debug",
        skip(data, key, expected)
    )]
    pub fn verify(data: &[u8], key: &[u8], expected: &[u8; 20]) -> Result<(), StunError> {
        use hmac::{Hmac, Mac};
        let mut hmac = Hmac::<sha1::Sha1>::new_from_slice(key).map_err(|_| {
            error!("failed to create hmac from key data");
            StunError::ParseError(StunParseError::InvalidData)
        })?;
        hmac.update(data);
        hmac.verify_slice(expected).map_err(|_| {
            error!("integrity check failed");
            StunError::IntegrityCheckFailed
        })
    }
}

impl TryFrom<&RawAttribute> for MessageIntegrity {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        MessageIntegrity::from_raw(value)
    }
}
impl From<MessageIntegrity> for RawAttribute {
    fn from(f: MessageIntegrity) -> Self {
        f.to_raw()
    }
}

impl std::fmt::Display for MessageIntegrity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: 0x", self.get_type())?;
        for val in self.hmac.iter() {
            write!(f, "{:02x}", val)?;
        }
        Ok(())
    }
}

/// The Fingerprint [`Attribute`]
#[derive(Debug)]
pub struct Fingerprint {
    fingerprint: [u8; 4],
}

impl Attribute for Fingerprint {
    fn get_type(&self) -> AttributeType {
        FINGERPRINT
    }

    fn length(&self) -> u16 {
        4
    }

    fn to_raw(&self) -> RawAttribute {
        let buf = bytewise_xor!(4, self.fingerprint, Fingerprint::XOR_CONSTANT, 0);
        RawAttribute::new(self.get_type(), &buf)
    }

    fn from_raw(raw: &RawAttribute) -> Result<Self, StunParseError> {
        if raw.header.atype != FINGERPRINT {
            return Err(StunParseError::WrongImplementation);
        }
        if raw.value.len() < 4 {
            return Err(StunParseError::NotEnoughData);
        }
        if raw.value.len() > 4 {
            return Err(StunParseError::TooBig);
        }
        // sized checked earlier
        let boxed: Box<[u8; 4]> = raw.value.clone().into_boxed_slice().try_into().unwrap();
        let fingerprint = bytewise_xor!(4, *boxed, Fingerprint::XOR_CONSTANT, 0);
        Ok(Self { fingerprint })
    }
}

impl Fingerprint {
    const XOR_CONSTANT: [u8; 4] = [0x53, 0x54, 0x55, 0x4E];

    /// Create a new Fingerprint [`Attribute`]
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let value = [0;4];
    /// let fingerprint = Fingerprint::new(value);
    /// assert_eq!(fingerprint.fingerprint(), &value);
    /// ```
    pub fn new(fingerprint: [u8; 4]) -> Self {
        Self { fingerprint }
    }

    /// Retrieve the fingerprint value
    ///
    /// # Examples
    ///
    /// ```
    /// # use librice::stun::attribute::*;
    /// let value = [0;4];
    /// let fingerprint = Fingerprint::new(value);
    /// assert_eq!(fingerprint.fingerprint(), &value);
    /// ```
    pub fn fingerprint(&self) -> &[u8; 4] {
        &self.fingerprint
    }

    /// Compute the fingerprint of a specified block of data as required by STUN
    ///
    /// # Examples
    /// ```
    /// # use librice::stun::attribute::*;
    /// let value = [99;4];
    /// assert_eq!(Fingerprint::compute(&value), [216, 45, 250, 14]);
    /// ```
    pub fn compute(data: &[u8]) -> [u8; 4] {
        use crc::{Crc, CRC_32_ISO_HDLC};
        const CRC_ALGO: Crc<u32> = Crc::<u32>::new(&CRC_32_ISO_HDLC);
        CRC_ALGO.checksum(data).to_be_bytes()
    }
}

impl TryFrom<&RawAttribute> for Fingerprint {
    type Error = StunParseError;

    fn try_from(value: &RawAttribute) -> Result<Self, Self::Error> {
        Fingerprint::from_raw(value)
    }
}

impl From<Fingerprint> for RawAttribute {
    fn from(f: Fingerprint) -> Self {
        f.to_raw()
    }
}

impl std::fmt::Display for Fingerprint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: 0x", self.get_type())?;
        for val in self.fingerprint.iter() {
            write!(f, "{:02x}", val)?;
        }
        Ok(())
    }
}

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

    fn init() {
        crate::tests::test_init_log();
    }

    #[test]
    fn attribute_type() {
        init();
        let atype = ERROR_CODE;
        let anum: u16 = atype.into();
        assert_eq!(atype, anum.into());
    }

    #[test]
    fn short_attribute_header() {
        init();
        let data = [0; 1];
        // not enough data to parse the header
        let res: Result<AttributeHeader, _> = data.as_ref().try_into();
        assert!(res.is_err());
    }

    #[test]
    fn raw_attribute_construct() {
        init();
        let a = RawAttribute::new(1.into(), &[80, 160]);
        assert_eq!(a.get_type(), 1.into());
        let bytes: Vec<_> = a.into();
        assert_eq!(bytes, &[0, 1, 0, 2, 80, 160, 0, 0]);
        let b = RawAttribute::try_from(bytes.as_ref()).unwrap();
        assert_eq!(b.get_type(), 1.into());
    }

    #[test]
    fn raw_attribute_encoding() {
        init();
        let orig = RawAttribute::new(1.into(), &[80, 160]);
        assert_eq!(orig.get_type(), 1.into());
        let raw = orig.to_raw();
        assert_eq!(raw.get_type(), 1.into());
        assert_eq!(orig.get_type(), raw.get_type());
        assert_eq!(orig.length(), raw.length());
        assert_eq!(orig.to_bytes(), raw.to_bytes());
        let raw = RawAttribute::from_raw(&orig).unwrap();
        assert_eq!(raw.get_type(), 1.into());
        assert_eq!(orig.get_type(), raw.get_type());
        assert_eq!(orig.length(), raw.length());
        assert_eq!(orig.to_bytes(), raw.to_bytes());
        let mut data: Vec<_> = raw.into();
        let len = data.len();
        // one byte too big vs data size
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 + 1);
        assert!(matches!(
            RawAttribute::try_from(data.as_ref()),
            Err(StunParseError::NotEnoughData)
        ));
    }

    #[test]
    fn username() {
        init();
        let s = "woohoo!";
        let user = Username::new(s).unwrap();
        assert_eq!(user.get_type(), USERNAME);
        assert_eq!(user.username(), s);
        assert_eq!(user.length() as usize, s.len());
        let raw: RawAttribute = user.into();
        assert_eq!(raw.get_type(), USERNAME);
        let user2 = Username::try_from(&raw).unwrap();
        assert_eq!(user2.get_type(), USERNAME);
        assert_eq!(user2.username(), s);
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            Username::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn error_code() {
        init();
        let codes = vec![300, 401, 699];
        for code in codes.iter().copied() {
            let reason = ErrorCode::default_reason_for_code(code);
            let err = ErrorCode::new(code, reason).unwrap();
            assert_eq!(err.get_type(), ERROR_CODE);
            assert_eq!(err.code(), code);
            assert_eq!(err.reason(), reason);
            let raw: RawAttribute = err.into();
            assert_eq!(raw.get_type(), ERROR_CODE);
            let err2 = ErrorCode::try_from(&raw).unwrap();
            assert_eq!(err2.get_type(), ERROR_CODE);
            assert_eq!(err2.code(), code);
            assert_eq!(err2.reason(), reason);
        }
        let code = codes[0];
        let reason = ErrorCode::default_reason_for_code(code);
        let err = ErrorCode::new(code, reason).unwrap();
        let raw: RawAttribute = err.into();
        // no data
        let mut data: Vec<_> = raw.clone().into();
        let len = 0;
        BigEndian::write_u16(&mut data[2..4], len as u16);
        assert!(matches!(
            ErrorCode::try_from(&RawAttribute::try_from(data[..len + 4].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            ErrorCode::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn unknown_attributes() {
        init();
        let mut unknown = UnknownAttributes::new(&[REALM]);
        unknown.add_attribute(ALTERNATE_SERVER);
        // duplicates ignored
        unknown.add_attribute(ALTERNATE_SERVER);
        assert_eq!(unknown.get_type(), UNKNOWN_ATTRIBUTES);
        assert!(unknown.has_attribute(REALM));
        assert!(unknown.has_attribute(ALTERNATE_SERVER));
        assert!(!unknown.has_attribute(NONCE));
        let raw: RawAttribute = unknown.into();
        assert_eq!(raw.get_type(), UNKNOWN_ATTRIBUTES);
        let unknown2 = UnknownAttributes::try_from(&raw).unwrap();
        assert_eq!(unknown2.get_type(), UNKNOWN_ATTRIBUTES);
        assert!(unknown2.has_attribute(REALM));
        assert!(unknown2.has_attribute(ALTERNATE_SERVER));
        assert!(!unknown2.has_attribute(NONCE));
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            UnknownAttributes::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::InvalidData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            UnknownAttributes::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn software() {
        init();
        let software = Software::new("software").unwrap();
        assert_eq!(software.get_type(), SOFTWARE);
        assert_eq!(software.software(), "software");
        let raw: RawAttribute = software.into();
        assert_eq!(raw.get_type(), SOFTWARE);
        let software2 = Software::try_from(&raw).unwrap();
        assert_eq!(software2.get_type(), SOFTWARE);
        assert_eq!(software2.software(), "software");
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            Software::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn xor_mapped_address() {
        init();
        let transaction_id = 0x9876_5432_1098_7654_3210_9876.into();
        let addrs = &[
            "192.168.0.1:40000".parse().unwrap(),
            "[fd12:3456:789a:1::1]:41000".parse().unwrap(),
        ];
        for addr in addrs {
            let mapped = XorMappedAddress::new(*addr, transaction_id);
            assert_eq!(mapped.get_type(), XOR_MAPPED_ADDRESS);
            assert_eq!(mapped.addr(transaction_id), *addr);
            let raw: RawAttribute = mapped.into();
            assert_eq!(raw.get_type(), XOR_MAPPED_ADDRESS);
            let mapped2 = XorMappedAddress::try_from(&raw).unwrap();
            assert_eq!(mapped2.get_type(), XOR_MAPPED_ADDRESS);
            assert_eq!(mapped2.addr(transaction_id), *addr);
            // truncate by one byte
            let mut data: Vec<_> = raw.clone().into();
            let len = data.len();
            BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
            assert!(matches!(
                XorMappedAddress::try_from(
                    &RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()
                ),
                Err(StunParseError::NotEnoughData)
            ));
            // provide incorrectly typed data
            let mut data: Vec<_> = raw.into();
            BigEndian::write_u16(&mut data[0..2], 0);
            assert!(matches!(
                XorMappedAddress::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
                Err(StunParseError::WrongImplementation)
            ));
        }
    }

    #[test]
    fn priority() {
        init();
        let val = 100;
        let priority = Priority::new(val);
        assert_eq!(priority.get_type(), PRIORITY);
        assert_eq!(priority.priority(), val);
        let raw: RawAttribute = priority.into();
        assert_eq!(raw.get_type(), PRIORITY);
        let mapped2 = Priority::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), PRIORITY);
        assert_eq!(mapped2.priority(), val);
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            Priority::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            Priority::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn use_candidate() {
        init();
        let use_candidate = UseCandidate::new();
        assert_eq!(use_candidate.get_type(), USE_CANDIDATE);
        assert_eq!(use_candidate.length(), 0);
        let raw: RawAttribute = use_candidate.into();
        assert_eq!(raw.get_type(), USE_CANDIDATE);
        let mapped2 = UseCandidate::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), USE_CANDIDATE);
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            UseCandidate::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn ice_controlling() {
        init();
        let tb = 100;
        let attr = IceControlling::new(tb);
        assert_eq!(attr.get_type(), ICE_CONTROLLING);
        assert_eq!(attr.tie_breaker(), tb);
        let raw: RawAttribute = attr.into();
        assert_eq!(raw.get_type(), ICE_CONTROLLING);
        let mapped2 = IceControlling::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), ICE_CONTROLLING);
        assert_eq!(mapped2.tie_breaker(), tb);
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            IceControlling::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            IceControlling::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn ice_controlled() {
        init();
        let tb = 100;
        let attr = IceControlled::new(tb);
        assert_eq!(attr.get_type(), ICE_CONTROLLED);
        assert_eq!(attr.tie_breaker(), tb);
        let raw: RawAttribute = attr.into();
        assert_eq!(raw.get_type(), ICE_CONTROLLED);
        let mapped2 = IceControlled::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), ICE_CONTROLLED);
        assert_eq!(mapped2.tie_breaker(), tb);
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            IceControlled::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            IceControlled::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn fingerprint() {
        init();
        let val = [1; 4];
        let attr = Fingerprint::new(val);
        assert_eq!(attr.get_type(), FINGERPRINT);
        assert_eq!(attr.fingerprint(), &val);
        let raw: RawAttribute = attr.into();
        assert_eq!(raw.get_type(), FINGERPRINT);
        let mapped2 = Fingerprint::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), FINGERPRINT);
        assert_eq!(mapped2.fingerprint(), &val);
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            Fingerprint::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            Fingerprint::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }

    #[test]
    fn message_integrity() {
        init();
        let val = [1; 20];
        let attr = MessageIntegrity::new(val);
        assert_eq!(attr.get_type(), MESSAGE_INTEGRITY);
        assert_eq!(attr.hmac(), &val);
        let raw: RawAttribute = attr.into();
        assert_eq!(raw.get_type(), MESSAGE_INTEGRITY);
        let mapped2 = MessageIntegrity::try_from(&raw).unwrap();
        assert_eq!(mapped2.get_type(), MESSAGE_INTEGRITY);
        assert_eq!(mapped2.hmac(), &val);
        // truncate by one byte
        let mut data: Vec<_> = raw.clone().into();
        let len = data.len();
        BigEndian::write_u16(&mut data[2..4], len as u16 - 4 - 1);
        assert!(matches!(
            MessageIntegrity::try_from(&RawAttribute::try_from(data[..len - 1].as_ref()).unwrap()),
            Err(StunParseError::NotEnoughData)
        ));
        // provide incorrectly typed data
        let mut data: Vec<_> = raw.into();
        BigEndian::write_u16(&mut data[0..2], 0);
        assert!(matches!(
            MessageIntegrity::try_from(&RawAttribute::try_from(data.as_ref()).unwrap()),
            Err(StunParseError::WrongImplementation)
        ));
    }
}