rs-pfcp 0.4.0

High-performance Rust implementation of PFCP (Packet Forwarding Control Protocol) for 5G networks with 100% 3GPP TS 29.244 Release 18 compliance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
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
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
//! Information Elements for PFCP messages.

use crate::error::PfcpError;

pub mod access_availability_control_information;
pub mod access_availability_information;
pub mod access_availability_report;
pub mod activate_predefined_rules;
pub mod activation_time;
pub mod add_mbs_unicast_parameters;
pub mod additional_monitoring_time;
pub mod additional_usage_reports_information;
pub mod aggregated_urr_id;
pub mod aggregated_urrs;
pub mod alternative_smf_ip_address;
pub mod apn_dnn;
pub mod application_detection_information;
pub mod application_id;
pub mod application_ids_pfds;
pub mod application_instance_id;
pub mod apply_action;
pub mod area_session_id;
pub mod atsss_control_parameters;
pub mod atsss_ll_control_information;
pub mod atsss_ll_information;
pub mod atsss_ll_parameters;
pub mod average_packet_delay;
pub mod averaging_window;
pub mod bar;
pub mod bar_id;
pub mod bridge_management_information_container;
pub mod c_tag;
pub mod called_number;
pub mod calling_number;
pub mod cause;
pub mod clock_drift_control_information;
pub mod clock_drift_report;
pub mod configured_time_domain;
pub mod cp_function_features;
pub mod cp_ip_address;
pub mod cp_pfcp_entity_ip_address;
pub mod create_bar;
pub mod create_bridge_info_for_tsc;
pub mod create_far;
pub mod create_mar;
pub mod create_pdr;
pub mod create_qer;
pub mod create_srr;
pub mod create_traffic_endpoint;
pub mod create_urr;
pub mod created_bridge_info_for_tsc;
pub mod created_l2tp_session;
pub mod created_pdr;
pub mod created_traffic_endpoint;
pub mod cumulative_rate_ratio_measurement;
pub mod cumulative_rate_ratio_threshold;
pub mod data_network_access_identifier;
pub mod data_status;
pub mod deactivate_predefined_rules;
pub mod deactivation_time;
pub mod destination_interface;
pub mod direct_reporting_information;
pub mod dl_buffering_duration;
pub mod dl_buffering_suggested_packet_count;
pub mod dl_data_packets_size;
pub mod dl_flow_level_marking;
pub mod dl_periodicity;
pub mod dns_query_response_filter;
pub mod dns_server_address;
pub mod downlink_data_notification_delay;
pub mod downlink_data_report;
pub mod downlink_data_service_information;
pub mod dropped_dl_traffic_threshold;
pub mod dscp_to_ppi_control_information;
pub mod dscp_to_ppi_mapping_information;
pub mod dstt_port_number;
pub mod duplicating_parameters;
pub mod duration_measurement;
pub mod end_time;
pub mod error_indication_report;
pub mod ethernet_context_information;
pub mod ethernet_filter_id;
pub mod ethernet_filter_properties;
pub mod ethernet_inactivity_timer;
pub mod ethernet_packet_filter;
pub mod ethernet_pdu_session_information;
pub mod ethernet_traffic_information;
pub mod ethertype;
pub mod event_notification_uri;
pub mod event_quota;
pub mod event_threshold;
pub mod event_time_stamp;
pub mod extended_dl_buffering_notification_policy;
pub mod f_teid;
pub mod failed_rule_id;
pub mod far_id;
pub mod flow_information;
pub mod forwarding_parameters;
pub mod forwarding_policy;
pub mod fq_csid;
pub mod framed_ipv6_route;
pub mod framed_route;
pub mod framed_routing;
pub mod fseid;
pub mod gate_status;
pub mod gbr;
pub mod graceful_release_period;
pub mod group_id;
pub mod gtpu_path_interface_type;
pub mod gtpu_path_qos_control_information;
pub mod gtpu_path_qos_report;
pub mod header_enrichment;
pub mod hplmn_s_nssai;
pub mod inactivity_detection_time;
pub mod ip_address_and_port_number_replacement;
pub mod ip_multicast_address;
pub mod ip_multicast_addressing_info;
pub mod ip_version;
pub mod join_ip_multicast_information_within_usage_report;
pub mod l2tp_session_indications;
pub mod l2tp_session_information;
pub mod l2tp_tunnel_information;
pub mod l2tp_user_authentication;
pub mod leave_ip_multicast_information_within_usage_report;
pub mod link_specific_multipath_ip_address;
pub mod linked_urr_id;
pub mod lns_address;
pub mod load_control_information;
pub mod local_ingress_tunnel;
pub mod mac_address;
pub mod mac_addresses_detected;
pub mod mac_addresses_removed;
pub mod mapped_n6_ip_address;
pub mod mar_id;
pub mod maximum_packet_delay;
pub mod maximum_receive_unit;
pub mod mbr;
pub mod mbs_multicast_parameters;
pub mod mbs_session_identifier;
pub mod mbs_session_n4_control_information;
pub mod mbs_session_n4_information;
pub mod mbs_session_n4mb_control_information;
pub mod mbs_session_n4mb_information;
pub mod mbs_unicast_parameters_id;
pub mod mbsn4_resp_flags;
pub mod mbsn4mb_req_flags;
pub mod measurement_indication;
pub mod measurement_information;
pub mod measurement_method;
pub mod measurement_period;
pub mod media_transport_protocol;
pub mod metadata;
pub mod metric;
pub mod minimum_packet_delay;
pub mod minimum_wait_time;
pub mod monitoring_time;
pub mod mpquic_address_information;
pub mod mpquic_control_information;
pub mod mpquic_parameters;
pub mod mptcp_address_information;
pub mod mptcp_applicable_indication;
pub mod mptcp_control_information;
pub mod mptcp_parameters;
pub mod mt_sdt_control_information;
pub mod mtedt_control_information;
pub mod multicast_transport_information;
pub mod multiplier;
pub mod n6_jitter_measurement;
pub mod n6_routing_information;
pub mod nbns_server_address;
pub mod network_instance;
pub mod nf_instance_id;
pub mod node_id;
pub mod node_report_type;
pub mod non_tgpp_access_forwarding_action_information;
pub mod notification_correlation_id;
pub mod number_of_reports;
pub mod number_of_ue_ip_addresses;
pub mod nwtt_port_number;
pub mod oci_flags;
pub mod offending_ie;
pub mod offending_ie_information;
pub mod outer_header_creation;
pub mod outer_header_removal;
pub mod overload_control_information;
pub mod packet_delay_thresholds;
pub mod packet_rate;
pub mod packet_rate_status;
pub mod packet_rate_status_report;
pub mod packet_rate_status_report_within_session_modification_response;
pub mod packet_replication_and_detection_carry_on_information;
pub mod paging_policy_indicator;
pub mod partial_failure_information;
pub mod path_failure_report;
pub mod pdi;
pub mod pdn_type;
pub mod pdr_id;
pub mod peer_up_restart_report;
pub mod pfcp_association_release_request;
pub mod pfcp_session_change_info;
pub mod pfcp_session_retention_information;
pub mod pfcpas_req_flags;
pub mod pfcpas_rsp_flags;
pub mod pfcpau_req_flags;
pub mod pfcpsdrsp_flags;
pub mod pfcpse_req_flags;
pub mod pfcpsm_req_flags;
pub mod pfcpsr_req_flags;
pub mod pfcpsrrsp_flags;
pub mod pfd_contents;
pub mod pfd_context;
pub mod pmf_address_information;
pub mod pmf_control_information;
pub mod pmf_parameters;
pub mod port_management_information_container;
pub mod precedence;
pub mod predefined_rules_name;
pub mod priority;
pub mod protocol_description;
pub mod provide_atsss_control_information;
pub mod provide_rds_configuration_information;
pub mod proxying;
pub mod qer_control_indications;
pub mod qer_correlation_id;
pub mod qer_id;
pub mod qer_indications;
pub mod qfi;
pub mod qos_information_in_gtpu_path_qos_report;
pub mod qos_monitoring_measurement;
pub mod qos_monitoring_per_qos_flow_control_information;
pub mod qos_monitoring_report;
pub mod qos_report_trigger;
pub mod query_packet_rate_status_within_session_modification_request;
pub mod query_urr;
pub mod query_urr_reference;
pub mod quota_holding_time;
pub mod quota_validity_time;
pub mod rat_type;
pub mod rds_configuration_information;
pub mod recovery_time_stamp;
pub mod redirect_information;
pub mod redundant_transmission_forwarding_parameters;
pub mod redundant_transmission_parameters;
pub mod remote_gtpu_peer;
pub mod remove_bar;
pub mod remove_far;
pub mod remove_mar;
pub mod remove_mbs_unicast_parameters;
pub mod remove_pdr;
pub mod remove_qer;
pub mod remove_srr;
pub mod remove_traffic_endpoint;
pub mod remove_urr;
pub mod report_type;
pub mod reporting_control_information;
pub mod reporting_flags;
pub mod reporting_frequency;
pub mod reporting_suggestion_info;
pub mod reporting_thresholds;
pub mod reporting_triggers;
pub mod requested_access_availability_information;
pub mod requested_clock_drift_information;
pub mod requested_qos_monitoring;
pub mod rqi;
pub mod rtp_header_extension_additional_information;
pub mod rtp_header_extension_id;
pub mod rtp_header_extension_information;
pub mod rtp_header_extension_type;
pub mod rtp_payload_format;
pub mod rtp_payload_information;
pub mod rtp_payload_type;
pub mod s_tag;
pub mod sdf_filter;
pub mod sequence_number;
pub mod session_report;
pub mod smf_set_id;
pub mod snssai;
pub mod source_interface;
pub mod source_ip_address;
pub mod srr_id;
pub mod start_time;
pub mod steering_functionality;
pub mod steering_mode;
pub mod steering_mode_indicator;
pub mod subsequent_event_quota;
pub mod subsequent_event_threshold;
pub mod subsequent_time_quota;
pub mod subsequent_time_threshold;
pub mod subsequent_volume_quota;
pub mod subsequent_volume_threshold;
pub mod suggested_buffering_packets_count;
pub mod tgpp_access_forwarding_action_information;
pub mod three_gpp_interface_type;
pub mod thresholds;
pub mod time_of_first_packet;
pub mod time_of_last_packet;
pub mod time_offset_measurement;
pub mod time_offset_threshold;
pub mod time_quota;
pub mod time_quota_mechanism;
pub mod time_threshold;
pub mod timer;
pub mod tl_container;
pub mod trace_information;
pub mod traffic_endpoint_id;
pub mod traffic_parameter_measurement_control_information;
pub mod traffic_parameter_measurement_indication;
pub mod traffic_parameter_measurement_report;
pub mod traffic_parameter_threshold;
pub mod transport_delay_reporting;
pub mod transport_level_marking;
pub mod transport_mode;
pub mod tsc_management_information_within_session_modification_request;
pub mod tsc_management_information_within_session_modification_response;
pub mod tsc_management_information_within_session_report_request;
pub mod tsn_bridge_id;
pub mod tsn_time_domain_number;
pub mod tunnel_password;
pub mod tunnel_preference;
pub mod ue_ip_address;
pub mod ue_ip_address_pool_identity;
pub mod ue_ip_address_pool_information;
pub mod ue_ip_address_usage_information;
pub mod ue_level_measurements_configuration;
pub mod ul_periodicity;
pub mod up_function_features;
pub mod update_bar;
pub mod update_bar_within_session_report_response;
pub mod update_duplicating_parameters;
pub mod update_far;
pub mod update_forwarding_parameters;
pub mod update_mar;
pub mod update_non_tgpp_access_forwarding_action_information;
pub mod update_pdr;
pub mod update_qer;
pub mod update_srr;
pub mod update_tgpp_access_forwarding_action_information;
pub mod update_traffic_endpoint;
pub mod update_urr;
pub mod updated_pdr;
pub mod ur_seqn;
pub mod uri;
pub mod urr_id;
pub mod usage_information;
pub mod usage_report;
pub mod usage_report_sdr;
pub mod usage_report_smr;
pub mod usage_report_srr;
pub mod usage_report_trigger;
pub mod user_id;
pub mod user_plane_inactivity_timer;
pub mod user_plane_path_failure_report;
pub mod user_plane_path_recovery_report;
pub mod validity_timer;
pub mod vendor_specific_node_report_type;
pub mod volume_measurement;
pub mod volume_quota;
pub mod weight;

pub mod volume_threshold;

// Re-export commonly used IE types for convenience
pub use alternative_smf_ip_address::AlternativeSmfIpAddress;
pub use gtpu_path_qos_control_information::GtpuPathQosControlInformation;
pub use nf_instance_id::NfInstanceId;
pub use node_id::NodeId;
pub use pfcp_session_change_info::PfcpSessionChangeInfo;
pub use pfcp_session_retention_information::PfcpSessionRetentionInformation;
pub use pfcpas_req_flags::PfcpasReqFlags;
pub use pfcpas_rsp_flags::PfcpasRspFlags;
pub use query_urr::QueryUrr;
pub use recovery_time_stamp::RecoveryTimeStamp;
pub use smf_set_id::SmfSetId;
pub use traffic_endpoint_id::TrafficEndpointId;
pub use update_duplicating_parameters::UpdateDuplicatingParameters;
pub use user_plane_path_recovery_report::UserPlanePathRecoveryReport;

// IE Type definitions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u16)]
pub enum IeType {
    CreatePdr = 1,
    Pdi = 2,
    CreateFar = 3,
    ForwardingParameters = 4,
    DuplicatingParameters = 5,
    CreateUrr = 6,
    CreateQer = 7,
    CreatedPdr = 8,
    UpdatePdr = 9,
    UpdateFar = 10,
    UpdateForwardingParameters = 11,
    UpdateBarWithinSessionReportResponse = 12,
    UpdateUrr = 13,
    UpdateQer = 14,
    RemovePdr = 15,
    RemoveFar = 16,
    RemoveUrr = 17,
    RemoveQer = 18,
    Cause = 19,
    SourceInterface = 20,
    Fteid = 21,
    NetworkInstance = 22,
    SdfFilter = 23,
    ApplicationId = 24,
    GateStatus = 25,
    Mbr = 26,
    Gbr = 27,
    QerCorrelationId = 28,
    Precedence = 29,
    TransportLevelMarking = 30,
    VolumeThreshold = 31,
    TimeThreshold = 32,
    MonitoringTime = 33,
    SubsequentVolumeThreshold = 34,
    SubsequentTimeThreshold = 35,
    InactivityDetectionTime = 36,
    ReportingTriggers = 37,
    RedirectInformation = 38,
    ReportType = 39,
    OffendingIe = 40,
    ForwardingPolicy = 41,
    DestinationInterface = 42,
    UpFunctionFeatures = 43,
    ApplyAction = 44,
    DownlinkDataServiceInformation = 45,
    DownlinkDataNotificationDelay = 46,
    DlBufferingDuration = 47,
    DlBufferingSuggestedPacketCount = 48,
    PfcpsmReqFlags = 49,
    PfcpsrrspFlags = 50,
    LoadControlInformation = 51,
    SequenceNumber = 52,
    Metric = 53,
    OverloadControlInformation = 54,
    Timer = 55,
    PdrId = 56,
    Fseid = 57,
    ApplicationIdsPfds = 58,
    PfdContext = 59,
    NodeId = 60,
    PfdContents = 61,
    MeasurementMethod = 62,
    UsageReportTrigger = 63,
    MeasurementPeriod = 64,
    FqCsid = 65,
    VolumeMeasurement = 66,
    DurationMeasurement = 67,
    ApplicationDetectionInformation = 68,
    TimeOfFirstPacket = 69,
    TimeOfLastPacket = 70,
    QuotaHoldingTime = 71,
    DroppedDlTrafficThreshold = 72,
    VolumeQuota = 73,
    TimeQuota = 74,
    StartTime = 75,
    EndTime = 76,
    QueryUrr = 77,
    UsageReportWithinSessionModificationResponse = 78,
    UsageReportWithinSessionDeletionResponse = 79,
    UsageReportWithinSessionReportRequest = 80,
    UrrId = 81,
    LinkedUrrId = 82,
    DownlinkDataReport = 83,
    OuterHeaderCreation = 84,
    CpFunctionFeatures = 89,
    UsageInformation = 90,
    ApplicationInstanceId = 91,
    FlowInformation = 92,
    UeIpAddress = 93,
    PacketRate = 94,
    OuterHeaderRemoval = 95,
    RecoveryTimeStamp = 96,
    DlFlowLevelMarking = 97,
    HeaderEnrichment = 98,
    ErrorIndicationReport = 99,
    MeasurementInformation = 100,
    NodeReportType = 101,
    UserPlanePathFailureReport = 102,
    RemoteGtpuPeer = 103,
    UrSeqn = 104,
    UpdateDuplicatingParameters = 105,
    ActivatePredefinedRules = 106,
    DeactivatePredefinedRules = 107,
    FarId = 108,
    QerId = 109,
    OciFlags = 110,
    PfcpAssociationReleaseRequest = 111,
    GracefulReleasePeriod = 112,
    PdnType = 113,
    FailedRuleId = 114,
    TimeQuotaMechanism = 115,
    UserPlaneIpResourceInformation = 116,
    UserPlaneInactivityTimer = 117,
    AggregatedUrrs = 118,
    Multiplier = 119,
    AggregatedUrrId = 120,
    SubsequentVolumeQuota = 121,
    SubsequentTimeQuota = 122,
    Rqi = 123,
    Qfi = 124,
    QueryUrrReference = 125,
    AdditionalUsageReportsInformation = 126,
    CreateTrafficEndpoint = 127,
    CreatedTrafficEndpoint = 128,
    UpdateTrafficEndpoint = 129,
    RemoveTrafficEndpoint = 130,
    TrafficEndpointId = 131,
    CreateBar = 85,
    UpdateBar = 86,
    RemoveBar = 87,
    BarId = 88,
    // Ethernet-related IEs
    EthernetPacketFilter = 132,
    MacAddress = 133,
    CTag = 134,
    STag = 135,
    Ethertype = 136,
    Proxying = 137,
    EthernetFilterId = 138,
    EthernetFilterProperties = 139,
    SuggestedBufferingPacketsCount = 140,
    UserId = 141,
    EthernetPduSessionInformation = 142,
    EthernetTrafficInformation = 143,
    MacAddressesDetected = 144,
    MacAddressesRemoved = 145,
    EthernetInactivityTimer = 146,
    AdditionalMonitoringTime = 147,
    EventQuota = 148,
    EventThreshold = 149,
    SubsequentEventQuota = 150,
    SubsequentEventThreshold = 151,
    TraceInformation = 152,
    FramedRoute = 153,
    FramedRouting = 154,
    FramedIpv6Route = 155,
    EventTimeStamp = 156,
    AveragingWindow = 157,
    PagingPolicyIndicator = 158,
    ApnDnn = 159,
    TgppInterfaceType = 160,
    PfcpsrReqFlags = 161,
    PfcpauReqFlags = 162,
    ActivationTime = 163,
    DeactivationTime = 164,
    CreateMar = 165,
    TgppAccessForwardingActionInformation = 166,
    NonTgppAccessForwardingActionInformation = 167,
    RemoveMar = 168,
    UpdateMar = 169,
    MarId = 170,
    SteeringFunctionality = 171,
    SteeringMode = 172,
    Weight = 173,
    Priority = 174,
    UpdateTgppAccessForwardingActionInformation = 175,
    UpdateNonTgppAccessForwardingActionInformation = 176,
    UeIpAddressPoolIdentity = 177,
    AlternativeSmfIpAddress = 178,
    PacketReplicationAndDetectionCarryOnInformation = 179,
    SmfSetId = 180,
    QuotaValidityTime = 181,
    NumberOfReports = 182,
    PfcpSessionRetentionInformation = 183,
    PfcpasRspFlags = 184,
    CpPfcpEntityIpAddress = 185,
    PfcpseReqFlags = 186,
    UserPlanePathRecoveryReport = 187,
    IpMulticastAddressingInfo = 188,
    JoinIpMulticastInformationWithinUsageReport = 189,
    LeaveIpMulticastInformationWithinUsageReport = 190,
    IpMulticastAddress = 191,
    SourceIpAddress = 192,
    PacketRateStatus = 193,
    // TSN (Time-Sensitive Networking) related IEs
    CreateBridgeInfoForTsc = 194,
    CreatedBridgeInfoForTsc = 195,
    DsttPortNumber = 196,
    NwttPortNumber = 197,
    TsnBridgeId = 198,
    TscManagementInformationWithinSessionModificationRequest = 199,
    TscManagementInformationWithinSessionModificationResponse = 200,
    TscManagementInformationWithinSessionReportRequest = 201,
    PortManagementInformationContainer = 202,
    ClockDriftControlInformation = 203,
    RequestedClockDriftInformation = 204,
    ClockDriftReport = 205,
    TsnTimeDomainNumber = 206,
    TimeOffsetThreshold = 207,
    CumulativeRateRatioThreshold = 208,
    TimeOffsetMeasurement = 209,
    CumulativeRateRatioMeasurement = 210,
    RemoveSrr = 211,
    CreateSrr = 212,
    UpdateSrr = 213,
    SessionReport = 214,
    SrrId = 215,
    AccessAvailabilityControlInformation = 216,
    RequestedAccessAvailabilityInformation = 217,
    AccessAvailabilityReport = 218,
    AccessAvailabilityInformation = 219,
    ProvideAtsssControlInformation = 220,
    AtsssControlParameters = 221,
    MptcpControlInformation = 222,
    AtsssLlControlInformation = 223,
    PmfControlInformation = 224,
    MptcpParameters = 225,
    AtsssLlParameters = 226,
    PmfParameters = 227,
    MptcpAddressInformation = 228,
    UeLinkSpecificIpAddress = 229,
    PmfAddressInformation = 230,
    AtsssLlInformation = 231,
    DataNetworkAccessIdentifier = 232,
    UeIpAddressPoolInformation = 233,
    AveragePacketDelay = 234,
    MinimumPacketDelay = 235,
    MaximumPacketDelay = 236,
    QosReportTrigger = 237,
    GtpuPathQosControlInformation = 238,
    GtpuPathQosReport = 239,
    QosInformationInGtpuPathQosReport = 240,
    GtpuPathInterfaceType = 241,
    QosMonitoringPerQosFlowControlInformation = 242,
    RequestedQosMonitoring = 243,
    ReportingFrequency = 244,
    PacketDelayThresholds = 245,
    MinimumWaitTime = 246,
    QosMonitoringReport = 247,
    QosMonitoringMeasurement = 248,
    MtedtControlInformation = 249,
    DlDataPacketsSize = 250,
    QerControlIndications = 251,
    PacketRateStatusReport = 252,
    NfInstanceId = 253,
    EthernetContextInformation = 254,
    RedundantTransmissionParameters = 255,
    UpdatedPdr = 256,
    Snssai = 257,
    IpVersion = 258,
    PfcpasReqFlags = 259,
    DataStatus = 260,
    ProvideRdsConfigurationInformation = 261,
    RdsConfigurationInformation = 262,
    QueryPacketRateStatusWithinSessionModificationRequest = 263,
    PacketRateStatusReportWithinSessionModificationResponse = 264,
    MptcpApplicableIndication = 265,
    BridgeManagementInformationContainer = 266,
    UeIpAddressUsageInformation = 267,
    NumberOfUeIpAddresses = 268,
    ValidityTimer = 269,
    RedundantTransmissionForwardingParameters = 270,
    TransportDelayReporting = 271,
    PartialFailureInformation = 272,
    OffendingIeInformation = 274,
    RatType = 275,
    L2tpTunnelInformation = 276,
    L2tpSessionInformation = 277,
    L2tpUserAuthentication = 278,
    CreatedL2tpSession = 279,
    LnsAddress = 280,
    TunnelPreference = 281,
    CallingNumber = 282,
    CalledNumber = 283,
    L2tpSessionIndications = 284,
    DnsServerAddress = 285,
    NbnsServerAddress = 286,
    MaximumReceiveUnit = 287,
    Thresholds = 288,
    SteeringModeIndicator = 289,
    PfcpSessionChangeInfo = 290,
    GroupId = 291,
    CpIpAddress = 292,
    IpAddressAndPortNumberReplacement = 293,
    DnsQueryResponseFilter = 294,
    DirectReportingInformation = 295,
    EventNotificationUri = 296,
    NotificationCorrelationId = 297,
    ReportingFlags = 298,
    PredefinedRulesName = 299,
    MbsSessionN4mbControlInformation = 300,
    MbsMulticastParameters = 301,
    AddMbsUnicastParameters = 302,
    MbsSessionN4mbInformation = 303,
    RemoveMbsUnicastParameters = 304,
    MbsSessionIdentifier = 305,
    MulticastTransportInformation = 306,
    Mbsn4mbReqFlags = 307,
    LocalIngressTunnel = 308,
    MbsUnicastParametersId = 309,
    MbsSessionN4ControlInformation = 310,
    MbsSessionN4Information = 311,
    Mbsn4RespFlags = 312,
    TunnelPassword = 313,
    AreaSessionId = 314,
    PeerUpRestartReport = 315,
    DscpToPpiControlInformation = 316,
    DscpToPpiMappingInformation = 317,
    PfcpsdrspFlags = 318,
    QerIndications = 319,
    VendorSpecificNodeReportType = 320,
    ConfiguredTimeDomain = 321,
    Metadata = 322,
    TrafficParameterMeasurementControlInformation = 323,
    TrafficParameterMeasurementReport = 324,
    TrafficParameterThreshold = 325,
    DlPeriodicity = 326,
    N6JitterMeasurement = 327,
    TrafficParameterMeasurementIndication = 328,
    UlPeriodicity = 329,
    MpquicControlInformation = 330,
    MpquicParameters = 331,
    MpquicAddressInformation = 332,
    TransportMode = 333,
    ProtocolDescription = 334,
    ReportingSuggestionInfo = 335,
    TlContainer = 336,
    MeasurementIndication = 337,
    HplmnSNssai = 338,
    MediaTransportProtocol = 339,
    RtpHeaderExtensionInformation = 340,
    RtpPayloadInformation = 341,
    RtpHeaderExtensionType = 342,
    RtpHeaderExtensionId = 343,
    RtpPayloadType = 344,
    RtpPayloadFormat = 345,
    ExtendedDlBufferingNotificationPolicy = 346,
    MtSdtControlInformation = 347,
    ReportingThresholds = 348,
    RtpHeaderExtensionAdditionalInformation = 349,
    MappedN6IpAddress = 350,
    N6RoutingInformation = 351,
    Uri = 352,
    UeLevelMeasurementsConfiguration = 353,
    ReportingControlInformation = 389,
    Unknown = 0,
}

impl From<u16> for IeType {
    fn from(v: u16) -> Self {
        match v {
            1 => IeType::CreatePdr,
            2 => IeType::Pdi,
            3 => IeType::CreateFar,
            4 => IeType::ForwardingParameters,
            5 => IeType::DuplicatingParameters,
            6 => IeType::CreateUrr,
            7 => IeType::CreateQer,
            8 => IeType::CreatedPdr,
            9 => IeType::UpdatePdr,
            10 => IeType::UpdateFar,
            11 => IeType::UpdateForwardingParameters,
            12 => IeType::UpdateBarWithinSessionReportResponse,
            13 => IeType::UpdateUrr,
            14 => IeType::UpdateQer,
            15 => IeType::RemovePdr,
            16 => IeType::RemoveFar,
            17 => IeType::RemoveUrr,
            18 => IeType::RemoveQer,
            19 => IeType::Cause,
            20 => IeType::SourceInterface,
            21 => IeType::Fteid,
            22 => IeType::NetworkInstance,
            23 => IeType::SdfFilter,
            24 => IeType::ApplicationId,
            25 => IeType::GateStatus,
            26 => IeType::Mbr,
            27 => IeType::Gbr,
            28 => IeType::QerCorrelationId,
            29 => IeType::Precedence,
            30 => IeType::TransportLevelMarking,
            31 => IeType::VolumeThreshold,
            32 => IeType::TimeThreshold,
            33 => IeType::MonitoringTime,
            34 => IeType::SubsequentVolumeThreshold,
            35 => IeType::SubsequentTimeThreshold,
            36 => IeType::InactivityDetectionTime,
            37 => IeType::ReportingTriggers,
            38 => IeType::RedirectInformation,
            39 => IeType::ReportType,
            40 => IeType::OffendingIe,
            41 => IeType::ForwardingPolicy,
            42 => IeType::DestinationInterface,
            43 => IeType::UpFunctionFeatures,
            44 => IeType::ApplyAction,
            45 => IeType::DownlinkDataServiceInformation,
            46 => IeType::DownlinkDataNotificationDelay,
            47 => IeType::DlBufferingDuration,
            48 => IeType::DlBufferingSuggestedPacketCount,
            49 => IeType::PfcpsmReqFlags,
            50 => IeType::PfcpsrrspFlags,
            51 => IeType::LoadControlInformation,
            52 => IeType::SequenceNumber,
            53 => IeType::Metric,
            54 => IeType::OverloadControlInformation,
            55 => IeType::Timer,
            56 => IeType::PdrId,
            57 => IeType::Fseid,
            58 => IeType::ApplicationIdsPfds,
            59 => IeType::PfdContext,
            60 => IeType::NodeId,
            61 => IeType::PfdContents,
            62 => IeType::MeasurementMethod,
            63 => IeType::UsageReportTrigger,
            64 => IeType::MeasurementPeriod,
            65 => IeType::FqCsid,
            66 => IeType::VolumeMeasurement,
            67 => IeType::DurationMeasurement,
            68 => IeType::ApplicationDetectionInformation,
            69 => IeType::TimeOfFirstPacket,
            70 => IeType::TimeOfLastPacket,
            71 => IeType::QuotaHoldingTime,
            72 => IeType::DroppedDlTrafficThreshold,
            73 => IeType::VolumeQuota,
            74 => IeType::TimeQuota,
            75 => IeType::StartTime,
            76 => IeType::EndTime,
            77 => IeType::QueryUrr,
            78 => IeType::UsageReportWithinSessionModificationResponse,
            79 => IeType::UsageReportWithinSessionDeletionResponse,
            80 => IeType::UsageReportWithinSessionReportRequest,
            81 => IeType::UrrId,
            82 => IeType::LinkedUrrId,
            83 => IeType::DownlinkDataReport,
            84 => IeType::OuterHeaderCreation,
            93 => IeType::UeIpAddress,
            95 => IeType::OuterHeaderRemoval,
            96 => IeType::RecoveryTimeStamp,
            106 => IeType::ActivatePredefinedRules,
            107 => IeType::DeactivatePredefinedRules,
            85 => IeType::CreateBar,
            86 => IeType::UpdateBar,
            87 => IeType::RemoveBar,
            88 => IeType::BarId,
            89 => IeType::CpFunctionFeatures,
            90 => IeType::UsageInformation,
            91 => IeType::ApplicationInstanceId,
            92 => IeType::FlowInformation,
            94 => IeType::PacketRate,
            97 => IeType::DlFlowLevelMarking,
            98 => IeType::HeaderEnrichment,
            99 => IeType::ErrorIndicationReport,
            100 => IeType::MeasurementInformation,
            101 => IeType::NodeReportType,
            102 => IeType::UserPlanePathFailureReport,
            103 => IeType::RemoteGtpuPeer,
            104 => IeType::UrSeqn,
            105 => IeType::UpdateDuplicatingParameters,
            108 => IeType::FarId,
            109 => IeType::QerId,
            110 => IeType::OciFlags,
            111 => IeType::PfcpAssociationReleaseRequest,
            112 => IeType::GracefulReleasePeriod,
            113 => IeType::PdnType,
            114 => IeType::FailedRuleId,
            115 => IeType::TimeQuotaMechanism,
            116 => IeType::UserPlaneIpResourceInformation,
            117 => IeType::UserPlaneInactivityTimer,
            118 => IeType::AggregatedUrrs,
            119 => IeType::Multiplier,
            120 => IeType::AggregatedUrrId,
            121 => IeType::SubsequentVolumeQuota,
            122 => IeType::SubsequentTimeQuota,
            123 => IeType::Rqi,
            124 => IeType::Qfi,
            125 => IeType::QueryUrrReference,
            126 => IeType::AdditionalUsageReportsInformation,
            127 => IeType::CreateTrafficEndpoint,
            128 => IeType::CreatedTrafficEndpoint,
            129 => IeType::UpdateTrafficEndpoint,
            130 => IeType::RemoveTrafficEndpoint,
            131 => IeType::TrafficEndpointId,
            132 => IeType::EthernetPacketFilter,
            133 => IeType::MacAddress,
            134 => IeType::CTag,
            135 => IeType::STag,
            136 => IeType::Ethertype,
            137 => IeType::Proxying,
            138 => IeType::EthernetFilterId,
            139 => IeType::EthernetFilterProperties,
            140 => IeType::SuggestedBufferingPacketsCount,
            141 => IeType::UserId,
            142 => IeType::EthernetPduSessionInformation,
            143 => IeType::EthernetTrafficInformation,
            144 => IeType::MacAddressesDetected,
            145 => IeType::MacAddressesRemoved,
            146 => IeType::EthernetInactivityTimer,
            147 => IeType::AdditionalMonitoringTime,
            148 => IeType::EventQuota,
            149 => IeType::EventThreshold,
            150 => IeType::SubsequentEventQuota,
            151 => IeType::SubsequentEventThreshold,
            152 => IeType::TraceInformation,
            153 => IeType::FramedRoute,
            154 => IeType::FramedRouting,
            155 => IeType::FramedIpv6Route,
            156 => IeType::EventTimeStamp,
            157 => IeType::AveragingWindow,
            158 => IeType::PagingPolicyIndicator,
            159 => IeType::ApnDnn,
            160 => IeType::TgppInterfaceType,
            161 => IeType::PfcpsrReqFlags,
            162 => IeType::PfcpauReqFlags,
            163 => IeType::ActivationTime,
            164 => IeType::DeactivationTime,
            165 => IeType::CreateMar,
            166 => IeType::TgppAccessForwardingActionInformation,
            167 => IeType::NonTgppAccessForwardingActionInformation,
            168 => IeType::RemoveMar,
            169 => IeType::UpdateMar,
            170 => IeType::MarId,
            171 => IeType::SteeringFunctionality,
            172 => IeType::SteeringMode,
            173 => IeType::Weight,
            174 => IeType::Priority,
            175 => IeType::UpdateTgppAccessForwardingActionInformation,
            176 => IeType::UpdateNonTgppAccessForwardingActionInformation,
            177 => IeType::UeIpAddressPoolIdentity,
            178 => IeType::AlternativeSmfIpAddress,
            179 => IeType::PacketReplicationAndDetectionCarryOnInformation,
            180 => IeType::SmfSetId,
            181 => IeType::QuotaValidityTime,
            182 => IeType::NumberOfReports,
            183 => IeType::PfcpSessionRetentionInformation,
            184 => IeType::PfcpasRspFlags,
            185 => IeType::CpPfcpEntityIpAddress,
            186 => IeType::PfcpseReqFlags,
            187 => IeType::UserPlanePathRecoveryReport,
            188 => IeType::IpMulticastAddressingInfo,
            189 => IeType::JoinIpMulticastInformationWithinUsageReport,
            190 => IeType::LeaveIpMulticastInformationWithinUsageReport,
            191 => IeType::IpMulticastAddress,
            192 => IeType::SourceIpAddress,
            193 => IeType::PacketRateStatus,
            194 => IeType::CreateBridgeInfoForTsc,
            195 => IeType::CreatedBridgeInfoForTsc,
            196 => IeType::DsttPortNumber,
            197 => IeType::NwttPortNumber,
            198 => IeType::TsnBridgeId,
            199 => IeType::TscManagementInformationWithinSessionModificationRequest,
            200 => IeType::TscManagementInformationWithinSessionModificationResponse,
            201 => IeType::TscManagementInformationWithinSessionReportRequest,
            202 => IeType::PortManagementInformationContainer,
            203 => IeType::ClockDriftControlInformation,
            204 => IeType::RequestedClockDriftInformation,
            205 => IeType::ClockDriftReport,
            206 => IeType::TsnTimeDomainNumber,
            207 => IeType::TimeOffsetThreshold,
            208 => IeType::CumulativeRateRatioThreshold,
            209 => IeType::TimeOffsetMeasurement,
            210 => IeType::CumulativeRateRatioMeasurement,
            211 => IeType::RemoveSrr,
            212 => IeType::CreateSrr,
            213 => IeType::UpdateSrr,
            214 => IeType::SessionReport,
            215 => IeType::SrrId,
            216 => IeType::AccessAvailabilityControlInformation,
            217 => IeType::RequestedAccessAvailabilityInformation,
            218 => IeType::AccessAvailabilityReport,
            219 => IeType::AccessAvailabilityInformation,
            220 => IeType::ProvideAtsssControlInformation,
            221 => IeType::AtsssControlParameters,
            222 => IeType::MptcpControlInformation,
            223 => IeType::AtsssLlControlInformation,
            224 => IeType::PmfControlInformation,
            225 => IeType::MptcpParameters,
            226 => IeType::AtsssLlParameters,
            227 => IeType::PmfParameters,
            228 => IeType::MptcpAddressInformation,
            229 => IeType::UeLinkSpecificIpAddress,
            230 => IeType::PmfAddressInformation,
            231 => IeType::AtsssLlInformation,
            232 => IeType::DataNetworkAccessIdentifier,
            233 => IeType::UeIpAddressPoolInformation,
            234 => IeType::AveragePacketDelay,
            235 => IeType::MinimumPacketDelay,
            236 => IeType::MaximumPacketDelay,
            237 => IeType::QosReportTrigger,
            238 => IeType::GtpuPathQosControlInformation,
            239 => IeType::GtpuPathQosReport,
            240 => IeType::QosInformationInGtpuPathQosReport,
            241 => IeType::GtpuPathInterfaceType,
            242 => IeType::QosMonitoringPerQosFlowControlInformation,
            243 => IeType::RequestedQosMonitoring,
            244 => IeType::ReportingFrequency,
            245 => IeType::PacketDelayThresholds,
            246 => IeType::MinimumWaitTime,
            247 => IeType::QosMonitoringReport,
            248 => IeType::QosMonitoringMeasurement,
            249 => IeType::MtedtControlInformation,
            250 => IeType::DlDataPacketsSize,
            251 => IeType::QerControlIndications,
            252 => IeType::PacketRateStatusReport,
            253 => IeType::NfInstanceId,
            254 => IeType::EthernetContextInformation,
            255 => IeType::RedundantTransmissionParameters,
            256 => IeType::UpdatedPdr,
            257 => IeType::Snssai,
            258 => IeType::IpVersion,
            259 => IeType::PfcpasReqFlags,
            260 => IeType::DataStatus,
            261 => IeType::ProvideRdsConfigurationInformation,
            262 => IeType::RdsConfigurationInformation,
            263 => IeType::QueryPacketRateStatusWithinSessionModificationRequest,
            264 => IeType::PacketRateStatusReportWithinSessionModificationResponse,
            265 => IeType::MptcpApplicableIndication,
            266 => IeType::BridgeManagementInformationContainer,
            267 => IeType::UeIpAddressUsageInformation,
            268 => IeType::NumberOfUeIpAddresses,
            269 => IeType::ValidityTimer,
            270 => IeType::RedundantTransmissionForwardingParameters,
            271 => IeType::TransportDelayReporting,
            272 => IeType::PartialFailureInformation,
            274 => IeType::OffendingIeInformation,
            275 => IeType::RatType,
            276 => IeType::L2tpTunnelInformation,
            277 => IeType::L2tpSessionInformation,
            278 => IeType::L2tpUserAuthentication,
            279 => IeType::CreatedL2tpSession,
            280 => IeType::LnsAddress,
            281 => IeType::TunnelPreference,
            282 => IeType::CallingNumber,
            283 => IeType::CalledNumber,
            284 => IeType::L2tpSessionIndications,
            285 => IeType::DnsServerAddress,
            286 => IeType::NbnsServerAddress,
            287 => IeType::MaximumReceiveUnit,
            288 => IeType::Thresholds,
            289 => IeType::SteeringModeIndicator,
            290 => IeType::PfcpSessionChangeInfo,
            291 => IeType::GroupId,
            292 => IeType::CpIpAddress,
            293 => IeType::IpAddressAndPortNumberReplacement,
            294 => IeType::DnsQueryResponseFilter,
            295 => IeType::DirectReportingInformation,
            296 => IeType::EventNotificationUri,
            297 => IeType::NotificationCorrelationId,
            298 => IeType::ReportingFlags,
            299 => IeType::PredefinedRulesName,
            300 => IeType::MbsSessionN4mbControlInformation,
            301 => IeType::MbsMulticastParameters,
            302 => IeType::AddMbsUnicastParameters,
            303 => IeType::MbsSessionN4mbInformation,
            304 => IeType::RemoveMbsUnicastParameters,
            305 => IeType::MbsSessionIdentifier,
            306 => IeType::MulticastTransportInformation,
            307 => IeType::Mbsn4mbReqFlags,
            308 => IeType::LocalIngressTunnel,
            309 => IeType::MbsUnicastParametersId,
            310 => IeType::MbsSessionN4ControlInformation,
            311 => IeType::MbsSessionN4Information,
            312 => IeType::Mbsn4RespFlags,
            313 => IeType::TunnelPassword,
            314 => IeType::AreaSessionId,
            315 => IeType::PeerUpRestartReport,
            316 => IeType::DscpToPpiControlInformation,
            317 => IeType::DscpToPpiMappingInformation,
            318 => IeType::PfcpsdrspFlags,
            319 => IeType::QerIndications,
            320 => IeType::VendorSpecificNodeReportType,
            321 => IeType::ConfiguredTimeDomain,
            322 => IeType::Metadata,
            323 => IeType::TrafficParameterMeasurementControlInformation,
            324 => IeType::TrafficParameterMeasurementReport,
            325 => IeType::TrafficParameterThreshold,
            326 => IeType::DlPeriodicity,
            327 => IeType::N6JitterMeasurement,
            328 => IeType::TrafficParameterMeasurementIndication,
            329 => IeType::UlPeriodicity,
            330 => IeType::MpquicControlInformation,
            331 => IeType::MpquicParameters,
            332 => IeType::MpquicAddressInformation,
            333 => IeType::TransportMode,
            334 => IeType::ProtocolDescription,
            335 => IeType::ReportingSuggestionInfo,
            336 => IeType::TlContainer,
            337 => IeType::MeasurementIndication,
            338 => IeType::HplmnSNssai,
            339 => IeType::MediaTransportProtocol,
            340 => IeType::RtpHeaderExtensionInformation,
            341 => IeType::RtpPayloadInformation,
            342 => IeType::RtpHeaderExtensionType,
            343 => IeType::RtpHeaderExtensionId,
            344 => IeType::RtpPayloadType,
            345 => IeType::RtpPayloadFormat,
            346 => IeType::ExtendedDlBufferingNotificationPolicy,
            347 => IeType::MtSdtControlInformation,
            348 => IeType::ReportingThresholds,
            349 => IeType::RtpHeaderExtensionAdditionalInformation,
            350 => IeType::MappedN6IpAddress,
            351 => IeType::N6RoutingInformation,
            352 => IeType::Uri,
            353 => IeType::UeLevelMeasurementsConfiguration,
            389 => IeType::ReportingControlInformation,
            _ => IeType::Unknown,
        }
    }
}

/// Trait for types that can be parsed from an [`Ie`] payload.
///
/// Implement this trait to enable [`Ie::parse`] for your IE type.
/// All standard IE types in this crate implement this trait automatically.
///
/// # Examples
///
/// ```
/// use rs_pfcp::ie::{Ie, IeType, ParseIe};
/// use rs_pfcp::ie::cause::Cause;
///
/// let ie = Ie::new(IeType::Cause, vec![1]);
/// let cause = ie.parse::<Cause>().unwrap();
/// ```
pub trait ParseIe: Sized {
    /// Parse this type from the raw IE payload bytes.
    fn parse_from_payload(data: &[u8]) -> Result<Self, PfcpError>;
}

/// Helper trait to convert marshal results into `Vec<u8>`.
///
/// This trait provides a unified interface for handling both `Vec<u8>` and
/// fixed-size arrays `[u8; N]` returned from IE `marshal()` methods.
pub trait IntoIePayload {
    fn into_payload(self) -> Vec<u8>;
}

impl IntoIePayload for Vec<u8> {
    fn into_payload(self) -> Vec<u8> {
        self
    }
}

impl<const N: usize> IntoIePayload for [u8; N] {
    fn into_payload(self) -> Vec<u8> {
        self.to_vec()
    }
}

/// Represents a PFCP Information Element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ie {
    pub ie_type: IeType,
    pub enterprise_id: Option<u16>,
    pub payload: Vec<u8>,
    child_ies: Vec<Ie>,
}

impl Ie {
    /// Creates a new IE.
    pub fn new(ie_type: IeType, payload: Vec<u8>) -> Self {
        Ie {
            ie_type,
            enterprise_id: None,
            payload,
            child_ies: Vec::new(),
        }
    }

    /// Creates a new vendor-specific IE.
    pub fn new_vendor_specific(ie_type: IeType, enterprise_id: u16, payload: Vec<u8>) -> Self {
        Ie {
            ie_type,
            enterprise_id: Some(enterprise_id),
            payload,
            child_ies: Vec::new(),
        }
    }

    /// Creates a new grouped IE.
    pub fn new_grouped(ie_type: IeType, ies: Vec<Ie>) -> Self {
        let mut payload = Vec::new();
        for ie in &ies {
            payload.extend_from_slice(&ie.marshal());
        }
        Ie {
            ie_type,
            enterprise_id: None,
            payload,
            child_ies: ies,
        }
    }

    /// Creates a new IE from a marshal result.
    ///
    /// This method accepts both `Vec<u8>` and `[u8; N]` return types from
    /// IE `marshal()` methods, eliminating the need to manually call `.to_vec()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_pfcp::ie::{Ie, IeType, cause::{Cause, CauseValue}};
    ///
    /// // Works with both Vec<u8> and [u8; N] returns
    /// let cause = Cause::new(CauseValue::RequestAccepted);
    /// let ie = Ie::from_marshal(IeType::Cause, cause.marshal());
    /// ```
    pub fn from_marshal<T: IntoIePayload>(ie_type: IeType, payload: T) -> Self {
        Ie::new(ie_type, payload.into_payload())
    }

    /// Returns the length of the IE in bytes.
    pub fn len(&self) -> u16 {
        let mut length = 4; // Type (2) + Length (2)
        if self.is_vendor_specific() {
            length += 2;
        }
        length += self.payload.len() as u16;
        length
    }

    /// Reports whether an IE is empty.
    pub fn is_empty(&self) -> bool {
        self.payload.is_empty()
    }

    /// Reports whether an IE is vendor-specific.
    pub fn is_vendor_specific(&self) -> bool {
        self.enterprise_id.is_some() || (self.ie_type as u16) & 0x8000 != 0
    }

    /// Serializes the IE into a byte vector.
    pub fn marshal(&self) -> Vec<u8> {
        let mut data = Vec::new();
        self.marshal_into(&mut data);
        data
    }

    /// Serializes the IE into an existing buffer.
    ///
    /// This method appends the marshaled IE to the provided buffer,
    /// allowing for buffer reuse and avoiding allocations.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_pfcp::ie::{Ie, IeType};
    ///
    /// let ie = Ie::new(IeType::Cause, vec![1]);
    ///
    /// // Reuse buffer for multiple IEs
    /// let mut buf = Vec::new();
    /// ie.marshal_into(&mut buf);
    /// // Process buf...
    /// buf.clear();
    /// ie.marshal_into(&mut buf);
    /// ```
    pub fn marshal_into(&self, buf: &mut Vec<u8>) {
        buf.extend_from_slice(&(self.ie_type as u16).to_be_bytes());

        let length = if self.is_vendor_specific() {
            self.payload.len() as u16 + 2
        } else {
            self.payload.len() as u16
        };
        buf.extend_from_slice(&length.to_be_bytes());

        if let Some(eid) = self.enterprise_id {
            buf.extend_from_slice(&eid.to_be_bytes());
        }

        buf.extend_from_slice(&self.payload);
    }

    /// Returns true if the IE type legitimately supports zero-length encoding.
    ///
    /// Per 3GPP TS 29.244 Release 18, certain IEs support zero-length to indicate
    /// "clear/reset" semantics in update operations (different from omitting the IE).
    ///
    /// # Zero-Length Semantics in Update Operations
    /// - **IE Omitted**: "No change" - keep existing value
    /// - **IE Present with Value**: "Update" - change to new value
    /// - **IE Present with Zero-Length**: "Clear/Reset" - remove value
    ///
    /// # IE Encoding Pattern Analysis
    ///
    /// Only **pure OCTET STRING IEs** (no internal structure) can be zero-length:
    ///
    /// ## ✅ Allowlisted (Zero-Length Valid)
    /// These IEs are pure OCTET STRING with no internal structure:
    /// - **Network Instance (Type 22)**: Clear network routing context in Update FAR
    /// - **APN/DNN (Type 159)**: Default APN (empty network name)
    /// - **Forwarding Policy (Type 41)**: Clear policy identifier
    ///
    /// ## ❌ Not Allowlisted (Cannot Be Zero-Length)
    /// All other IEs have structure that prevents zero-length at protocol level:
    ///
    /// **Structured OCTET STRING** (have type/flag bytes):
    /// - User ID (Type 141): Requires 1 byte type field (IMSI/IMEI/NAI/etc.)
    /// - Redirect Information: Requires 1 byte address type + address
    /// - Header Enrichment: Requires type + name + value structure
    ///
    /// **Flow Descriptions** (cannot be empty per specification):
    /// - SDF Filter (Type 23): Requires flow description
    /// - Application ID (Type 24): Requires application identifier
    ///
    /// **Fixed-Length/Flags** (always > 0):
    /// - All integer IDs (PDR ID, FAR ID, QER ID, URR ID)
    /// - Timestamps and counters
    /// - Bitflag IEs (Apply Action, Measurement Method, etc.)
    ///
    /// # Important Distinction
    /// Some IEs like User ID can have **empty value fields** (e.g., NAI type with no name),
    /// but still require their **structure bytes** (type field), so they cannot be
    /// zero-length at the IE protocol level.
    fn allows_zero_length(ie_type: IeType) -> bool {
        matches!(
            ie_type,
            IeType::NetworkInstance     // TS 29.244 R18 Section 8.2.4: Zero-length valid
            | IeType::ApnDnn            // TS 29.244 R18 Section 8.2.103: Empty = default APN
            | IeType::ForwardingPolicy // Variable-length string, empty = clear
        )
    }

    /// Deserializes a byte slice into an IE.
    pub fn unmarshal(b: &[u8]) -> Result<Self, PfcpError> {
        if b.len() < 4 {
            return Err(PfcpError::invalid_length("IE", IeType::Unknown, 4, b.len()));
        }

        // Read raw type value to preserve vendor bit (0x8000)
        let raw_type = u16::from_be_bytes([b[0], b[1]]);
        let ie_type = IeType::from(raw_type);
        let length = u16::from_be_bytes([b[2], b[3]]);

        // Security: Reject zero-length IEs except for explicitly allowlisted types.
        // Per 3GPP TS 29.244 Release 18, certain IEs legitimately support zero-length
        // to indicate "clear/reset" semantics in update operations.
        // All other zero-length IEs are rejected to prevent DoS attacks.
        if length == 0 && !Self::allows_zero_length(ie_type) {
            return Err(PfcpError::invalid_value(
                "IE",
                format!("{:?} (type {})", ie_type, raw_type),
                "Zero-length IE not allowed",
            ));
        }

        let mut offset = 4;
        // Check vendor bit in RAW type value, not converted IeType
        let enterprise_id = if raw_type & 0x8000 != 0 {
            if b.len() < 6 {
                return Err(PfcpError::invalid_length(
                    "Vendor-specific IE",
                    ie_type,
                    6,
                    b.len(),
                ));
            }
            offset += 2;
            Some(u16::from_be_bytes([b[4], b[5]]))
        } else {
            None
        };

        // For vendor-specific IEs, length includes enterprise ID (2 bytes)
        // So actual payload length = length - 2
        let payload_length = if enterprise_id.is_some() && length >= 2 {
            length - 2
        } else if enterprise_id.is_some() {
            0 // Edge case: vendor IE with length < 2
        } else {
            length
        };

        let end = offset + payload_length as usize;
        if b.len() < end {
            return Err(PfcpError::invalid_length(
                "IE payload",
                ie_type,
                end,
                b.len(),
            ));
        }
        let payload = b[offset..end].to_vec();

        Ok(Ie {
            ie_type,
            enterprise_id,
            payload,
            child_ies: Vec::new(), // Parsing child IEs will be handled separately
        })
    }

    // --- Value Accessors ---

    pub fn as_u8(&self) -> Result<u8, PfcpError> {
        if self.payload.is_empty() {
            return Err(PfcpError::invalid_length("IE payload", self.ie_type, 1, 0));
        }
        Ok(self.payload[0])
    }

    pub fn as_u16(&self) -> Result<u16, PfcpError> {
        if self.payload.len() < 2 {
            return Err(PfcpError::invalid_length(
                "IE payload",
                self.ie_type,
                2,
                self.payload.len(),
            ));
        }
        Ok(u16::from_be_bytes([self.payload[0], self.payload[1]]))
    }

    pub fn as_u32(&self) -> Result<u32, PfcpError> {
        if self.payload.len() < 4 {
            return Err(PfcpError::invalid_length(
                "IE payload",
                self.ie_type,
                4,
                self.payload.len(),
            ));
        }
        Ok(u32::from_be_bytes([
            self.payload[0],
            self.payload[1],
            self.payload[2],
            self.payload[3],
        ]))
    }

    pub fn as_u64(&self) -> Result<u64, PfcpError> {
        if self.payload.len() < 8 {
            return Err(PfcpError::invalid_length(
                "IE payload",
                self.ie_type,
                8,
                self.payload.len(),
            ));
        }
        Ok(u64::from_be_bytes([
            self.payload[0],
            self.payload[1],
            self.payload[2],
            self.payload[3],
            self.payload[4],
            self.payload[5],
            self.payload[6],
            self.payload[7],
        ]))
    }

    pub fn as_string(&self) -> Result<String, PfcpError> {
        std::str::from_utf8(&self.payload)
            .map(|s| s.to_string())
            .map_err(|e| {
                PfcpError::invalid_value(
                    "IE payload",
                    format!("{:?}", self.ie_type),
                    format!("Invalid UTF-8: {}", e),
                )
            })
    }

    pub fn as_ies(&mut self) -> Result<&[Ie], PfcpError> {
        if !self.child_ies.is_empty() {
            return Ok(&self.child_ies);
        }

        let mut offset = 0;
        while offset < self.payload.len() {
            let ie = Ie::unmarshal(&self.payload[offset..])?;
            let ie_len = ie.len() as usize;
            self.child_ies.push(ie);
            offset += ie_len;
        }
        Ok(&self.child_ies)
    }

    /// Parse the IE payload into a strongly-typed representation.
    ///
    /// This is a convenience method to convert a raw [`Ie`] into a typed IE value
    /// without manually referencing `.payload`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_pfcp::ie::{Ie, IeType};
    /// use rs_pfcp::ie::cause::{Cause, CauseValue};
    ///
    /// let ie = Ie::new(IeType::Cause, vec![1]);
    /// let cause = ie.parse::<Cause>().unwrap();
    /// assert_eq!(cause.value, CauseValue::RequestAccepted);
    /// ```
    ///
    /// ```
    /// use rs_pfcp::ie::{Ie, IeType};
    /// use rs_pfcp::ie::create_pdr::CreatePdr;
    ///
    /// // Grouped IE - parse directly from the raw Ie
    /// fn handle(ie: &Ie) -> rs_pfcp::error::PfcpError {
    ///     ie.parse::<CreatePdr>().unwrap_err()
    /// }
    /// ```
    pub fn parse<T: ParseIe>(&self) -> Result<T, PfcpError> {
        T::parse_from_payload(&self.payload)
    }
}

/// Efficiently marshals a slice of IEs into a byte vector.
///
/// Pre-allocates capacity based on IE lengths to avoid reallocations.
/// This is the standard pattern for marshaling grouped IEs.
///
/// # Examples
///
/// ```
/// use rs_pfcp::ie::{marshal_ies, Ie, IeType};
///
/// let ies = vec![
///     Ie::new(IeType::PdrId, vec![0x00, 0x01]),
///     Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
/// ];
///
/// let marshaled = marshal_ies(&ies);
/// let expected_len: usize = ies.iter().map(|ie| ie.len() as usize).sum();
/// assert_eq!(marshaled.len(), expected_len);
/// ```
///
/// # Performance
///
/// This function pre-calculates the required capacity and allocates once,
/// avoiding multiple reallocations during marshaling. It's equivalent to
/// the pattern used in Phase 1 capacity optimization but extracted for reuse.
pub fn marshal_ies(ies: &[Ie]) -> Vec<u8> {
    let capacity: usize = ies.iter().map(|ie| ie.len() as usize).sum();
    let mut data = Vec::with_capacity(capacity);
    for ie in ies {
        data.extend_from_slice(&ie.marshal());
    }
    data
}

/// Iterator over Information Elements in a payload.
///
/// Automatically tracks byte offset and unmarshals IEs sequentially.
/// This is the standard pattern for parsing grouped IE payloads.
///
/// # Examples
///
/// ```
/// use rs_pfcp::ie::{IeIterator, IeType, pdr_id::PdrId, far_id::FarId};
/// use rs_pfcp::error::PfcpError;
///
/// # fn example(payload: &[u8]) -> Result<(), PfcpError> {
/// let mut pdr_id = None;
/// let mut far_id = None;
///
/// for ie_result in IeIterator::new(payload) {
///     let ie = ie_result?;
///     match ie.ie_type {
///         IeType::PdrId => pdr_id = Some(PdrId::unmarshal(&ie.payload)?),
///         IeType::FarId => far_id = Some(FarId::unmarshal(&ie.payload)?),
///         _ => (), // Ignore unknown IEs
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - IE header is malformed
/// - Payload is truncated (IE extends past end)
///
/// # Implementation Notes
///
/// This iterator automatically stops on the first error and won't continue
/// iteration after an error is encountered. This matches the standard error
/// handling pattern for PFCP parsing.
pub struct IeIterator<'a> {
    payload: &'a [u8],
    offset: usize,
}

impl<'a> IeIterator<'a> {
    /// Creates a new IE iterator over the given payload.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_pfcp::ie::IeIterator;
    ///
    /// let payload = vec![/* IE bytes */];
    /// let iter = IeIterator::new(&payload);
    /// ```
    pub fn new(payload: &'a [u8]) -> Self {
        IeIterator { payload, offset: 0 }
    }
}

impl<'a> Iterator for IeIterator<'a> {
    type Item = Result<Ie, PfcpError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.offset >= self.payload.len() {
            return None;
        }

        match Ie::unmarshal(&self.payload[self.offset..]) {
            Ok(ie) => {
                let ie_len = ie.len() as usize;
                self.offset += ie_len;
                Some(Ok(ie))
            }
            Err(e) => {
                // Move to end to stop iteration
                self.offset = self.payload.len();
                Some(Err(e))
            }
        }
    }
}

/// Ergonomic builder support for converting common Rust types to IEs.
///
/// This module provides the `IntoIe` trait and implementations for common types
/// to enable ergonomic builder APIs that accept standard Rust types directly.
///
/// # Examples
///
/// ```
/// use rs_pfcp::ie::{Ie, IntoIe};
/// use std::time::SystemTime;
///
/// // Convert SystemTime directly to RecoveryTimeStamp IE
/// let ie: Ie = SystemTime::now().into_ie();
/// ```
pub mod builder_support {
    use super::*;
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
    use std::time::SystemTime;

    /// Trait for types that can be automatically converted to Information Elements.
    ///
    /// This trait enables ergonomic builder APIs by allowing standard Rust types
    /// to be passed directly to builder methods, which then convert them to the
    /// appropriate IE representation.
    ///
    /// # Examples
    ///
    /// ```
    /// use rs_pfcp::ie::builder_support::IntoIe;
    /// use std::time::SystemTime;
    ///
    /// let timestamp = SystemTime::now();
    /// let ie = timestamp.into_ie();
    /// ```
    pub trait IntoIe {
        /// Converts this value into an Information Element.
        fn into_ie(self) -> Ie;
    }

    /// SystemTime → RecoveryTimeStamp IE
    impl IntoIe for SystemTime {
        fn into_ie(self) -> Ie {
            use crate::ie::recovery_time_stamp::RecoveryTimeStamp;
            let ts = RecoveryTimeStamp::new(self);
            Ie::new(IeType::RecoveryTimeStamp, ts.marshal().to_vec())
        }
    }

    /// Ipv4Addr → SourceIpAddress IE (IPv4 only)
    impl IntoIe for Ipv4Addr {
        fn into_ie(self) -> Ie {
            use crate::ie::source_ip_address::SourceIpAddress;
            let ip = SourceIpAddress::new(Some(self), None);
            ip.to_ie()
        }
    }

    /// Ipv6Addr → SourceIpAddress IE (IPv6 only)
    impl IntoIe for Ipv6Addr {
        fn into_ie(self) -> Ie {
            use crate::ie::source_ip_address::SourceIpAddress;
            let ip = SourceIpAddress::new(None, Some(self));
            ip.to_ie()
        }
    }

    /// IpAddr → SourceIpAddress IE (dispatches to IPv4 or IPv6)
    impl IntoIe for IpAddr {
        fn into_ie(self) -> Ie {
            match self {
                IpAddr::V4(addr) => addr.into_ie(),
                IpAddr::V6(addr) => addr.into_ie(),
            }
        }
    }

    /// &str → NodeId IE (FQDN)
    impl IntoIe for &str {
        fn into_ie(self) -> Ie {
            use crate::ie::node_id::NodeId;
            let node_id = NodeId::new_fqdn(self);
            node_id.to_ie()
        }
    }

    /// String → NodeId IE (FQDN)
    impl IntoIe for String {
        fn into_ie(self) -> Ie {
            self.as_str().into_ie()
        }
    }

    /// (u64, Ipv4Addr) → F-SEID IE (IPv4 only)
    ///
    /// Convenient tuple conversion for F-SEID construction.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::Ipv4Addr;
    ///
    /// let seid = 0x123456789ABCDEFu64;
    /// let ip = Ipv4Addr::new(10, 0, 0, 1);
    /// let ie = (seid, ip).into_ie();
    /// ```
    impl IntoIe for (u64, Ipv4Addr) {
        fn into_ie(self) -> Ie {
            use crate::ie::fseid::Fseid;
            let (seid, ip) = self;
            let fseid = Fseid::new(seid, Some(ip), None);
            Ie::new(IeType::Fseid, fseid.marshal())
        }
    }

    /// (u64, Ipv6Addr) → F-SEID IE (IPv6 only)
    ///
    /// Convenient tuple conversion for F-SEID construction.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::Ipv6Addr;
    ///
    /// let seid = 0x123456789ABCDEFu64;
    /// let ip = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
    /// let ie = (seid, ip).into_ie();
    /// ```
    impl IntoIe for (u64, Ipv6Addr) {
        fn into_ie(self) -> Ie {
            use crate::ie::fseid::Fseid;
            let (seid, ip) = self;
            let fseid = Fseid::new(seid, None, Some(ip));
            Ie::new(IeType::Fseid, fseid.marshal())
        }
    }

    /// (u64, IpAddr) → F-SEID IE (dispatches based on IP version)
    ///
    /// Convenient tuple conversion for F-SEID construction that handles both IPv4 and IPv6.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::{IpAddr, Ipv4Addr};
    ///
    /// let seid = 0x123456789ABCDEFu64;
    /// let ip: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
    /// let ie = (seid, ip).into_ie();
    /// ```
    impl IntoIe for (u64, IpAddr) {
        fn into_ie(self) -> Ie {
            let (seid, ip) = self;
            match ip {
                IpAddr::V4(v4) => (seid, v4).into_ie(),
                IpAddr::V6(v6) => (seid, v6).into_ie(),
            }
        }
    }

    /// (u32, Ipv4Addr) → F-TEID IE (IPv4 only)
    ///
    /// Convenient tuple conversion for F-TEID construction with TEID and IPv4 address.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::Ipv4Addr;
    ///
    /// let teid = 0x12345678u32;
    /// let ip = Ipv4Addr::new(192, 168, 1, 1);
    /// let ie = (teid, ip).into_ie();
    /// ```
    impl IntoIe for (u32, Ipv4Addr) {
        fn into_ie(self) -> Ie {
            use crate::ie::f_teid::Fteid;
            let (teid, ip) = self;
            let fteid = Fteid::new(true, false, teid, Some(ip), None, 0);
            Ie::new(IeType::Fteid, fteid.marshal())
        }
    }

    /// (u32, Ipv6Addr) → F-TEID IE (IPv6 only)
    ///
    /// Convenient tuple conversion for F-TEID construction with TEID and IPv6 address.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::Ipv6Addr;
    ///
    /// let teid = 0x12345678u32;
    /// let ip = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
    /// let ie = (teid, ip).into_ie();
    /// ```
    impl IntoIe for (u32, Ipv6Addr) {
        fn into_ie(self) -> Ie {
            use crate::ie::f_teid::Fteid;
            let (teid, ip) = self;
            let fteid = Fteid::new(false, true, teid, None, Some(ip), 0);
            Ie::new(IeType::Fteid, fteid.marshal())
        }
    }

    /// (u32, IpAddr) → F-TEID IE (dispatches based on IP version)
    ///
    /// Convenient tuple conversion for F-TEID construction that handles both IPv4 and IPv6.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::{IpAddr, Ipv4Addr};
    ///
    /// let teid = 0x12345678u32;
    /// let ip: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
    /// let ie = (teid, ip).into_ie();
    /// ```
    impl IntoIe for (u32, IpAddr) {
        fn into_ie(self) -> Ie {
            let (teid, ip) = self;
            match ip {
                IpAddr::V4(v4) => (teid, v4).into_ie(),
                IpAddr::V6(v6) => (teid, v6).into_ie(),
            }
        }
    }

    /// (Ipv4Addr, Ipv6Addr) → UE IP Address IE (dual-stack)
    ///
    /// Convenient tuple conversion for UE IP Address with both IPv4 and IPv6.
    ///
    /// # Example
    ///
    /// ```
    /// use rs_pfcp::ie::IntoIe;
    /// use std::net::{Ipv4Addr, Ipv6Addr};
    ///
    /// let ipv4 = Ipv4Addr::new(10, 0, 0, 1);
    /// let ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
    /// let ie = (ipv4, ipv6).into_ie();
    /// ```
    impl IntoIe for (Ipv4Addr, Ipv6Addr) {
        fn into_ie(self) -> Ie {
            use crate::ie::ue_ip_address::UeIpAddress;
            let (ipv4, ipv6) = self;
            let ue_ip = UeIpAddress::new(Some(ipv4), Some(ipv6));
            Ie::new(IeType::UeIpAddress, ue_ip.marshal())
        }
    }
}

// Re-export IntoIe for convenience
pub use builder_support::IntoIe;

// Implement ParseIe for all standard IE types that follow the
// `fn unmarshal(data: &[u8]) -> Result<Self, PfcpError>` pattern.
macro_rules! impl_parse_ie {
    ($($ty:ty),* $(,)?) => {
        $(
            impl ParseIe for $ty {
                fn parse_from_payload(data: &[u8]) -> Result<Self, PfcpError> {
                    Self::unmarshal(data)
                }
            }
        )*
    };
}

impl_parse_ie!(
    // Core session IEs
    cause::Cause,
    node_id::NodeId,
    fseid::Fseid,
    f_teid::Fteid,
    // Scalar ID IEs
    pdr_id::PdrId,
    far_id::FarId,
    urr_id::UrrId,
    qer_id::QerId,
    bar_id::BarId,
    // PDR / FAR / URR / QER components
    precedence::Precedence,
    source_interface::SourceInterface,
    destination_interface::DestinationInterface,
    network_instance::NetworkInstance,
    apply_action::ApplyAction,
    gate_status::GateStatus,
    mbr::Mbr,
    gbr::Gbr,
    reporting_triggers::ReportingTriggers,
    report_type::ReportType,
    ue_ip_address::UeIpAddress,
    outer_header_removal::OuterHeaderRemoval,
    outer_header_creation::OuterHeaderCreation,
    // Feature / capability IEs
    up_function_features::UPFunctionFeatures,
    cp_function_features::CPFunctionFeatures,
    // Timestamp & identity IEs
    recovery_time_stamp::RecoveryTimeStamp,
    nf_instance_id::NfInstanceId,
    alternative_smf_ip_address::AlternativeSmfIpAddress,
    smf_set_id::SmfSetId,
    pfcpas_req_flags::PfcpasReqFlags,
    pfcpas_rsp_flags::PfcpasRspFlags,
    // Grouped IEs
    clock_drift_control_information::ClockDriftControlInformation,
    clock_drift_report::ClockDriftReport,
    gtpu_path_qos_report::GtpuPathQosReport,
    qos_information_in_gtpu_path_qos_report::QosInformationInGtpuPathQosReport,
    provide_rds_configuration_information::ProvideRdsConfigurationInformation,
    rds_configuration_information::RdsConfigurationInformation,
    create_pdr::CreatePdr,
    create_far::CreateFar,
    create_mar::CreateMar,
    create_srr::CreateSrr,
    update_mar::UpdateMar,
    update_srr::UpdateSrr,
    tgpp_access_forwarding_action_information::TgppAccessForwardingActionInformation,
    non_tgpp_access_forwarding_action_information::NonTgppAccessForwardingActionInformation,
    update_tgpp_access_forwarding_action_information::UpdateTgppAccessForwardingActionInformation,
    update_non_tgpp_access_forwarding_action_information::UpdateNonTgppAccessForwardingActionInformation,
    tsc_management_information_within_session_modification_request::TscManagementInformationWithinSessionModificationRequest,
    tsc_management_information_within_session_modification_response::TscManagementInformationWithinSessionModificationResponse,
    query_packet_rate_status_within_session_modification_request::QueryPacketRateStatusWithinSessionModificationRequest,
    packet_rate_status_report_within_session_modification_response::PacketRateStatusReportWithinSessionModificationResponse,
    create_urr::CreateUrr,
    create_qer::CreateQer,
    create_bar::CreateBar,
    created_pdr::CreatedPdr,
    pdi::Pdi,
    forwarding_parameters::ForwardingParameters,
    update_far::UpdateFar,
    update_pdr::UpdatePdr,
    update_qer::UpdateQer,
    update_urr::UpdateUrr,
    usage_report_srr::UsageReportSrr,
    usage_report_smr::UsageReportSmr,
    usage_report_sdr::UsageReportSdr,
    pdn_type::PdnType,
    // Group D: ATSSS grouped IEs
    provide_atsss_control_information::ProvideAtsssControlInformation,
    atsss_control_parameters::AtsssControlParameters,
    mptcp_parameters::MptcpParameters,
    atsss_ll_parameters::AtsssLlParameters,
    pmf_parameters::PmfParameters,
    mpquic_parameters::MpquicParameters,
    // Group D: ATSSS control flag IEs
    mptcp_control_information::MptcpControlInformation,
    atsss_ll_control_information::AtsssLlControlInformation,
    pmf_control_information::PmfControlInformation,
    mpquic_control_information::MpquicControlInformation,
    // Group D: ATSSS result/address leaf IEs
    atsss_ll_information::AtsssLlInformation,
    mptcp_address_information::MptcpAddressInformation,
    link_specific_multipath_ip_address::LinkSpecificMultipathIpAddress,
    pmf_address_information::PmfAddressInformation,
    mpquic_address_information::MpquicAddressInformation,
    // Group F: MBS session-level grouped IEs
    mbs_session_n4mb_control_information::MbsSessionN4mbControlInformation,
    mbs_session_n4mb_information::MbsSessionN4mbInformation,
    mbs_session_n4_control_information::MbsSessionN4ControlInformation,
    mbs_session_n4_information::MbsSessionN4Information,
    // Group F: MBS FAR child grouped IEs
    mbs_multicast_parameters::MbsMulticastParameters,
    add_mbs_unicast_parameters::AddMbsUnicastParameters,
    remove_mbs_unicast_parameters::RemoveMbsUnicastParameters,
    // Group E: L2TP parent grouped IEs
    l2tp_tunnel_information::L2tpTunnelInformation,
    l2tp_session_information::L2tpSessionInformation,
    created_l2tp_session::CreatedL2tpSession,
    // Group E: L2TP child IEs
    lns_address::LnsAddress,
    tunnel_preference::TunnelPreference,
    calling_number::CallingNumber,
    called_number::CalledNumber,
    l2tp_session_indications::L2tpSessionIndications,
    dns_server_address::DnsServerAddress,
    nbns_server_address::NbnsServerAddress,
    maximum_receive_unit::MaximumReceiveUnit,
    // Phase 4: Simple scalar, flag, and opaque-container IEs
    aggregated_urr_id::AggregatedUrrId,
    bridge_management_information_container::BridgeManagementInformationContainer,
    configured_time_domain::ConfiguredTimeDomain,
    cumulative_rate_ratio_measurement::CumulativeRateRatioMeasurement,
    cumulative_rate_ratio_threshold::CumulativeRateRatioThreshold,
    dl_buffering_suggested_packet_count::DlBufferingSuggestedPacketCount,
    extended_dl_buffering_notification_policy::ExtendedDlBufferingNotificationPolicy,
    gtpu_path_interface_type::GtpuPathInterfaceType,
    mbs_unicast_parameters_id::MbsUnicastParametersId,
    media_transport_protocol::MediaTransportProtocol,
    metadata::Metadata,
    minimum_wait_time::MinimumWaitTime,
    mt_sdt_control_information::MtSdtControlInformation,
    port_management_information_container::PortManagementInformationContainer,
    reporting_control_information::ReportingControlInformation,
    rtp_header_extension_id::RtpHeaderExtensionId,
    rtp_header_extension_type::RtpHeaderExtensionType,
    rtp_payload_format::RtpPayloadFormat,
    rtp_payload_type::RtpPayloadType,
    time_offset_measurement::TimeOffsetMeasurement,
    time_offset_threshold::TimeOffsetThreshold,
    tl_container::TlContainer,
    transport_mode::TransportMode,
    ue_level_measurements_configuration::UeLevelMeasurementsConfiguration,
    vendor_specific_node_report_type::VendorSpecificNodeReportType,
    // Phase 5: Medium-complexity leaf IEs
    access_availability_information::AccessAvailabilityInformation,
    dscp_to_ppi_mapping_information::DscpToPpiMappingInformation,
    local_ingress_tunnel::LocalIngressTunnel,
    n6_routing_information::N6RoutingInformation,
    packet_delay_thresholds::PacketDelayThresholds,
    qos_monitoring_measurement::QosMonitoringMeasurement,
    remote_gtpu_peer::RemoteGtpuPeer,
    reporting_suggestion_info::ReportingSuggestionInfo,
    reporting_thresholds::ReportingThresholds,
    traffic_parameter_threshold::TrafficParameterThreshold,
    // Phase 6: Simple grouped IEs
    access_availability_control_information::AccessAvailabilityControlInformation,
    access_availability_report::AccessAvailabilityReport,
    additional_monitoring_time::AdditionalMonitoringTime,
    aggregated_urrs::AggregatedUrrs,
    create_bridge_info_for_tsc::CreateBridgeInfoForTsc,
    created_bridge_info_for_tsc::CreatedBridgeInfoForTsc,
    downlink_data_report::DownlinkDataReport,
    dscp_to_ppi_control_information::DscpToPpiControlInformation,
    error_indication_report::ErrorIndicationReport,
    ip_multicast_addressing_info::IpMulticastAddressingInfo,
    join_ip_multicast_information_within_usage_report::JoinIpMulticastInformationWithinUsageReport,
    leave_ip_multicast_information_within_usage_report::LeaveIpMulticastInformationWithinUsageReport,
    partial_failure_information::PartialFailureInformation,
    peer_up_restart_report::PeerUpRestartReport,
    remove_mar::RemoveMar,
    remove_srr::RemoveSrr,
    session_report::SessionReport,
    ue_ip_address_pool_information::UeIpAddressPoolInformation,
    updated_pdr::UpdatedPdr,
);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Seid, Teid};

    #[test]
    fn test_reject_zero_length_ie() {
        // IE: Recovery Time Stamp (Type 96), Length 0
        let malformed = vec![
            0x00, 0x60, // Type: 96
            0x00, 0x00, // Length: 0
        ];

        let result = Ie::unmarshal(&malformed);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, PfcpError::InvalidValue { .. }));
        assert!(err.to_string().contains("Zero-length"));
        assert!(err.to_string().contains("96"));
    }

    #[test]
    fn test_reject_zero_length_vendor_specific_ie() {
        // Vendor-specific IE (bit 15 set), Length 0
        let malformed = vec![
            0x80, 0x01, // Type: 32769 (vendor-specific)
            0x00, 0x00, // Length: 0
            0x00, 0x0A, // Enterprise ID: 10
        ];

        let result = Ie::unmarshal(&malformed);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, PfcpError::InvalidValue { .. }));
        assert!(err.to_string().contains("Zero-length"));
    }

    #[test]
    fn test_accept_valid_one_byte_ie() {
        // Cause IE (Type 19), Length 1, Value 1 (Request accepted)
        let valid = vec![
            0x00, 0x13, // Type: 19 (Cause)
            0x00, 0x01, // Length: 1
            0x01, // Value: 1
        ];

        let result = Ie::unmarshal(&valid);
        assert!(result.is_ok());
        let ie = result.unwrap();
        assert_eq!(ie.ie_type, IeType::Cause);
        assert_eq!(ie.payload.len(), 1);
        assert_eq!(ie.payload[0], 1);
    }

    #[test]
    fn test_security_dos_prevention() {
        // Simulate attack scenario from free5gc issue #483
        // Multiple zero-length IEs should all be rejected
        let attack_vectors = vec![
            vec![0x00, 0x60, 0x00, 0x00], // Recovery Time Stamp
            vec![0x00, 0x13, 0x00, 0x00], // Cause
            vec![0x00, 0x3C, 0x00, 0x00], // Node ID
            vec![0x00, 0x39, 0x00, 0x00], // F-SEID
        ];

        for malformed in attack_vectors {
            let result = Ie::unmarshal(&malformed);
            assert!(
                result.is_err(),
                "Should reject zero-length IE: {:?}",
                malformed
            );
        }
    }

    #[test]
    fn test_zero_length_allowlist_network_instance() {
        // Network Instance (Type 22) with zero length is valid per TS 29.244 R18
        let zero_length_ni = vec![
            0x00, 0x16, // Type: 22 (NetworkInstance)
            0x00, 0x00, // Length: 0
        ];

        let result = Ie::unmarshal(&zero_length_ni);
        assert!(result.is_ok(), "Network Instance should allow zero-length");
        let ie = result.unwrap();
        assert_eq!(ie.ie_type, IeType::NetworkInstance);
        assert_eq!(ie.payload.len(), 0);
    }

    #[test]
    fn test_zero_length_allowlist_apn_dnn() {
        // APN/DNN (Type 159) with zero length is valid (default APN)
        let zero_length_apn = vec![
            0x00, 0x9F, // Type: 159 (ApnDnn)
            0x00, 0x00, // Length: 0
        ];

        let result = Ie::unmarshal(&zero_length_apn);
        assert!(result.is_ok(), "APN/DNN should allow zero-length");
        let ie = result.unwrap();
        assert_eq!(ie.ie_type, IeType::ApnDnn);
        assert_eq!(ie.payload.len(), 0);
    }

    #[test]
    fn test_zero_length_allowlist_forwarding_policy() {
        // Forwarding Policy (Type 41) with zero length is valid (clear policy)
        let zero_length_fp = vec![
            0x00, 0x29, // Type: 41 (ForwardingPolicy)
            0x00, 0x00, // Length: 0
        ];

        let result = Ie::unmarshal(&zero_length_fp);
        assert!(result.is_ok(), "Forwarding Policy should allow zero-length");
        let ie = result.unwrap();
        assert_eq!(ie.ie_type, IeType::ForwardingPolicy);
        assert_eq!(ie.payload.len(), 0);
    }

    #[test]
    fn test_zero_length_rejected_for_non_allowlisted() {
        // Test that non-allowlisted IEs still reject zero-length
        let test_cases = vec![
            (0x0018, "ApplicationId"),   // Type 24
            (0x0017, "SdfFilter"),       // Type 23
            (0x0014, "SourceInterface"), // Type 20
            (0x001D, "Precedence"),      // Type 29
            (0x006C, "FarId"),           // Type 108
        ];

        for (ie_type, name) in test_cases {
            let zero_length_ie = vec![
                (ie_type >> 8) as u8,
                (ie_type & 0xFF) as u8,
                0x00,
                0x00, // Length: 0
            ];

            let result = Ie::unmarshal(&zero_length_ie);
            assert!(
                result.is_err(),
                "{} should reject zero-length (not in allowlist)",
                name
            );
            let err = result.unwrap_err();
            assert!(err.to_string().contains("Zero-length"));
        }
    }

    #[test]
    fn test_zero_length_update_far_scenario() {
        // Real-world scenario: Update FAR with zero-length Network Instance
        // This clears the network routing context per TS 29.244 R18
        use crate::ie::network_instance::NetworkInstance;

        // Create zero-length Network Instance IE
        let clear_ni = NetworkInstance::new("");
        let clear_ni_ie = clear_ni.to_ie();

        // Verify it marshals to zero-length
        let marshaled = clear_ni_ie.marshal();
        assert_eq!(marshaled[0..2], [0x00, 0x16]); // Type 22
        assert_eq!(marshaled[2..4], [0x00, 0x00]); // Length 0

        // Verify it can be unmarshaled
        let unmarshaled = Ie::unmarshal(&marshaled);
        assert!(
            unmarshaled.is_ok(),
            "Zero-length Network Instance should unmarshal successfully"
        );

        // Verify the payload is empty
        let ie = unmarshaled.unwrap();
        assert_eq!(ie.payload.len(), 0);
        assert_eq!(ie.ie_type, IeType::NetworkInstance);

        // Verify the NetworkInstance interprets empty correctly
        let ni_result = NetworkInstance::unmarshal(&ie.payload);
        assert!(ni_result.is_ok());
        assert_eq!(ni_result.unwrap().instance, "");
    }

    // ========================================================================
    // IE Type Conversion Tests
    // ========================================================================

    #[test]
    fn test_ie_type_from_u16_core_types() {
        // Test core IE types conversion from u16
        assert_eq!(IeType::from(1), IeType::CreatePdr);
        assert_eq!(IeType::from(2), IeType::Pdi);
        assert_eq!(IeType::from(3), IeType::CreateFar);
        assert_eq!(IeType::from(19), IeType::Cause);
        assert_eq!(IeType::from(56), IeType::PdrId);
        assert_eq!(IeType::from(57), IeType::Fseid);
        assert_eq!(IeType::from(60), IeType::NodeId);
        assert_eq!(IeType::from(108), IeType::FarId);
        assert_eq!(IeType::from(109), IeType::QerId);
    }

    #[test]
    fn test_ie_type_from_u16_session_types() {
        // Test session-related IE types
        assert_eq!(IeType::from(8), IeType::CreatedPdr);
        assert_eq!(IeType::from(9), IeType::UpdatePdr);
        assert_eq!(IeType::from(10), IeType::UpdateFar);
        assert_eq!(IeType::from(15), IeType::RemovePdr);
        assert_eq!(IeType::from(16), IeType::RemoveFar);
        assert_eq!(IeType::from(85), IeType::CreateBar);
        assert_eq!(IeType::from(86), IeType::UpdateBar);
        assert_eq!(IeType::from(87), IeType::RemoveBar);
        assert_eq!(IeType::from(88), IeType::BarId);
    }

    #[test]
    fn test_ie_type_from_u16_network_types() {
        // Test network-related IE types
        assert_eq!(IeType::from(20), IeType::SourceInterface);
        assert_eq!(IeType::from(21), IeType::Fteid);
        assert_eq!(IeType::from(22), IeType::NetworkInstance);
        assert_eq!(IeType::from(42), IeType::DestinationInterface);
        assert_eq!(IeType::from(84), IeType::OuterHeaderCreation);
        assert_eq!(IeType::from(95), IeType::OuterHeaderRemoval);
        assert_eq!(IeType::from(192), IeType::SourceIpAddress);
    }

    #[test]
    fn test_ie_type_from_u16_qos_types() {
        // Test QoS-related IE types
        assert_eq!(IeType::from(25), IeType::GateStatus);
        assert_eq!(IeType::from(26), IeType::Mbr);
        assert_eq!(IeType::from(27), IeType::Gbr);
        assert_eq!(IeType::from(29), IeType::Precedence);
        assert_eq!(IeType::from(30), IeType::TransportLevelMarking);
    }

    #[test]
    fn test_ie_type_from_u16_monitoring_types() {
        // Test monitoring and reporting IE types
        assert_eq!(IeType::from(62), IeType::MeasurementMethod);
        assert_eq!(IeType::from(63), IeType::UsageReportTrigger);
        assert_eq!(IeType::from(66), IeType::VolumeMeasurement);
        assert_eq!(IeType::from(67), IeType::DurationMeasurement);
        assert_eq!(IeType::from(96), IeType::RecoveryTimeStamp);
    }

    #[test]
    fn test_ie_type_from_u16_tsn_types() {
        // Test TSN (Time-Sensitive Networking) IE types
        assert_eq!(IeType::from(194), IeType::CreateBridgeInfoForTsc);
        assert_eq!(IeType::from(195), IeType::CreatedBridgeInfoForTsc);
        assert_eq!(IeType::from(198), IeType::TsnBridgeId);
        assert_eq!(IeType::from(206), IeType::TsnTimeDomainNumber);
    }

    #[test]
    fn test_ie_type_from_u16_5g_types() {
        // Test 5G-specific IE types
        assert_eq!(IeType::from(113), IeType::PdnType);
        assert_eq!(IeType::from(159), IeType::ApnDnn);
        assert_eq!(IeType::from(160), IeType::TgppInterfaceType);
        assert_eq!(IeType::from(257), IeType::Snssai);
    }

    #[test]
    fn test_ie_type_from_u16_unknown() {
        // Test unknown IE type
        assert_eq!(IeType::from(9999), IeType::Unknown);
        assert_eq!(IeType::from(0), IeType::Unknown);
        assert_eq!(IeType::from(65535), IeType::Unknown);
    }

    #[test]
    fn test_ie_type_to_u16_round_trip() {
        // Test that IE types can be converted to u16 and back
        let test_types = vec![
            IeType::CreatePdr,
            IeType::Cause,
            IeType::NodeId,
            IeType::Fteid,
            IeType::PdrId,
            IeType::FarId,
            IeType::Snssai,
            IeType::SourceIpAddress,
        ];

        for ie_type in test_types {
            let as_u16 = ie_type as u16;
            let back = IeType::from(as_u16);
            assert_eq!(back, ie_type, "Round-trip failed for {:?}", ie_type);
        }
    }

    // ========================================================================
    // IE Construction Tests
    // ========================================================================

    #[test]
    fn test_ie_new() {
        let payload = vec![0x01, 0x02, 0x03];
        let ie = Ie::new(IeType::Cause, payload.clone());

        assert_eq!(ie.ie_type, IeType::Cause);
        assert_eq!(ie.enterprise_id, None);
        assert_eq!(ie.payload, payload);
        assert_eq!(ie.child_ies.len(), 0);
        assert!(!ie.is_vendor_specific());
    }

    #[test]
    fn test_ie_new_vendor_specific() {
        let payload = vec![0xAA, 0xBB];
        let ie = Ie::new_vendor_specific(IeType::Unknown, 12345, payload.clone());

        assert_eq!(ie.ie_type, IeType::Unknown);
        assert_eq!(ie.enterprise_id, Some(12345));
        assert_eq!(ie.payload, payload);
        assert!(ie.is_vendor_specific());
    }

    #[test]
    fn test_ie_new_grouped() {
        // Create child IEs
        let child1 = Ie::new(IeType::PdrId, vec![0x00, 0x01]);
        let child2 = Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]);

        let grouped = Ie::new_grouped(IeType::CreatePdr, vec![child1.clone(), child2.clone()]);

        assert_eq!(grouped.ie_type, IeType::CreatePdr);
        assert_eq!(grouped.enterprise_id, None);
        assert_eq!(grouped.child_ies.len(), 2);

        // Payload should contain marshaled child IEs
        let expected_payload = {
            let mut v = Vec::new();
            v.extend_from_slice(&child1.marshal());
            v.extend_from_slice(&child2.marshal());
            v
        };
        assert_eq!(grouped.payload, expected_payload);
    }

    #[test]
    fn test_ie_from_marshal() {
        use crate::ie::cause::{Cause, CauseValue};
        use crate::ie::destination_interface::{DestinationInterface, Interface};

        // Test with IE that returns [u8; N] (array)
        let cause = Cause::new(CauseValue::RequestAccepted);
        let ie_from_array = Ie::from_marshal(IeType::Cause, cause.marshal());
        assert_eq!(ie_from_array.ie_type, IeType::Cause);
        assert_eq!(ie_from_array.payload, vec![1]);

        // Test with IE that returns Vec<u8>
        let dest_if = DestinationInterface::new(Interface::Core);
        let ie_from_vec = Ie::from_marshal(IeType::DestinationInterface, dest_if.marshal());
        assert_eq!(ie_from_vec.ie_type, IeType::DestinationInterface);
        assert_eq!(ie_from_vec.payload, vec![0x01]); // Interface::Core = 1

        // Verify both methods produce identical results to Ie::new()
        let ie_traditional = Ie::new(IeType::Cause, cause.marshal().to_vec());
        assert_eq!(ie_from_array, ie_traditional);
    }

    // ========================================================================
    // IE Property Tests
    // ========================================================================

    #[test]
    fn test_ie_len_simple() {
        let ie = Ie::new(IeType::Cause, vec![0x01]);
        // Type (2) + Length (2) + Payload (1) = 5, but len() returns header+payload size
        assert_eq!(ie.len(), 5);
    }

    #[test]
    fn test_ie_len_vendor_specific() {
        let ie = Ie::new_vendor_specific(IeType::Unknown, 123, vec![0xAA, 0xBB]);
        // Type (2) + Length (2) + Enterprise ID (2) + Payload (2) = 8
        assert_eq!(ie.len(), 8);
    }

    #[test]
    fn test_ie_is_empty() {
        let empty = Ie::new(IeType::NetworkInstance, vec![]);
        assert!(empty.is_empty());

        let not_empty = Ie::new(IeType::Cause, vec![0x01]);
        assert!(!not_empty.is_empty());
    }

    #[test]
    fn test_ie_is_vendor_specific_with_enterprise_id() {
        let ie = Ie::new_vendor_specific(IeType::Unknown, 100, vec![0x01]);
        assert!(ie.is_vendor_specific());
    }

    #[test]
    fn test_ie_is_vendor_specific_with_flag() {
        // Create IE with type that has bit 15 set (0x8000)
        // Since we can't modify the enum value, we test via unmarshal
        let vendor_ie_bytes = vec![
            0x80, 0x01, // Type with vendor bit set (32769)
            0x00, 0x02, // Length (2 bytes for enterprise ID)
            0x00, 0x0A, // Enterprise ID (10)
        ];
        let ie = Ie::unmarshal(&vendor_ie_bytes).unwrap();
        assert!(ie.is_vendor_specific());
        assert_eq!(ie.enterprise_id, Some(10));
    }

    // ========================================================================
    // IE Marshal/Unmarshal Tests
    // ========================================================================

    #[test]
    fn test_ie_marshal_simple() {
        let ie = Ie::new(IeType::Cause, vec![0x01]);
        let marshaled = ie.marshal();

        assert_eq!(marshaled[0..2], [0x00, 0x13]); // Type 19
        assert_eq!(marshaled[2..4], [0x00, 0x01]); // Length 1
        assert_eq!(marshaled[4], 0x01); // Payload
    }

    #[test]
    fn test_ie_marshal_vendor_specific() {
        let ie = Ie::new_vendor_specific(IeType::Unknown, 12345, vec![0xAA, 0xBB]);
        let marshaled = ie.marshal();

        assert_eq!(marshaled[0..2], [0x00, 0x00]); // Type 0 (Unknown)
        assert_eq!(marshaled[2..4], [0x00, 0x04]); // Length 4 (2 for eid + 2 for payload)
        assert_eq!(marshaled[4..6], [0x30, 0x39]); // Enterprise ID 12345
        assert_eq!(marshaled[6..8], [0xAA, 0xBB]); // Payload
    }

    #[test]
    fn test_ie_unmarshal_simple_round_trip() {
        let original = Ie::new(IeType::PdrId, vec![0x00, 0x42]);
        let marshaled = original.marshal();
        let unmarshaled = Ie::unmarshal(&marshaled).unwrap();

        assert_eq!(unmarshaled.ie_type, original.ie_type);
        assert_eq!(unmarshaled.enterprise_id, original.enterprise_id);
        assert_eq!(unmarshaled.payload, original.payload);
    }

    #[test]
    fn test_ie_unmarshal_vendor_specific_round_trip() {
        // Test unmarshal of vendor-specific IE with enterprise bit set
        let vendor_ie_bytes = vec![
            0x80, 0x01, // Type with vendor bit set (32769)
            0x00, 0x05, // Length (2 for enterprise ID + 3 for payload)
            0x03, 0xE7, // Enterprise ID (999)
            0x01, 0x02, 0x03, // Payload
        ];

        let unmarshaled = Ie::unmarshal(&vendor_ie_bytes).unwrap();
        assert!(unmarshaled.is_vendor_specific());
        assert_eq!(unmarshaled.enterprise_id, Some(999));
        assert_eq!(unmarshaled.payload, vec![0x01, 0x02, 0x03]);
    }

    #[test]
    fn test_ie_unmarshal_too_short() {
        let short_buffer = vec![0x00, 0x13, 0x00]; // Only 3 bytes
        let result = Ie::unmarshal(&short_buffer);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_unmarshal_payload_length_mismatch() {
        let malformed = vec![
            0x00, 0x13, // Type: Cause
            0x00, 0x05, // Length: 5
            0x01, // Payload: only 1 byte (expected 5)
        ];
        let result = Ie::unmarshal(&malformed);

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_unmarshal_vendor_specific_too_short() {
        // Buffer too short for enterprise ID parsing
        let malformed = vec![
            0x80, 0x01, // Type with vendor bit
            0x00, 0x02, // Length: 2
            0x00, // Only 1 byte (need 2 for enterprise ID)
        ];
        let result = Ie::unmarshal(&malformed);

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, PfcpError::InvalidLength { .. }));
    }

    // ========================================================================
    // IE Value Accessor Tests
    // ========================================================================

    #[test]
    fn test_ie_as_u8() {
        let ie = Ie::new(IeType::Cause, vec![0x42]);
        assert_eq!(ie.as_u8().unwrap(), 0x42);
    }

    #[test]
    fn test_ie_as_u8_empty_payload() {
        let ie = Ie::new(IeType::NetworkInstance, vec![]);
        let result = ie.as_u8();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_as_u16() {
        let ie = Ie::new(IeType::PdrId, vec![0x12, 0x34]);
        assert_eq!(ie.as_u16().unwrap(), 0x1234);
    }

    #[test]
    fn test_ie_as_u16_too_short() {
        let ie = Ie::new(IeType::PdrId, vec![0x12]);
        let result = ie.as_u16();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_as_u32() {
        let ie = Ie::new(IeType::FarId, vec![0x12, 0x34, 0x56, 0x78]);
        assert_eq!(ie.as_u32().unwrap(), 0x12345678);
    }

    #[test]
    fn test_ie_as_u32_too_short() {
        let ie = Ie::new(IeType::FarId, vec![0x12, 0x34]);
        let result = ie.as_u32();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_as_u64() {
        let ie = Ie::new(
            IeType::Fseid,
            vec![0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0],
        );
        assert_eq!(ie.as_u64().unwrap(), 0x123456789ABCDEF0);
    }

    #[test]
    fn test_ie_as_u64_too_short() {
        let ie = Ie::new(IeType::Fseid, vec![0x12, 0x34, 0x56, 0x78]);
        let result = ie.as_u64();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_as_string() {
        let ie = Ie::new(
            IeType::NetworkInstance,
            b"internet.mnc001.mcc001.gprs".to_vec(),
        );
        assert_eq!(ie.as_string().unwrap(), "internet.mnc001.mcc001.gprs");
    }

    #[test]
    fn test_ie_as_string_invalid_utf8() {
        let ie = Ie::new(IeType::NetworkInstance, vec![0xFF, 0xFE, 0xFD]);
        let result = ie.as_string();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidValue { .. }
        ));
    }

    // ========================================================================
    // Grouped IE Tests
    // ========================================================================

    #[test]
    fn test_ie_as_ies_simple() {
        // Create a grouped IE with two children
        let child1 = Ie::new(IeType::PdrId, vec![0x00, 0x01]);
        let child2 = Ie::new(IeType::Precedence, vec![0x00, 0x64]);

        let mut grouped = Ie::new_grouped(IeType::CreatePdr, vec![child1, child2]);

        let children = grouped.as_ies().unwrap();
        assert_eq!(children.len(), 2);
        assert_eq!(children[0].ie_type, IeType::PdrId);
        assert_eq!(children[1].ie_type, IeType::Precedence);
    }

    #[test]
    fn test_ie_as_ies_cached() {
        // Create a grouped IE
        let child = Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x01]);
        let mut grouped = Ie::new_grouped(IeType::CreateFar, vec![child]);

        // First call parses children
        let children1 = grouped.as_ies().unwrap();
        assert_eq!(children1.len(), 1);

        // Second call should return cached children
        let children2 = grouped.as_ies().unwrap();
        assert_eq!(children2.len(), 1);
        assert_eq!(children2[0].ie_type, IeType::FarId);
    }

    #[test]
    fn test_ie_as_ies_empty_payload() {
        let mut ie = Ie::new(IeType::CreatePdr, vec![]);
        let children = ie.as_ies().unwrap();
        assert_eq!(children.len(), 0);
    }

    #[test]
    fn test_ie_as_ies_malformed_child() {
        // Payload contains incomplete child IE
        let mut ie = Ie::new(IeType::CreatePdr, vec![0x00, 0x38]); // Only type, no length
        let result = ie.as_ies();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PfcpError::InvalidLength { .. }
        ));
    }

    #[test]
    fn test_ie_as_ies_nested() {
        // Create nested grouped IEs
        let inner_child = Ie::new(IeType::SourceInterface, vec![0x00]);
        let inner_grouped = Ie::new_grouped(IeType::Pdi, vec![inner_child]);

        let pdr_id = Ie::new(IeType::PdrId, vec![0x00, 0x01]);
        let mut outer_grouped = Ie::new_grouped(IeType::CreatePdr, vec![pdr_id, inner_grouped]);

        let children = outer_grouped.as_ies().unwrap();
        assert_eq!(children.len(), 2);
        assert_eq!(children[0].ie_type, IeType::PdrId);
        assert_eq!(children[1].ie_type, IeType::Pdi);

        // Parse nested children
        let mut pdi = children[1].clone();
        let nested_children = pdi.as_ies().unwrap();
        assert_eq!(nested_children.len(), 1);
        assert_eq!(nested_children[0].ie_type, IeType::SourceInterface);
    }

    // ========================================================================
    // Edge Cases and Integration Tests
    // ========================================================================

    #[test]
    fn test_ie_large_payload() {
        // Test with maximum reasonable payload size
        let large_payload = vec![0x42; 1000];
        let ie = Ie::new(IeType::NetworkInstance, large_payload.clone());
        let marshaled = ie.marshal();
        let unmarshaled = Ie::unmarshal(&marshaled).unwrap();

        assert_eq!(unmarshaled.payload, large_payload);
    }

    #[test]
    fn test_ie_all_ie_types_round_trip() {
        // Test a sample of all IE type categories
        let test_types = vec![
            (IeType::CreatePdr, vec![0x01, 0x02]),
            (IeType::Cause, vec![0x01]),
            (IeType::NodeId, vec![0x00, 0x01, 0x02, 0x03, 0x04]),
            (IeType::Fseid, vec![0x01; 8]),
            (IeType::Snssai, vec![0x01, 0x02, 0x03, 0x04]),
            (IeType::SourceIpAddress, vec![0x01; 4]),
            (IeType::RecoveryTimeStamp, vec![0x00, 0x00, 0x00, 0x01]),
        ];

        for (ie_type, payload) in test_types {
            let original = Ie::new(ie_type, payload);
            let marshaled = original.marshal();
            let unmarshaled = Ie::unmarshal(&marshaled).unwrap();

            assert_eq!(
                unmarshaled.ie_type, original.ie_type,
                "Failed for {:?}",
                ie_type
            );
            assert_eq!(
                unmarshaled.payload, original.payload,
                "Failed for {:?}",
                ie_type
            );
        }
    }

    // IntoIe trait tests for tuple conversions
    mod into_ie_tests {
        use super::*;
        use crate::ie::fseid::Fseid;
        use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

        #[test]
        fn test_into_ie_tuple_fseid_ipv4() {
            let seid = 0x123456789ABCDEFu64;
            let ipv4 = Ipv4Addr::new(10, 0, 0, 1);
            let ie = (seid, ipv4).into_ie();

            assert_eq!(ie.ie_type, IeType::Fseid);

            let fseid = Fseid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fseid.seid, Seid(seid));
            assert_eq!(fseid.ipv4_address, Some(ipv4));
            assert_eq!(fseid.ipv6_address, None);
        }

        #[test]
        fn test_into_ie_tuple_fseid_ipv6() {
            let seid = 0x123456789ABCDEFu64;
            let ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
            let ie = (seid, ipv6).into_ie();

            assert_eq!(ie.ie_type, IeType::Fseid);

            let fseid = Fseid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fseid.seid, Seid(seid));
            assert_eq!(fseid.ipv4_address, None);
            assert_eq!(fseid.ipv6_address, Some(ipv6));
        }

        #[test]
        fn test_into_ie_tuple_fseid_ipaddr_v4() {
            let seid = 0x123456789ABCDEFu64;
            let ip = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
            let ie = (seid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fseid);

            let fseid = Fseid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fseid.seid, Seid(seid));
            assert!(fseid.ipv4_address.is_some());
            assert!(fseid.ipv6_address.is_none());
        }

        #[test]
        fn test_into_ie_tuple_fseid_ipaddr_v6() {
            let seid = 0x123456789ABCDEFu64;
            let ip = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
            let ie = (seid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fseid);

            let fseid = Fseid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fseid.seid, Seid(seid));
            assert!(fseid.ipv4_address.is_none());
            assert!(fseid.ipv6_address.is_some());
        }

        #[test]
        fn test_into_ie_tuple_fseid_round_trip() {
            let seid = 0xFEDCBA9876543210u64;
            let ipv4 = Ipv4Addr::new(192, 168, 1, 1);

            // Create IE from tuple
            let ie = (seid, ipv4).into_ie();

            // Unmarshal and verify
            let fseid = Fseid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fseid.seid, Seid(seid));
            assert_eq!(fseid.ipv4_address, Some(ipv4));

            // Verify it matches explicit construction
            let explicit_fseid = Fseid::new(seid, Some(ipv4), None);
            assert_eq!(fseid, explicit_fseid);
        }

        #[test]
        fn test_into_ie_tuple_fteid_ipv4() {
            use crate::ie::f_teid::Fteid;

            let teid = 0x12345678u32;
            let ip = Ipv4Addr::new(192, 168, 1, 1);

            let ie = (teid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fteid);
            let fteid = Fteid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fteid.teid, Teid(teid));
            assert_eq!(fteid.ipv4_address, Some(ip));
            assert_eq!(fteid.ipv6_address, None);
            assert!(fteid.v4);
            assert!(!fteid.v6);
        }

        #[test]
        fn test_into_ie_tuple_fteid_ipv6() {
            use crate::ie::f_teid::Fteid;

            let teid = 0x87654321u32;
            let ip = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);

            let ie = (teid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fteid);
            let fteid = Fteid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fteid.teid, Teid(teid));
            assert_eq!(fteid.ipv4_address, None);
            assert_eq!(fteid.ipv6_address, Some(ip));
            assert!(!fteid.v4);
            assert!(fteid.v6);
        }

        #[test]
        fn test_into_ie_tuple_fteid_ipaddr_v4() {
            use crate::ie::f_teid::Fteid;

            let teid = 0xABCD1234u32;
            let ipv4 = Ipv4Addr::new(10, 0, 0, 1);
            let ip: IpAddr = IpAddr::V4(ipv4);

            let ie = (teid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fteid);
            let fteid = Fteid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fteid.teid, Teid(teid));
            assert_eq!(fteid.ipv4_address, Some(ipv4));
            assert_eq!(fteid.ipv6_address, None);
        }

        #[test]
        fn test_into_ie_tuple_fteid_ipaddr_v6() {
            use crate::ie::f_teid::Fteid;

            let teid = 0xDEADBEEFu32;
            let ipv6 = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
            let ip: IpAddr = IpAddr::V6(ipv6);

            let ie = (teid, ip).into_ie();

            assert_eq!(ie.ie_type, IeType::Fteid);
            let fteid = Fteid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fteid.teid, Teid(teid));
            assert_eq!(fteid.ipv4_address, None);
            assert_eq!(fteid.ipv6_address, Some(ipv6));
        }

        #[test]
        fn test_into_ie_tuple_fteid_round_trip() {
            use crate::ie::f_teid::Fteid;

            let teid = 0xCAFEBABEu32;
            let ipv4 = Ipv4Addr::new(172, 16, 0, 1);

            // Create IE from tuple
            let ie = (teid, ipv4).into_ie();

            // Unmarshal and verify
            let fteid = Fteid::unmarshal(&ie.payload).unwrap();
            assert_eq!(fteid.teid, Teid(teid));
            assert_eq!(fteid.ipv4_address, Some(ipv4));

            // Verify it matches explicit construction
            let explicit_fteid = Fteid::new(true, false, teid, Some(ipv4), None, 0);
            assert_eq!(fteid, explicit_fteid);
        }

        #[test]
        fn test_into_ie_tuple_ue_ip_dual_stack() {
            use crate::ie::ue_ip_address::UeIpAddress;

            let ipv4 = Ipv4Addr::new(10, 1, 2, 3);
            let ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0xabc, 0xdef, 0, 0, 0, 1);

            let ie = (ipv4, ipv6).into_ie();

            assert_eq!(ie.ie_type, IeType::UeIpAddress);
            let ue_ip = UeIpAddress::unmarshal(&ie.payload).unwrap();
            assert_eq!(ue_ip.ipv4_address, Some(ipv4));
            assert_eq!(ue_ip.ipv6_address, Some(ipv6));
            assert!(ue_ip.v4);
            assert!(ue_ip.v6);
        }

        #[test]
        fn test_into_ie_tuple_ue_ip_round_trip() {
            use crate::ie::ue_ip_address::UeIpAddress;

            let ipv4 = Ipv4Addr::new(192, 0, 2, 1);
            let ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 42);

            // Create IE from tuple
            let ie = (ipv4, ipv6).into_ie();

            // Unmarshal and verify
            let ue_ip = UeIpAddress::unmarshal(&ie.payload).unwrap();
            assert_eq!(ue_ip.ipv4_address, Some(ipv4));
            assert_eq!(ue_ip.ipv6_address, Some(ipv6));

            // Verify it matches explicit construction
            let explicit_ue_ip = UeIpAddress::new(Some(ipv4), Some(ipv6));
            assert_eq!(ue_ip, explicit_ue_ip);
        }
    }

    /// Tests for grouped IE helper functions (Phase 2)
    mod grouped_ie_helpers {
        use super::*;

        #[test]
        fn test_marshal_ies_empty() {
            let ies: Vec<Ie> = vec![];
            let result = marshal_ies(&ies);
            assert_eq!(result.len(), 0);
        }

        #[test]
        fn test_marshal_ies_single() {
            let ies = vec![Ie::new(IeType::PdrId, vec![0x00, 0x01])];
            let result = marshal_ies(&ies);

            // Verify result contains IE header + payload
            // IE header is 4 bytes (type:2 + length:2)
            assert!(result.len() >= 4);

            // Verify length matches sum of IE lengths
            let expected_len: usize = ies.iter().map(|ie| ie.len() as usize).sum();
            assert_eq!(result.len(), expected_len);
        }

        #[test]
        fn test_marshal_ies_multiple() {
            let ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
                Ie::new(IeType::Precedence, vec![0x00, 0x00, 0x00, 0x64]),
            ];
            let result = marshal_ies(&ies);

            // Verify length matches sum of all IE lengths
            let expected_len: usize = ies.iter().map(|ie| ie.len() as usize).sum();
            assert_eq!(result.len(), expected_len);
        }

        #[test]
        fn test_marshal_ies_round_trip() {
            // Create some IEs, marshal them, then unmarshal and verify
            let original_ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
            ];

            let marshaled = marshal_ies(&original_ies);

            // Use IeIterator to parse them back
            let mut parsed_ies = vec![];
            for ie_result in IeIterator::new(&marshaled) {
                parsed_ies.push(ie_result.unwrap());
            }

            assert_eq!(parsed_ies.len(), original_ies.len());
            assert_eq!(parsed_ies[0].ie_type, IeType::PdrId);
            assert_eq!(parsed_ies[1].ie_type, IeType::FarId);
        }

        #[test]
        fn test_ie_iterator_empty() {
            let payload: Vec<u8> = vec![];
            let mut iter = IeIterator::new(&payload);
            assert!(iter.next().is_none());
        }

        #[test]
        fn test_ie_iterator_single() {
            // Create valid IE payload
            let ie = Ie::new(IeType::PdrId, vec![0x00, 0x01]);
            let payload = ie.marshal();

            let mut count = 0;
            for ie_result in IeIterator::new(&payload) {
                let parsed_ie = ie_result.unwrap();
                assert_eq!(parsed_ie.ie_type, IeType::PdrId);
                assert_eq!(parsed_ie.payload, vec![0x00, 0x01]);
                count += 1;
            }
            assert_eq!(count, 1);
        }

        #[test]
        fn test_ie_iterator_multiple() {
            let ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
                Ie::new(IeType::Precedence, vec![0x00, 0x00, 0x00, 0x64]),
            ];
            let payload = marshal_ies(&ies);

            let mut count = 0;
            let expected_types = [IeType::PdrId, IeType::FarId, IeType::Precedence];

            for ie_result in IeIterator::new(&payload) {
                let ie = ie_result.unwrap();
                assert_eq!(ie.ie_type, expected_types[count]);
                count += 1;
            }
            assert_eq!(count, 3);
        }

        #[test]
        fn test_ie_iterator_with_question_mark_operator() {
            // Test that the iterator works well with ? operator
            fn parse_ies(payload: &[u8]) -> Result<Vec<IeType>, PfcpError> {
                let mut types = vec![];
                for ie_result in IeIterator::new(payload) {
                    let ie = ie_result?; // ← Test ? operator
                    types.push(ie.ie_type);
                }
                Ok(types)
            }

            let ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
            ];
            let payload = marshal_ies(&ies);

            let types = parse_ies(&payload).unwrap();
            assert_eq!(types, vec![IeType::PdrId, IeType::FarId]);
        }

        #[test]
        fn test_ie_iterator_error_truncated() {
            // Malformed payload (truncated IE header)
            let payload = vec![0x00, 0x01]; // IE header needs 4 bytes minimum

            let mut iter = IeIterator::new(&payload);
            match iter.next() {
                Some(Err(_)) => (), // Expected error
                other => panic!("Expected error for truncated payload, got: {:?}", other),
            }

            // Iterator should stop after error
            assert!(iter.next().is_none());
        }

        #[test]
        fn test_ie_iterator_stops_on_error() {
            // Create payload with valid IE followed by truncated IE
            let valid_ie = Ie::new(IeType::PdrId, vec![0x00, 0x01]);
            let mut payload = valid_ie.marshal();
            payload.extend_from_slice(&[0x00, 0x01]); // Truncated IE

            let mut count = 0;
            let mut error_found = false;

            for ie_result in IeIterator::new(&payload) {
                match ie_result {
                    Ok(_) => count += 1,
                    Err(_) => {
                        error_found = true;
                        break;
                    }
                }
            }

            assert_eq!(count, 1, "Should parse one valid IE");
            assert!(error_found, "Should encounter error on truncated IE");
        }

        #[test]
        fn test_marshal_ies_preserves_order() {
            // Verify that marshal_ies preserves IE order
            let ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::Precedence, vec![0x00, 0x00, 0x00, 0x64]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
            ];

            let marshaled = marshal_ies(&ies);

            // Parse back and verify order
            let mut types = vec![];
            for ie_result in IeIterator::new(&marshaled) {
                types.push(ie_result.unwrap().ie_type);
            }

            assert_eq!(
                types,
                vec![IeType::PdrId, IeType::Precedence, IeType::FarId]
            );
        }

        #[test]
        fn test_ie_iterator_offset_tracking() {
            // Verify that offset is tracked correctly
            let ies = vec![
                Ie::new(IeType::PdrId, vec![0x00, 0x01]),
                Ie::new(IeType::FarId, vec![0x00, 0x00, 0x00, 0x02]),
            ];
            let payload = marshal_ies(&ies);

            let mut iter = IeIterator::new(&payload);

            // First IE
            assert_eq!(iter.offset, 0);
            let ie1 = iter.next().unwrap().unwrap();
            let ie1_len = ie1.len() as usize;
            assert_eq!(iter.offset, ie1_len);

            // Second IE
            let ie2 = iter.next().unwrap().unwrap();
            assert_eq!(iter.offset, ie1_len + ie2.len() as usize);

            // End of payload
            assert_eq!(iter.offset, payload.len());
            assert!(iter.next().is_none());
        }
    }

    // ========================================================================
    // ParseIe Tests
    // ========================================================================

    #[test]
    fn test_parse_cause() {
        use cause::{Cause, CauseValue};
        let ie = Ie::new(IeType::Cause, vec![1]);
        let cause = ie.parse::<Cause>().unwrap();
        assert_eq!(cause.value, CauseValue::RequestAccepted);
    }

    #[test]
    fn test_parse_cause_error_on_empty() {
        use cause::Cause;
        let ie = Ie::new(IeType::Cause, vec![]);
        // payload is empty but we're calling parse directly on the Ie,
        // bypassing the zero-length wire check — parse still errors correctly.
        assert!(ie.parse::<Cause>().is_err());
    }

    #[test]
    fn test_parse_pdr_id() {
        use pdr_id::PdrId;
        let original = PdrId::new(42);
        let ie = original.to_ie();
        let parsed = ie.parse::<PdrId>().unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_parse_far_id() {
        use far_id::FarId;
        let original = FarId::new(7);
        let ie = original.to_ie();
        let parsed = ie.parse::<FarId>().unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_parse_node_id() {
        use node_id::NodeId;
        let original = NodeId::new_ipv4("192.168.1.1".parse().unwrap());
        let ie = original.to_ie();
        let parsed = ie.parse::<NodeId>().unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_parse_recovery_time_stamp() {
        use std::time::Duration;
        use std::time::UNIX_EPOCH;
        let original = RecoveryTimeStamp::new(UNIX_EPOCH + Duration::from_secs(1_700_000_000));
        let ie = original.to_ie();
        let parsed = ie.parse::<RecoveryTimeStamp>().unwrap();
        assert_eq!(
            parsed
                .timestamp
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            original
                .timestamp
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        );
    }

    #[test]
    fn test_parse_works_on_any_ie_reference() {
        // Verify that parse works on both owned and borrowed Ie
        use cause::{Cause, CauseValue};
        let ie = Ie::new(IeType::Cause, vec![64]);
        let cause = ie.parse::<Cause>().unwrap();
        assert_eq!(cause.value, CauseValue::RequestRejected);

        // Works via reference too (auto-deref applies)
        let cause_ref = ie.parse::<Cause>().unwrap();
        assert_eq!(cause_ref.value, CauseValue::RequestRejected);
    }
}