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
//! Yet Another Tag Length Value (YATLV) format.
//!
//! Tag-length-value formats are a common way to exchange structured data in a compact and
//! well defined way.  They stand midway between schema-rich formats (like `JSON`, `YAML` and `XML`)
//! and compact binary formats that contain no schema information (like `bincode`).
//!
//! One advantage of tag-length-value formats is they support better forwards compatibility
//! than their schema-less cousins because they contain just enough information for a parser to
//! skip fields they do not recognise.
//!
//! Unlike many tag-length-value formats, no attempt is made to use variable length
//! encodings to reduce the amount of space taken by the 'length'.  This does lead to larger
//! encodings but simplifies the job of the parser and builder significantly.
//!
//! Structure of the format:
//! ```abnf
//! packet-frame = frame-size frame
//! frame-size   = unsigned32
//! frame        = frame-format field-count *field
//! frame-format = 0x01
//! field-count  = unsigned32
//! field        = field-tag field-length field-value
//! field-tag    = unsigned16
//! field-length = unsigned32
//! field-value  = octet-array
//! unsigned16   = 0x0000-0xFFFF
//! unsigned32   = 0x00000000-0xFFFFFFFF
//! octet-array  = *0x00-0xFF
//! ```
//! Where:
//!
//! * frame-format is always 0x01, but alternative formats may be added later
//! * the number `field`s must match `field-count`
//! * the length of `field-value` must match `field-length`.
//! * `unsigned-16` and `unsigned-32` are encoded using big-endian.
//!
//! The root frame can either be encoded as a `frame` or as a `packet-frame`.  Encoding
//! as a `packet-frame` is useful when sending `frame`s across a stream.
//!
//! Although applications can store arbitrary data in the `field-value`, the following
//! conventions should normally be observed:
//!
//! * numbers use big-endian encoding
//! * boolean values are encoded using a single byte (`0x00`=`false`, `0xFF`=`true`)
//! * text is encoded as UTF-8
//!
//! # Reading and Writing
//!
//! This library tries to make reading and writing reliable and not dependant on
//! the values being written.  To that end, the `add_*` methods for numbers always
//! use the same number of bytes, irrespective of the actual values being written.
//! Currently only `add_data` and `add_str` can add a variable number of bytes to the frame.
//!
//! Reading attempts to be forward compatible, with the following guarantees:
//!
//! * Any number written by a smaller `add_u*` method can always be be safely read by a larger one.
//! (e.g., a number written using `add_u16` can be safely read using`get_u32`).
//! * Any number written by a larger `add_u*` method can be read by a smaller one _if_ the value
//! is small enough.
//!
//! This means that when upgrading a program it should always be safe to increase the range
//! of a field, but special handling is needed if the range of a field is going to decreased.
//!
//! # Create Features
//!
//! Yatlv has one optional feature:
//!
//! * `uuid` supports reading and writing uuids.
//!
//! # Example Usage
//!
//! ```
//! use yatlv::Result;
//! # fn main() -> Result<()> {
//!
//! use yatlv::{FrameBuilder, FrameBuilderLike, FrameParser};
//!
//! const TAG1: u16 = 1;
//! const TAG2: u16 = 2;
//! const TAG3: u16 = 3;
//! const TAG4: u16 = 4;
//!
//! // the FrameBuilder will expand the buffer as needed, but it is more
//! // efficient to allocate enough capacity up front.
//! let mut buf = Vec::with_capacity(1000);
//!
//! {
//!     let mut bld1 = FrameBuilder::new(&mut buf);
//!     bld1.add_str(TAG1, "hello");
//!
//!     {
//!         // child FrameBuilders retain a mutable reference
//!         // to their parent - so you cannot have two child
//!         // FrameBuilders in the same scope.
//!         let mut bld2a = bld1.add_frame(TAG2);
//!         bld2a.add_u32(TAG4, 78);
//!         bld2a.add_u32(TAG4, 109);
//!     }
//!
//!     {
//!         let mut bld2b = bld1.add_frame(TAG3);
//!         bld2b.add_str(TAG4, "goodbye");
//!     }
//! }
//!
//! let parser1 = FrameParser::new(&buf)?;
//! assert_eq!(Some("hello"), parser1.get_str(TAG1)?);
//!
//! // FrameParsers only have an immutable reference to their parent,
//! // so you can hold references to multiple child frames when parsing.
//! let parser2a = parser1.get_frame(TAG2)?.unwrap();
//! let parser2b = parser1.get_frame(TAG3)?.unwrap();
//!
//! // Here we are using iterator access to get all the values with the same tag (TAG4)
//! let frame2a_values: Vec<_> = parser2a.get_u32s(TAG4).map(|v| v.unwrap()).collect();
//! assert_eq!(vec![78, 109], frame2a_values);
//!
//! let frame2b_value = parser2b.get_str(TAG4)?;
//! assert_eq!(Some("goodbye"), frame2b_value);
//!
//! # Ok(())}
//! ```

use std::convert::TryInto;

const SIZE_BYTES: usize = 4;

/// FrameBuilderLike defines the methods common to [FrameBuilder] and [PacketFrameBuilder].
pub trait FrameBuilderLike {
    /// Add a slice of data as a field to the frame.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = &[90, 9];
    ///     bld.add_data(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,          // frame-format
    ///     0, 0, 0, 1, // field count
    ///     0, 45,      // field-tag
    ///     0, 0, 0, 2, // field-length
    ///     90, 9       // field-value
    /// ], &data[..]);
    /// ```
    fn add_data(&mut self, tag: u16, value: &[u8]);

    /// Create a new child frame builder.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let mut child_bld = bld.add_frame(45);
    ///     let tag2 = 60;
    ///     let data = &[90, 9];
    ///     child_bld.add_data(60, data);
    /// }
    /// assert_eq!(&[
    ///     1,           // frame-format
    ///     0, 0, 0, 1,  // field count
    ///     0, 45,       // field-tag
    ///     0, 0, 0, 13, // field-length
    ///     1,           // child frame format
    ///     0, 0, 0, 1,  // child field count
    ///     0, 60,       // child field-tag2
    ///     0, 0, 0, 2,  // child field-length
    ///     90, 9        // child field-value
    /// ], &data[..]);
    /// ```
    fn add_frame(&mut self, tag: u16) -> PacketFrameBuilder;

    #[deprecated]
    /// Use [FrameBuilderLike::add_frame] instead.
    fn add_child(&mut self, tag: u16) -> PacketFrameBuilder {
        self.add_frame(tag)
    }

    /// Add a bool flied to the frame.
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     bld.add_bool(1022, true);
    ///     bld.add_bool(1021, false);
    /// }
    /// assert_eq!(&[
    ///     1,          // frame-format
    ///     0, 0, 0, 2, // field count = 1
    ///     3, 254,     // tag = 1022
    ///     0, 0, 0, 1, // field length = 2
    ///     255,        // field value
    ///     3, 253,     // tag = 1021
    ///     0, 0, 0, 1, // field length = 2
    ///     0           // field value
    /// ], &data[..]);
    /// ```
    fn add_bool(&mut self, tag: u16, value: bool) {
        self.add_u8(tag, if value { 0xFF } else { 0x00 })
    }

    /// Add a u8 field to the frame.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = 7;
    ///     bld.add_u8(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,          // frame-format
    ///     0, 0, 0, 1, // field count
    ///     0, 45,      // field-tag
    ///     0, 0, 0, 1, // field-length
    ///     7           // field-value
    /// ], &data[..]);
    /// ```
    fn add_u8(&mut self, tag: u16, value: u8) {
        self.add_data(tag, &value.to_be_bytes())
    }

    /// Add a u16 field to the frame.
    ///
    /// This method will always use a two byte encoding
    /// for the value.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = 7;
    ///     bld.add_u16(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,          // frame-format
    ///     0, 0, 0, 1, // field count
    ///     0, 45,      // field-tag
    ///     0, 0, 0, 2, // field-length
    ///     0, 7        // field-value
    /// ], &data[..]);
    /// ```
    fn add_u16(&mut self, tag: u16, value: u16) {
        self.add_data(tag, &value.to_be_bytes())
    }

    /// Add a u32 field to the frame.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = 7;
    ///     bld.add_u32(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,          // frame-format
    ///     0, 0, 0, 1, // field count
    ///     0, 45,      // field-tag
    ///     0, 0, 0, 4, // field-length
    ///     0, 0, 0, 7  // field-value
    /// ], &data[..]);
    /// ```
    fn add_u32(&mut self, tag: u16, value: u32) {
        self.add_data(tag, &value.to_be_bytes())
    }

    /// Add a u64 field to the frame.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = 7;
    ///     bld.add_u64(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,                     // frame-format
    ///     0, 0, 0, 1,            // field count
    ///     0, 45,                 // field-tag
    ///     0, 0, 0, 8,            // field-length
    ///     0, 0, 0, 0, 0, 0, 0, 7 // field-value
    /// ], &data[..]);
    /// ```
    fn add_u64(&mut self, tag: u16, value: u64) {
        self.add_data(tag, &value.to_be_bytes())
    }

    /// Add a str field to the frame.
    ///
    /// ```
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = "hello";
    ///     bld.add_str(tag, data);
    /// }
    /// assert_eq!(&[
    ///     1,                      // frame-format
    ///     0, 0, 0, 1,             // field count
    ///     0, 45,                  // field-tag
    ///     0, 0, 0, 5,             // field-length
    ///     104, 101, 108, 108, 111 // field-value
    /// ], &data[..]);
    /// ```
    fn add_str<S>(&mut self, tag: u16, value: S)
    where
        S: AsRef<str>,
    {
        self.add_data(tag, &value.as_ref().as_bytes())
    }

    /// Add a uuid field to the frame.
    ///
    /// ```
    /// use uuid::Uuid;
    /// use yatlv::{FrameBuilder, FrameBuilderLike};
    /// let mut data = Vec::with_capacity(100);
    /// {
    ///     let mut bld = FrameBuilder::new(&mut data);
    ///     let tag = 45;
    ///     let data = Uuid::parse_str("3011712a-d972-4a5d-bbf9-ec5fb7525c97").unwrap();
    ///     bld.add_uuid(tag, &data);
    /// }
    /// assert_eq!(&[
    ///     1,                      // frame-format
    ///     0, 0, 0, 1,             // field count
    ///     0, 45,                  // field-tag
    ///     0, 0, 0, 16,             // field-length
    ///     48, 17, 113, 42, 217, 114, 74, 93, 187, 249, 236, 95, 183, 82, 92, 151 // field-value
    /// ], &data[..]);
    /// ```
    #[cfg(feature = "uuid")]
    fn add_uuid(&mut self, tag: u16, value: &uuid::Uuid) {
        self.add_data(tag, value.as_bytes())
    }
}

/// FrameBuilder can be used to push a frame into a mutable `Vec<u8>`
///
/// For usage details see [FrameBuilderLike].
///
/// ```
/// use yatlv::FrameBuilder;
/// let mut data = Vec::with_capacity(100);
/// {
///     FrameBuilder::new(&mut data);
/// }
/// assert_eq!(&[
///     1,         // frame-format
///     0, 0, 0, 0 // field-count
/// ], &data[..]);
/// ```
pub struct FrameBuilder<'a> {
    field_count: u32,
    field_start: usize,
    data: &'a mut Vec<u8>,
}

impl<'a> Drop for FrameBuilder<'a> {
    fn drop(&mut self) {
        let field_count_pos = self.field_start + 1;
        self.data[field_count_pos..field_count_pos + SIZE_BYTES]
            .copy_from_slice(&self.field_count.to_be_bytes())
    }
}

impl<'a> FrameBuilder<'a> {
    pub fn new(data: &mut Vec<u8>) -> FrameBuilder {
        let field_start = data.len();
        data.extend_from_slice(&[1, 0, 0, 0, 0]);

        FrameBuilder {
            field_count: 0,
            field_start,
            data,
        }
    }
}

impl<'a> FrameBuilderLike for FrameBuilder<'a> {
    fn add_data(&mut self, tag: u16, value: &[u8]) {
        self.field_count += 1;
        self.data.reserve(6 + value.len());
        self.data.extend_from_slice(&tag.to_be_bytes());
        self.data
            .extend_from_slice(&(value.len() as u32).to_be_bytes());
        self.data.extend_from_slice(value);
    }

    fn add_frame(&mut self, tag: u16) -> PacketFrameBuilder {
        self.field_count += 1;
        self.data.reserve(6);
        self.data.extend_from_slice(&tag.to_be_bytes());
        PacketFrameBuilder::new(self.data)
    }
}

/// PacketBuilder can be used to push a packet-frame into a mutable `Vec<u8>`
///
/// For usage details see [FrameBuilderLike].
/// ```
/// use yatlv::PacketFrameBuilder;
/// let mut data = Vec::with_capacity(100);
/// {
///     PacketFrameBuilder::new(&mut data);
/// }
/// assert_eq!(&[
///     0, 0, 0, 5, // packet-size
///     1,  // frame-format
///     0, 0, 0, 0 // field-count
/// ], &data[..]);
/// ```
pub struct PacketFrameBuilder<'a> {
    field_count: u32,
    packet_start: usize,
    data: &'a mut Vec<u8>,
}

impl<'a> Drop for PacketFrameBuilder<'a> {
    fn drop(&mut self) {
        let packet_length = (self.data.len() - self.packet_start - SIZE_BYTES) as u32;

        self.data[self.packet_start..self.packet_start + SIZE_BYTES]
            .copy_from_slice(&packet_length.to_be_bytes());

        let field_count_pos = self.packet_start + 5;
        self.data[field_count_pos..field_count_pos + SIZE_BYTES]
            .copy_from_slice(&self.field_count.to_be_bytes())
    }
}

impl<'a> PacketFrameBuilder<'a> {
    pub fn new(data: &mut Vec<u8>) -> PacketFrameBuilder {
        let packet_start = data.len();
        data.extend_from_slice(&[0, 0, 0, 0, 1, 0, 0, 0, 0]);

        PacketFrameBuilder {
            field_count: 0,
            packet_start,
            data,
        }
    }
}

impl<'a> FrameBuilderLike for PacketFrameBuilder<'a> {
    fn add_data(&mut self, tag: u16, value: &[u8]) {
        self.field_count += 1;
        self.data.reserve(6 + value.len());
        self.data.extend_from_slice(&tag.to_be_bytes());
        self.data
            .extend_from_slice(&(value.len() as u32).to_be_bytes());
        self.data.extend_from_slice(value);
    }

    fn add_frame(&mut self, tag: u16) -> PacketFrameBuilder {
        self.field_count += 1;
        self.data.reserve(6);
        self.data.extend_from_slice(&tag.to_be_bytes());
        PacketFrameBuilder::new(self.data)
    }
}

/// Library Error Type
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
    /// The frame must start with a single format byte.
    IncompleteFrameFormat,

    /// The frame format must be one of the recognized formats (currently only, `0x01`).
    InvalidFrameFormat(u32),

    /// The frame must have a four byte field-count that indicates the number fields
    /// in the frame (encoded as big-endian u32)
    IncompleteFrameFieldCount,

    /// Each field must start with a two byte tag (big-endian u16) and a
    /// four byte length (big-endian u32).
    IncompleteFieldTagOrLength,

    /// Each field must have a value that is field-length long
    /// This error as expected and actual lengths.
    IncompleteFieldValue(usize, usize),

    /// When converting a field to an expected type of value the field length
    /// must be compatible with the expected value type.
    IncompatibleFieldLength(usize),

    /// When converting a field into an expected type the value of the field
    /// must be compatible with the expected type.
    IncompatibleFieldValue,

    /// Once all the fields have been read there should be no more data in the
    /// frame.
    UnexpectedData,
}

/// Library Result Type
pub type Result<T> = std::result::Result<T, Error>;

struct FrameParserField<'a> {
    tag: u16,
    value: &'a [u8],
}

/// FrameParser can be used to access field encoded as a frame.
pub struct FrameParser<'a> {
    fields: Vec<FrameParserField<'a>>,
}

enum FrameFormat {
    Format1,
}

fn read_frame_format(data: &[u8]) -> Result<(FrameFormat, &[u8])> {
    if !data.is_empty() {
        let (field_count_bytes, tail) = data.split_at(1);
        let raw_format = field_count_bytes[0];
        let format = match raw_format {
            0x01 => Ok(FrameFormat::Format1),
            _ => Err(Error::InvalidFrameFormat(raw_format as u32)),
        }?;
        Ok((format, tail))
    } else {
        Err(Error::IncompleteFrameFormat)
    }
}

fn read_frame_field_count(data: &[u8]) -> Result<(u32, &[u8])> {
    if data.len() >= 4 {
        let (field_count_bytes, tail) = data.split_at(4);
        let field_count = u32::from_be_bytes(field_count_bytes.try_into().unwrap());
        Ok((field_count, tail))
    } else {
        Err(Error::IncompleteFrameFieldCount)
    }
}

fn read_field_tag_and_length(data: &[u8]) -> Result<(u16, usize, &[u8])> {
    if data.len() >= 6 {
        let (tag_bytes, tail) = data.split_at(2);
        let tag = u16::from_be_bytes(tag_bytes.try_into().unwrap());
        let (length_bytes, tail) = tail.split_at(4);
        let length = u32::from_be_bytes(length_bytes.try_into().unwrap()) as usize;
        Ok((tag, length, tail))
    } else {
        Err(Error::IncompleteFieldTagOrLength)
    }
}

fn read_field_value(data: &[u8], field_length: usize) -> Result<(&[u8], &[u8])> {
    if data.len() >= field_length {
        Ok(data.split_at(field_length))
    } else {
        Err(Error::IncompleteFieldValue(field_length, data.len()))
    }
}

impl<'a> FrameParser<'a> {
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_data(12, &[4, 5]);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a single data field (tag=12, value=[4, 5])
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected: &[u8] = &[4, 5];
    /// assert_eq!(Some(expected), parser.get_data(12));
    /// # Ok(()) }
    ///  ```
    pub fn new(frame_data: &[u8]) -> Result<FrameParser> {
        let (_, body) = read_frame_format(frame_data)?;
        let (field_count, mut body) = read_frame_field_count(body)?;
        let mut fields = Vec::with_capacity(field_count as usize);
        for _ in 0..field_count {
            let (tag, length, tail) = read_field_tag_and_length(body)?;
            let (value, tail) = read_field_value(tail, length)?;
            fields.push(FrameParserField { tag, value });
            body = tail
        }
        if body.is_empty() {
            Ok(FrameParser { fields })
        } else {
            Err(Error::UnexpectedData)
        }
    }

    /// Read field from frame.
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_data(12, &[4, 5]);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a single data field (tag=12, value=[4, 5])
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected: &[u8] = &[4, 5];
    /// assert_eq!(Some(expected), parser.get_data(12));
    /// # Ok(()) }
    ///  ```
    pub fn get_data(&self, search_tag: u16) -> Option<&'a [u8]> {
        for field in &self.fields {
            if field.tag == search_tag {
                return Some(field.value);
            }
        }
        None
    }

    /// Read fields from frame.
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_data(12, &[4, 5]);
    /// #     bld.add_data(12, &[3, 5]);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=[4, 5], value2=[3, 5])
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected = vec![&[4, 5], &[3, 5]];
    /// let actual: Vec<&[u8]> =  parser.get_datas(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_datas<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = &'a [u8]>
    where
        'b: 'a,
    {
        self.fields
            .iter()
            .filter(move |f| f.tag == search_tag)
            .map(|f| f.value)
    }

    /// Read u8 field from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u8`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u8(12, 9);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a single data field (tag=12, value=9)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some(9), parser.get_u8(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_u8(&self, search_tag: u16) -> Result<Option<u8>> {
        self.decode_value(search_tag, decode_u8)
    }

    /// Read u8 fields from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u8`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u8(12, 6);
    /// #     bld.add_u8(12, 9);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=6, value2=9)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<u8>> = vec![Ok(6), Ok(9)];
    /// let actual: Vec<Result<u8>> = parser.get_u8s(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_u8s<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<u8>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_u8(v))
    }

    /// Read u16 field from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u16`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u16(12, 1024);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a single data field (tag=12, value=1024)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some(1024), parser.get_u16(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_u16(&self, search_tag: u16) -> Result<Option<u16>> {
        self.decode_value(search_tag, decode_u16)
    }

    /// Read u16 fields from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u16`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u16(12, 1024);
    /// #     bld.add_u16(12, 1025);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=1024, value2=1025)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<u16>> = vec![Ok(1024), Ok(1025)];
    /// let actual: Vec<Result<u16>> = parser.get_u16s(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_u16s<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<u16>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_u16(v))
    }

    /// Read u32 field from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u32`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u32(12, 1744964616);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // single data field (tag=12, value=1744964616)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some(1744964616), parser.get_u32(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_u32(&self, search_tag: u16) -> Result<Option<u32>> {
        self.decode_value(search_tag, decode_u32)
    }

    /// Read u32 fields from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes, so long as the value
    /// is small enough to be returned in a `u32`.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u32(12, 1744964616);
    /// #     bld.add_u32(12, 1744964617);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=1744964616, value2=1744964617)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<u32>> = vec![Ok(1744964616), Ok(1744964617)];
    /// let actual: Vec<Result<u32>> = parser.get_u32s(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_u32s<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<u32>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_u32(v))
    }

    /// Read u64 field from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u64(12, 150626523450313736);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // single data field (tag=12, value=150626523450313736)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some(150626523450313736), parser.get_u64(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_u64(&self, search_tag: u16) -> Result<Option<u64>> {
        self.decode_value(search_tag, decode_u64)
    }

    /// Read u64 fields from frame
    ///
    /// Can handle data stored a 1, 2, 4 or 8 bytes.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_u64(12, 150626523450313736);
    /// #     bld.add_u64(12, 150626523450313737);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=150626523450313736, value2=150626523450313737)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<u64>> = vec![Ok(150626523450313736), Ok(150626523450313737)];
    /// let actual: Vec<Result<u64>> = parser.get_u64s(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_u64s<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<u64>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_u64(v))
    }

    /// Read bool field from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_bool(12, true);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // single data field (tag=12, value=true)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some(true), parser.get_bool(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_bool(&self, search_tag: u16) -> Result<Option<bool>> {
        self.decode_value(search_tag, decode_bool)
    }

    /// Read bool fields from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_bool(12, false);
    /// #     bld.add_bool(12, true);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=false, value2=true)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<bool>> = vec![Ok(false), Ok(true)];
    /// let actual: Vec<Result<bool>> = parser.get_bools(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_bools<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<bool>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_bool(v))
    }

    /// Attempt to find field-value of field that has the search_tag and then
    /// attempts to convert it to the required type using the supplied `decoder` function.
    fn decode_value<T, F>(&self, search_tag: u16, decoder: F) -> Result<Option<T>>
    where
        F: FnOnce(&[u8]) -> Result<T>,
    {
        self.get_data(search_tag).map(|v| decoder(v)).transpose()
    }

    /// Read str field from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_str(12, "test_str");
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // single data field (tag=12, value="test_str" in UTF-8)
    /// let parser = FrameParser::new(&frame_data)?;
    /// assert_eq!(Some("test_str"), parser.get_str(12)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_str(&self, search_tag: u16) -> Result<Option<&str>> {
        self.decode_ref(search_tag, decode_str)
    }

    /// Read str fields from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     bld.add_str(12, "hello");
    /// #     bld.add_str(12, "goodbye");
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1="hello", value2="goodbye")
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected : Vec<Result<&str>> = vec![Ok("hello"), Ok("goodbye")];
    /// let actual: Vec<Result<&str>> = parser.get_strs(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    pub fn get_strs<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<&'a str>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_str(v))
    }

    ///Read uuid field from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     let uuid = uuid::Uuid::parse_str("3011712a-d972-4a5d-bbf9-ec5fb7525c97").unwrap();
    /// #     bld.add_uuid(12, &uuid);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // single data field (tag=12, value=3011712a-d972-4a5d-bbf9-ec5fb7525c97)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected = uuid::Uuid::parse_str("3011712a-d972-4a5d-bbf9-ec5fb7525c97").unwrap();
    /// assert_eq!(Some(expected), parser.get_uuid(12)?);
    /// # Ok(()) }
    ///  ```
    #[cfg(feature = "uuid")]
    pub fn get_uuid(&self, search_tag: u16) -> Result<Option<uuid::Uuid>> {
        self.decode_value(search_tag, decode_uuid)
    }

    ///Read uuid fields from frame
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     let uuid = uuid::Uuid::parse_str("3011712a-d972-4a5d-bbf9-ec5fb7525c97").unwrap();
    /// #     bld.add_uuid(12, &uuid);
    /// #     let uuid = uuid::Uuid::parse_str("40b4e52c-1501-48d3-98eb-e2c66cb76cbf").unwrap();
    /// #     bld.add_uuid(12, &uuid);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a two fields
    /// // (tag=12, value1=3011712a-d972-4a5d-bbf9-ec5fb7525c97, value2=40b4e52c-1501-48d3-98eb-e2c66cb76cbf)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let expected = vec! [Ok(uuid::Uuid::parse_str("3011712a-d972-4a5d-bbf9-ec5fb7525c97").unwrap()),
    ///                      Ok(uuid::Uuid::parse_str("40b4e52c-1501-48d3-98eb-e2c66cb76cbf").unwrap())];
    /// let actual: Vec<Result<uuid::Uuid>> = parser.get_uuids(12).collect();
    /// assert_eq!(expected, actual);
    /// # Ok(()) }
    ///  ```
    #[cfg(feature = "uuid")]
    pub fn get_uuids<'b>(&'b self, search_tag: u16) -> impl Iterator<Item = Result<uuid::Uuid>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| decode_uuid(v))
    }

    /// Attempt to find field-value of field that has the search_tag and then
    /// attempts to convert it to the required type using the supplied `decoder` function.
    fn decode_ref<T, F>(&self, search_tag: u16, decoder: F) -> Result<Option<&T>>
    where
        F: FnOnce(&[u8]) -> Result<&T>,
        T: ?Sized,
    {
        self.get_data(search_tag).map(|v| decoder(v)).transpose()
    }

    /// Read a child frame from a frame.
    ///
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     let mut bld2 = bld.add_frame(12);
    /// #     bld2.add_u8(13, 2);
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with a
    /// // child frame (tag=12) which contains a single
    /// // value (tag=13, value=2)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let child_parser = parser.get_frame(12)?.unwrap();
    /// assert_eq!(Some(2), child_parser.get_u8(13)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_frame(&self, search_tag: u16) -> Result<Option<FrameParser>> {
        self.get_data(search_tag)
            .map(|v| FrameParser::new(v))
            .transpose()
    }

    /// Read child frames from a frame.
    /// ```
    /// # use yatlv::{FrameParser, FrameBuilder, FrameBuilderLike, Result};
    /// # fn main() -> Result<()> {
    /// # let mut frame_data = Vec::new();
    /// # {
    /// #     let mut bld = FrameBuilder::new(&mut frame_data);
    /// #     for _ in 0..2 {
    /// #         let mut child = bld.add_frame(12);
    /// #         child.add_u8(13, 2)
    /// #     }
    /// # }
    /// #
    /// // Assuming frame_data contains a frame with two
    /// // child frame (tag=12) which each contains a single
    /// // value (tag=13, value=2)
    /// let parser = FrameParser::new(&frame_data)?;
    /// let children: Vec<FrameParser> = parser.get_frames(12).map(|v| v.unwrap()).collect();
    /// assert_eq!(2, children.len());
    /// assert_eq!(Some(2), children[0].get_u8(13)?);
    /// assert_eq!(Some(2), children[1].get_u8(13)?);
    /// # Ok(()) }
    ///  ```
    pub fn get_frames<'b>(
        &'b self,
        search_tag: u16,
    ) -> impl Iterator<Item = Result<FrameParser<'a>>> + 'b
    where
        'b: 'a,
    {
        self.get_datas(search_tag).map(|v| FrameParser::new(v))
    }
}

fn decode_u8(value: &[u8]) -> Result<u8> {
    match value.len() {
        1 => Ok(value[0]),

        2 => u16::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        4 => u32::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        8 => u64::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        _ => Err(Error::IncompatibleFieldLength(value.len())),
    }
}

fn decode_u16(value: &[u8]) -> Result<u16> {
    match value.len() {
        1 => Ok(value[0] as u16),

        2 => Ok(u16::from_be_bytes(value.try_into().unwrap())),

        4 => u32::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        8 => u64::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        _ => Err(Error::IncompatibleFieldLength(value.len())),
    }
}

fn decode_u32(value: &[u8]) -> Result<u32> {
    match value.len() {
        1 => Ok(value[0] as u32),

        2 => Ok(u16::from_be_bytes(value.try_into().unwrap()) as u32),

        4 => Ok(u32::from_be_bytes(value.try_into().unwrap())),

        8 => u64::from_be_bytes(value.try_into().unwrap())
            .try_into()
            .map_err(|_| Error::IncompatibleFieldValue),

        _ => Err(Error::IncompatibleFieldLength(value.len())),
    }
}

fn decode_u64(value: &[u8]) -> Result<u64> {
    match value.len() {
        1 => Ok(value[0] as u64),

        2 => Ok(u16::from_be_bytes(value.try_into().unwrap()) as u64),

        4 => Ok(u32::from_be_bytes(value.try_into().unwrap()) as u64),

        8 => Ok(u64::from_be_bytes(value.try_into().unwrap())),

        _ => Err(Error::IncompatibleFieldLength(value.len())),
    }
}

fn decode_bool(value: &[u8]) -> Result<bool> {
    if value.len() != 1 {
        return Err(Error::IncompatibleFieldLength(value.len()));
    }
    match value[0] {
        0x00 => Ok(false),
        0xFF => Ok(true),
        _ => Err(Error::IncompatibleFieldValue),
    }
}

fn decode_str(value: &[u8]) -> Result<&str> {
    std::str::from_utf8(value).map_err(|_| Error::IncompatibleFieldValue)
}

#[cfg(feature = "uuid")]
fn decode_uuid(value: &[u8]) -> Result<uuid::Uuid> {
    uuid::Uuid::from_slice(value).map_err(|_| Error::IncompatibleFieldLength(value.len()))
}

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

    #[test]
    fn can_make_an_empty_frame() {
        let mut data = Vec::with_capacity(100);
        {
            FrameBuilder::new(&mut data);
        }
        assert_eq!(&[1, 0, 0, 0, 0], &data[..]);
    }

    #[test]
    fn can_make_an_empty_packet_frame() {
        let mut data = Vec::with_capacity(100);
        {
            PacketFrameBuilder::new(&mut data);
        }
        assert_eq!(&[0, 0, 0, 5, 1, 0, 0, 0, 0], &data[..]);
    }

    #[test]
    fn can_add_data_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_data(1022, &[9, 255]);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 2, // field length = 2
                9, 255, // field value
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_data_to_packet_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = PacketFrameBuilder::new(&mut data);
            bld.add_data(1022, &[9, 255]);
        }
        assert_eq!(
            &[
                0, 0, 0, 13, // frame size = 13
                1,  // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 2, // field length = 2
                9, 255, // field value
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_child_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            let mut child_bld = bld.add_frame(1022);
            child_bld.add_data(60, &[9, 255])
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 13, // child frame size
                1,  // child frame format
                0, 0, 0, 1, // child frame field count
                0, 60, // field-tag in child frame
                0, 0, 0, 2, // field-length in child frame
                9, 255 // field-value in child frame
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_child_to_packet_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = PacketFrameBuilder::new(&mut data);
            let mut child_bld = bld.add_frame(1022);
            child_bld.add_data(60, &[9, 255])
        }
        assert_eq!(
            &[
                0, 0, 0, 24, // packet size
                1,  // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 13, // child frame size
                1,  // child frame format
                0, 0, 0, 1, // child frame field count
                0, 60, // field-tag in child frame
                0, 0, 0, 2, // field-length in child frame
                9, 255 // field-value in child frame
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_bool_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_bool(1022, true);
            bld.add_bool(1021, false);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 2, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 1,   // field length = 2
                255, // field value
                3, 253, // tag = 1021
                0, 0, 0, 1, // field length = 2
                0  // field value
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_u8_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(1022, 89);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 1,  // field length = 2
                89  // field value
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_u16_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u16(1022, 1009);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 2, // field length = 2
                3, 241 // field value (1009)
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_u32_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u32(1022, 156090);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 4, // field length = 2
                0, 2, 97, 186 // field value (156090)
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_u64_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u64(1022, 156234234090);
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 8, // field length = 2
                0, 0, 0, 36, 96, 73, 56, 234 // field value (156234234090)
            ],
            &data[..]
        );
    }

    #[test]
    fn can_add_utf8_to_frame() {
        let mut data = Vec::with_capacity(100);
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_str(1022, "hello");
        }
        assert_eq!(
            &[
                1, // frame format
                0, 0, 0, 1, // field count = 1
                3, 254, // tag = 1022
                0, 0, 0, 5, // field length = 2
                104, 101, 108, 108, 111 // field value (156234234090)
            ],
            &data[..]
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_there_is_not_enough_data_for_frame_format() {
        let data = &[]; // need four bytes for a field count.
        assert_eq!(
            Some(Error::IncompleteFrameFormat),
            FrameParser::new(data).err()
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_frame_format_is_not_recognized() {
        let data = &[8]; // need four bytes for a field count.
        assert_eq!(
            Some(Error::InvalidFrameFormat(8)),
            FrameParser::new(data).err()
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_there_is_not_enough_data_for_field_count() {
        let data = &[1, 0, 0, 0]; // need four bytes for a field count.
        assert_eq!(
            Some(Error::IncompleteFrameFieldCount),
            FrameParser::new(data).err()
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_there_is_not_enough_data_for_field_tag_and_length() {
        let data = &[
            1, // frame format
            0, 0, 0, 1, // field count = 1
            0, 1, // tag = 1
            0, 0, 0, // incomplete field length
        ];
        assert_eq!(
            Some(Error::IncompleteFieldTagOrLength),
            FrameParser::new(data).err()
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_there_is_not_enough_data_for_a_field_value() {
        let data = &[
            1, // frame format
            0, 0, 0, 1, // field count = 1
            0, 1, // tag = 1
            0, 0, 0, 4, // field length = 4
            1, 2, 3, // incomplete value
        ];
        assert_eq!(
            Some(Error::IncompleteFieldValue(4, 3)),
            FrameParser::new(data).err()
        );
    }

    #[test]
    fn can_not_parse_a_frame_if_there_is_excess_data() {
        let data = &[
            1, // frame format
            0, 0, 0, 1, // field count = 1
            0, 1, // tag = 1
            0, 0, 0, 4, // field length = 4
            1, 2, 3, 4, // incomplete value
            5, // excess data
        ];
        assert_eq!(Some(Error::UnexpectedData), FrameParser::new(data).err());
    }

    #[test]
    fn can_read_data_from_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 1, // field count = 1
            0, 1, // tag = 1
            0, 0, 0, 4, // field length = 4
            1, 2, 3, 4, //
        ];
        let frame = FrameParser::new(data).unwrap();
        assert_eq!(&[1, 2, 3, 4], frame.get_data(1).unwrap());
    }

    #[test]
    fn can_read_datas_from_a_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 3, // field count = 3
            0, 1, // tag = 1
            0, 0, 0, 2, // field length = 2
            10, 11, //
            0, 2, // tag = 2, will be skipped
            0, 0, 0, 2, // field length = 2
            20, 22, //
            0, 1, // tag = 1
            0, 0, 0, 2, // field length = 2
            30, 33, //
        ];
        let frame = FrameParser::new(data).unwrap();
        let expected = vec![&[10, 11], &[30, 33]];
        let actual: Vec<&[u8]> = frame.get_datas(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_attempt_to_read_data_from_a_frame_if_it_is_not_there() {
        let data = &[
            1, // frame format
            0, 0, 0, 1, // field count = 1
            0, 1, // tag = 1
            0, 0, 0, 4, // field length = 4
            1, 2, 3, 4, //
        ];
        let frame = FrameParser::new(data).unwrap();
        assert_eq!(None, frame.get_data(3));
    }

    #[test]
    fn can_not_decode_u8_with_zero_bytes() {
        assert_eq!(
            Some(Error::IncompatibleFieldLength(0)),
            decode_u8(&[]).err()
        );
    }

    #[test]
    fn can_decode_compatible_values_into_u8() {
        assert_eq!(Ok(8), decode_u8(&[8]));
        assert_eq!(Ok(8), decode_u8(&[0, 8]));
        assert_eq!(Ok(8), decode_u8(&[0, 0, 0, 8]));
        assert_eq!(Ok(8), decode_u8(&[0, 0, 0, 0, 0, 0, 0, 8]));
    }

    #[test]
    fn can_not_decode_incompatible_values_into_u8() {
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u8(&[1, 8]).err()
        );
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u8(&[0, 0, 1, 8]).err()
        );
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u8(&[0, 0, 0, 0, 0, 0, 1, 8]).err()
        );
    }

    #[test]
    fn can_read_u8_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 250);
            bld.add_u16(200, 251);
            bld.add_u32(300, 252);
            bld.add_u64(400, 253);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(250), frame.get_u8(100).unwrap());
        assert_eq!(Some(251), frame.get_u8(200).unwrap());
        assert_eq!(Some(252), frame.get_u8(300).unwrap());
        assert_eq!(Some(253), frame.get_u8(400).unwrap());
    }

    #[test]
    fn can_read_u8s_from_a_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 3, // field count = 3
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            10, //
            0, 2, // tag = 2, will be skipped
            0, 0, 0, 1,  // field length = 2
            20, //
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            30, //
        ];
        let frame = FrameParser::new(data).unwrap();
        let expected: Vec<Result<u8>> = vec![Ok(10), Ok(30)];
        let actual: Vec<Result<u8>> = frame.get_u8s(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_not_decode_u16_with_zero_bytes() {
        assert_eq!(
            Some(Error::IncompatibleFieldLength(0)),
            decode_u16(&[]).err()
        );
    }

    #[test]
    fn can_decode_compatible_values_into_u16() {
        assert_eq!(Ok(8), decode_u16(&[8]));
        assert_eq!(Ok(3080), decode_u16(&[12, 8]));
        assert_eq!(Ok(3080), decode_u16(&[0, 0, 12, 8]));
        assert_eq!(Ok(3080), decode_u16(&[0, 0, 0, 0, 0, 0, 12, 8]));
    }

    #[test]
    fn can_not_decode_incompatible_values_into_u16() {
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u16(&[0, 1, 255, 255]).err()
        );
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u16(&[0, 0, 0, 0, 0, 1, 255, 255]).err()
        );
    }

    #[test]
    fn can_read_u16_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 90);
            bld.add_u16(200, 1025);
            bld.add_u32(300, 1026);
            bld.add_u64(400, 1027);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(90), frame.get_u16(100).unwrap());
        assert_eq!(Some(1025), frame.get_u16(200).unwrap());
        assert_eq!(Some(1026), frame.get_u16(300).unwrap());
        assert_eq!(Some(1027), frame.get_u16(400).unwrap());
    }

    #[test]
    fn can_read_u16s_from_a_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 3, // field count = 3
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            10, //
            0, 2, // tag = 2, will be skipped
            0, 0, 0, 1,  // field length = 2
            20, //
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            30, //
        ];
        let frame = FrameParser::new(data).unwrap();
        let expected: Vec<Result<u16>> = vec![Ok(10), Ok(30)];
        let actual: Vec<Result<u16>> = frame.get_u16s(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_not_decode_u32_with_zero_bytes() {
        assert_eq!(
            Some(Error::IncompatibleFieldLength(0)),
            decode_u32(&[]).err()
        );
    }

    #[test]
    fn can_decode_compatible_values_into_u32() {
        assert_eq!(Ok(8), decode_u32(&[8]));
        assert_eq!(Ok(3080), decode_u32(&[12, 8]));
        assert_eq!(Ok(1744964616), decode_u32(&[104, 2, 12, 8]));
        assert_eq!(Ok(1744964616), decode_u32(&[0, 0, 0, 0, 104, 2, 12, 8]));
    }

    #[test]
    fn can_not_decode_incompatible_values_into_u32() {
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_u32(&[0, 0, 0, 1, 255, 255, 255, 255]).err()
        );
    }

    #[test]
    fn can_read_u32_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 90);
            bld.add_u16(200, 1025);
            bld.add_u32(300, 1744964616);
            bld.add_u64(400, 1744964617);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(90), frame.get_u32(100).unwrap());
        assert_eq!(Some(1025), frame.get_u32(200).unwrap());
        assert_eq!(Some(1744964616), frame.get_u32(300).unwrap());
        assert_eq!(Some(1744964617), frame.get_u32(400).unwrap());
    }

    #[test]
    fn can_read_u32s_from_a_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 3, // field count = 3
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            10, //
            0, 2, // tag = 2, will be skipped
            0, 0, 0, 1,  // field length = 2
            20, //
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            30, //
        ];
        let frame = FrameParser::new(data).unwrap();
        let expected: Vec<Result<u32>> = vec![Ok(10), Ok(30)];
        let actual: Vec<Result<u32>> = frame.get_u32s(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_not_decode_u64_with_zero_bytes() {
        assert_eq!(
            Some(Error::IncompatibleFieldLength(0)),
            decode_u64(&[]).err()
        );
    }

    #[test]
    fn can_decode_compatible_values_into_u64() {
        assert_eq!(Ok(8), decode_u64(&[8]));
        assert_eq!(Ok(3080), decode_u64(&[12, 8]));
        assert_eq!(Ok(1744964616), decode_u64(&[104, 2, 12, 8]));
        assert_eq!(
            Ok(150626523450313736),
            decode_u64(&[2, 23, 34, 6, 104, 2, 12, 8])
        );
    }

    #[test]
    fn can_read_u64_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 90);
            bld.add_u16(200, 1025);
            bld.add_u32(300, 1744964616);
            bld.add_u64(400, 150626523450313736);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(90), frame.get_u64(100).unwrap());
        assert_eq!(Some(1025), frame.get_u64(200).unwrap());
        assert_eq!(Some(1744964616), frame.get_u64(300).unwrap());
        assert_eq!(Some(150626523450313736), frame.get_u64(400).unwrap());
    }

    #[test]
    fn can_read_u64s_from_a_frame() {
        let data = &[
            1, // frame format
            0, 0, 0, 3, // field count = 3
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            10, //
            0, 2, // tag = 2, will be skipped
            0, 0, 0, 1,  // field length = 2
            20, //
            0, 1, // tag = 1
            0, 0, 0, 1,  // field length = 2
            30, //
        ];
        let frame = FrameParser::new(data).unwrap();
        let expected: Vec<Result<u64>> = vec![Ok(10), Ok(30)];
        let actual: Vec<Result<u64>> = frame.get_u64s(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_not_decode_bool_with_zero_bytes() {
        assert_eq!(
            Some(Error::IncompatibleFieldLength(0)),
            decode_bool(&[]).err()
        );
    }

    #[test]
    fn can_decode_compatible_values_into_bool() {
        assert_eq!(Ok(false), decode_bool(&[0x00]));
        assert_eq!(Ok(true), decode_bool(&[0xFF]));
    }

    #[test]
    fn can_not_decode_incompatible_values_into_bool() {
        assert_eq!(
            Some(Error::IncompatibleFieldValue),
            decode_bool(&[0x01]).err()
        );
    }

    #[test]
    fn can_read_bool_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_bool(100, true);
            bld.add_bool(200, false);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(true), frame.get_bool(100).unwrap());
        assert_eq!(Some(false), frame.get_bool(200).unwrap());
    }

    #[test]
    fn can_read_bools_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_bool(1, false);
            bld.add_bool(2, false); // will be ignored
            bld.add_bool(1, true);
        }
        let frame = FrameParser::new(&data).unwrap();
        let expected: Vec<Result<bool>> = vec![Ok(false), Ok(true)];
        let actual: Vec<Result<bool>> = frame.get_bools(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_read_str_from_a_frame() {
        let test_str = "short test string";
        let mut data = Vec::new();

        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_str(100, test_str);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(test_str), frame.get_str(100).unwrap());
    }

    #[test]
    fn can_read_strs_from_a_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_str(1, "hello");
            bld.add_str(2, "welcome"); // will be ignored
            bld.add_str(1, "goodbye");
        }
        let frame = FrameParser::new(&data).unwrap();
        let expected: Vec<Result<&str>> = vec![Ok("hello"), Ok("goodbye")];
        let actual: Vec<Result<&str>> = frame.get_strs(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    #[cfg(feature = "uuid")]
    fn can_read_uuid_from_a_frame() {
        let test_uuid = uuid::Uuid::parse_str("40b4e52c-1501-48d3-98eb-e2c66cb76cbf").unwrap();
        let mut data = Vec::new();

        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_uuid(100, &test_uuid);
        }

        let frame = FrameParser::new(&data).unwrap();
        assert_eq!(Some(test_uuid), frame.get_uuid(100).unwrap());
    }

    #[test]
    #[cfg(feature = "uuid")]
    fn can_read_uuids_from_a_frame() {
        let test_uuid1 = uuid::Uuid::parse_str("40b4e52c-1501-48d3-98eb-e2c66cb76cbf").unwrap();
        let test_uuid2 = uuid::Uuid::parse_str("e6bb35e5-547b-4930-b72c-5d50aa60ff49").unwrap();
        let test_uuid3 = uuid::Uuid::parse_str("451f82e5-c17a-4843-a9c7-5ff3f7ae20fd").unwrap();

        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_uuid(1, &test_uuid1);
            bld.add_uuid(2, &test_uuid2); // will be ignored
            bld.add_uuid(1, &test_uuid3);
        }
        let frame = FrameParser::new(&data).unwrap();
        let expected: Vec<Result<uuid::Uuid>> = vec![Ok(test_uuid1), Ok(test_uuid3)];
        let actual: Vec<Result<uuid::Uuid>> = frame.get_uuids(1).collect();
        assert_eq!(expected, actual);
    }

    #[test]
    fn can_read_child_frame() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 1);
            let mut bld2 = bld.add_frame(200);
            bld2.add_u8(300, 3);
        }

        let frame = FrameParser::new(&data).unwrap();
        let child_frame = frame.get_frame(200).unwrap().unwrap();
        assert_eq!(Some(3), child_frame.get_u8(300).unwrap());
    }

    #[test]
    fn can_read_child_frames() {
        let mut data = Vec::new();
        {
            let mut bld = FrameBuilder::new(&mut data);
            bld.add_u8(100, 1);
            for i in 0..2 {
                let mut bld2 = bld.add_frame(200);
                bld2.add_u8(300, i);
            }
        }

        let frame = FrameParser::new(&data).unwrap();
        let child_frame: Vec<FrameParser> = frame.get_frames(200).map(|v| v.unwrap()).collect();

        assert_eq!(Some(0), child_frame[0].get_u8(300).unwrap());
        assert_eq!(Some(1), child_frame[1].get_u8(300).unwrap());
    }
}