netget-tool 0.3.5

Network protocol stubbing toolkit: ~280 protocol servers and clients whose responses come from an LLM, a script, a static rule or a person.
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
//! NGAP (3GPP TS 38.413) PDU structure, the IEs of the procedures NetGet speaks, and message
//! builders — shared by the AMF (server) and the gNB (client).
//!
//! # What is decoded and what is skipped
//!
//! An NGAP PDU is a CHOICE of initiating / successful / unsuccessful message, each carrying a
//! procedure code, a criticality and an open type holding a `ProtocolIE-Container`: a list of
//! `(id, criticality, open type)` fields. [`decode_pdu`] walks that outer structure for every
//! procedure, so any NGAP message can be framed, named and have its IE ids reported. The IE
//! *values* are decoded only for the procedures listed in [`procedure_name`]'s implemented set:
//! NG Setup, Initial UE Message, Downlink/Uplink NAS Transport, Error Indication, NG Reset and UE
//! Context Release. An IE NetGet does not decode stays as its raw octets and is surfaced by id —
//! the open-type framing is exactly what lets a receiver do that honestly.
//!
//! Every value is checked against its ASN.1 constraint on the way in *and* on the way out, so an
//! action cannot put a 33-bit gNB ID or an eleven-digit MCC on the wire.
//!
//! # Bounds
//!
//! [`MAX_PDU_LEN`] bounds the PDU, [`MAX_IES`] the IE count per container, [`MAX_NAS_PDU_LEN`] the
//! NAS-PDU, and every `SEQUENCE OF` is bounded by its own 38.413 constraint *and* by
//! [`MAX_LIST_ITEMS`] in total per decode, so the structure handed to the model is bounded however
//! the peer nests its lists. No decoder here recurses.

use super::aper::{self, AperError, Reader, Writer};
use serde_json::{json, Map, Value};

/// SCTP Payload Protocol Identifier for NGAP (TS 38.412 section 7).
pub const PPID: u32 = 60;
/// SCTP port the AMF listens on (TS 38.412 section 7, IANA).
pub const SCTP_PORT: u16 = 38412;
/// Largest NGAP PDU accepted or written. NGAP itself has no length field; this is the bound on
/// one SCTP message (or one lab-transport frame).
pub const MAX_PDU_LEN: usize = 65_535;
/// IEs accepted in one `ProtocolIE-Container`. The constraint allows 65535; the largest message in
/// NetGet's subset carries about ten.
pub const MAX_IES: usize = 64;
/// Largest NAS-PDU accepted or written. A 5GMM message NetGet handles is under a hundred octets;
/// 8 KiB leaves room for any capability container a UE might add without approaching the APER
/// fragmentation threshold.
pub const MAX_NAS_PDU_LEN: usize = 8_192;
/// `SEQUENCE OF` elements decoded per PDU, summed across every list in it.
pub const MAX_LIST_ITEMS: usize = 1_024;

// Procedure codes (TS 38.413 section 9.4.7).
pub const PROC_AMF_CONFIGURATION_UPDATE: u8 = 0;
pub const PROC_DOWNLINK_NAS_TRANSPORT: u8 = 4;
pub const PROC_ERROR_INDICATION: u8 = 9;
pub const PROC_INITIAL_UE_MESSAGE: u8 = 15;
pub const PROC_NG_RESET: u8 = 20;
pub const PROC_NG_SETUP: u8 = 21;
pub const PROC_RAN_CONFIGURATION_UPDATE: u8 = 35;
pub const PROC_UE_CONTEXT_RELEASE: u8 = 41;
pub const PROC_UPLINK_NAS_TRANSPORT: u8 = 46;

// IE ids (TS 38.413 section 9.4.7).
pub const IE_AMF_NAME: u16 = 1;
pub const IE_AMF_SET_ID: u16 = 3;
pub const IE_AMF_UE_NGAP_ID: u16 = 10;
pub const IE_CAUSE: u16 = 15;
pub const IE_CRITICALITY_DIAGNOSTICS: u16 = 19;
pub const IE_DEFAULT_PAGING_DRX: u16 = 21;
pub const IE_FIVE_G_S_TMSI: u16 = 26;
pub const IE_GLOBAL_RAN_NODE_ID: u16 = 27;
pub const IE_NAS_PDU: u16 = 38;
pub const IE_PLMN_SUPPORT_LIST: u16 = 80;
pub const IE_RAN_NODE_NAME: u16 = 82;
pub const IE_RAN_UE_NGAP_ID: u16 = 85;
pub const IE_RELATIVE_AMF_CAPACITY: u16 = 86;
pub const IE_RESET_TYPE: u16 = 88;
pub const IE_RRC_ESTABLISHMENT_CAUSE: u16 = 90;
pub const IE_SERVED_GUAMI_LIST: u16 = 96;
pub const IE_SUPPORTED_TA_LIST: u16 = 102;
pub const IE_TIME_TO_WAIT: u16 = 107;
pub const IE_UE_ASSOCIATED_LOGICAL_NG_CONNECTION_LIST: u16 = 111;
pub const IE_UE_CONTEXT_REQUEST: u16 = 112;
pub const IE_UE_NGAP_IDS: u16 = 114;
pub const IE_USER_LOCATION_INFORMATION: u16 = 121;

pub const MAX_AMF_UE_NGAP_ID: u64 = (1 << 40) - 1;
pub const MAX_RAN_UE_NGAP_ID: u64 = u32::MAX as u64;

/// Name of a procedure code, for logs and events. `None` for a code NetGet has no name for.
pub fn procedure_name(code: u8) -> Option<&'static str> {
    Some(match code {
        0 => "AMFConfigurationUpdate",
        1 => "AMFStatusIndication",
        4 => "DownlinkNASTransport",
        9 => "ErrorIndication",
        12 => "HandoverPreparation",
        14 => "InitialContextSetup",
        15 => "InitialUEMessage",
        20 => "NGReset",
        21 => "NGSetup",
        24 => "Paging",
        25 => "PathSwitchRequest",
        26 => "PDUSessionResourceModify",
        29 => "PDUSessionResourceRelease",
        30 => "PDUSessionResourceSetup",
        35 => "RANConfigurationUpdate",
        40 => "UEContextModification",
        41 => "UEContextRelease",
        42 => "UEContextReleaseRequest",
        44 => "UERadioCapabilityInfoIndication",
        46 => "UplinkNASTransport",
        _ => return None,
    })
}

/// Name of an IE id NetGet decodes, for events. Others are reported by number.
pub fn ie_name(id: u16) -> Option<&'static str> {
    Some(match id {
        IE_AMF_NAME => "AMFName",
        IE_AMF_SET_ID => "AMFSetID",
        IE_AMF_UE_NGAP_ID => "AMF-UE-NGAP-ID",
        IE_CAUSE => "Cause",
        IE_CRITICALITY_DIAGNOSTICS => "CriticalityDiagnostics",
        IE_DEFAULT_PAGING_DRX => "DefaultPagingDRX",
        IE_FIVE_G_S_TMSI => "FiveG-S-TMSI",
        IE_GLOBAL_RAN_NODE_ID => "GlobalRANNodeID",
        IE_NAS_PDU => "NAS-PDU",
        IE_PLMN_SUPPORT_LIST => "PLMNSupportList",
        IE_RAN_NODE_NAME => "RANNodeName",
        IE_RAN_UE_NGAP_ID => "RAN-UE-NGAP-ID",
        IE_RELATIVE_AMF_CAPACITY => "RelativeAMFCapacity",
        IE_RESET_TYPE => "ResetType",
        IE_RRC_ESTABLISHMENT_CAUSE => "RRCEstablishmentCause",
        IE_SERVED_GUAMI_LIST => "ServedGUAMIList",
        IE_SUPPORTED_TA_LIST => "SupportedTAList",
        IE_TIME_TO_WAIT => "TimeToWait",
        IE_UE_ASSOCIATED_LOGICAL_NG_CONNECTION_LIST => "UE-associatedLogicalNG-connectionList",
        IE_UE_CONTEXT_REQUEST => "UEContextRequest",
        IE_UE_NGAP_IDS => "UE-NGAP-IDs",
        IE_USER_LOCATION_INFORMATION => "UserLocationInformation",
        _ => return None,
    })
}

// ============================================================================
// Errors carry the Cause the peer is answered with
// ============================================================================

/// A PDU NetGet refuses, with the NGAP Cause that tells the peer why. The detail is for the log
/// only; nothing in it is put on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtocolError {
    pub cause: Cause,
    pub detail: String,
}

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

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

impl From<AperError> for ProtocolError {
    fn from(e: AperError) -> Self {
        ProtocolError {
            cause: Cause::protocol(PROTOCOL_TRANSFER_SYNTAX_ERROR),
            detail: e.0,
        }
    }
}

fn abstract_reject(detail: impl Into<String>) -> ProtocolError {
    ProtocolError {
        cause: Cause::protocol(PROTOCOL_ABSTRACT_SYNTAX_ERROR_REJECT),
        detail: detail.into(),
    }
}

fn semantic(detail: impl Into<String>) -> ProtocolError {
    ProtocolError {
        cause: Cause::protocol(PROTOCOL_SEMANTIC_ERROR),
        detail: detail.into(),
    }
}

pub type CodecResult<T> = Result<T, ProtocolError>;

/// An encode refusal: what the action asked for cannot be put on the wire.
#[derive(Debug, Clone)]
pub struct EncodeError(pub String);

impl std::fmt::Display for EncodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

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

impl From<AperError> for EncodeError {
    fn from(e: AperError) -> Self {
        EncodeError(e.0)
    }
}

pub type EncodeResult<T> = Result<T, EncodeError>;

fn enc_err<T>(msg: impl Into<String>) -> EncodeResult<T> {
    Err(EncodeError(msg.into()))
}

// ============================================================================
// Cause (TS 38.413 section 9.3.1.2)
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CauseGroup {
    RadioNetwork,
    Transport,
    Nas,
    Protocol,
    Misc,
}

const RADIO_NETWORK_ROOT: &[&str] = &[
    "unspecified",
    "txnrelocoverall-expiry",
    "successful-handover",
    "release-due-to-ngran-generated-reason",
    "release-due-to-5gc-generated-reason",
    "handover-cancelled",
    "partial-handover",
    "ho-failure-in-target-5GC-ngran-node-or-target-system",
    "ho-target-not-allowed",
    "tngrelocoverall-expiry",
    "tngrelocprep-expiry",
    "cell-not-available",
    "unknown-targetID",
    "no-radio-resources-available-in-target-cell",
    "unknown-local-UE-NGAP-ID",
    "inconsistent-remote-UE-NGAP-ID",
    "handover-desirable-for-radio-reason",
    "time-critical-handover",
    "resource-optimisation-handover",
    "reduce-load-in-serving-cell",
    "user-inactivity",
    "radio-connection-with-ue-lost",
    "radio-resources-not-available",
    "invalid-qos-combination",
    "failure-in-radio-interface-procedure",
    "interaction-with-other-procedure",
    "unknown-PDU-session-ID",
    "unkown-qos-flow-ID",
    "multiple-PDU-session-ID-instances",
    "multiple-qos-flow-ID-instances",
    "encryption-and-or-integrity-protection-algorithms-not-supported",
    "ng-intra-system-handover-triggered",
    "ng-inter-system-handover-triggered",
    "xn-handover-triggered",
    "not-supported-5QI-value",
    "ue-context-transfer",
    "ims-voice-eps-fallback-or-rat-fallback-triggered",
    "up-integrity-protection-not-possible",
    "up-confidentiality-protection-not-possible",
    "slice-not-supported",
    "ue-in-rrc-inactive-state-not-reachable",
    "redirection",
    "resources-not-available-for-the-slice",
    "ue-max-integrity-protected-data-rate-reason",
    "release-due-to-cn-detected-mobility",
];
const RADIO_NETWORK_EXT: &[&str] = &[
    "n26-interface-not-available",
    "release-due-to-pre-emption",
    "multiple-location-reporting-reference-ID-instances",
    "rsn-not-available-for-the-up",
    "npn-access-denied",
    "cag-only-access-denied",
    "insufficient-ue-capabilities",
    "redcap-ue-not-supported",
    "unknown-MBS-Session-ID",
    "indicated-MBS-session-area-information-not-served-by-the-gNB",
    "inconsistent-slice-info-for-the-session",
    "misaligned-association-for-multicast-unicast",
    "eredcap-ue-not-supported",
    "two-rx-xr-ue-not-supported",
    "aerial-ue-flight-information-reporting-initiation-failure",
    "unknown-RAN-AIoT-Device-NGAP-ID",
    "requested-AIoT-service-area-information-not-served-by-the-gNB",
    "unknown-AIoT-session",
    "aiot-device-not-reachable",
    "multiple-AIoT-session-ID-instances",
];
const TRANSPORT_ROOT: &[&str] = &["transport-resource-unavailable", "unspecified"];
const NAS_ROOT: &[&str] = &[
    "normal-release",
    "authentication-failure",
    "deregister",
    "unspecified",
];
const NAS_EXT: &[&str] = &[
    "uE-not-in-PLMN-serving-area",
    "mobile-IAB-not-authorized",
    "iAB-not-authorized",
    "no-aiot-NAS-response",
];
const PROTOCOL_ROOT: &[&str] = &[
    "transfer-syntax-error",
    "abstract-syntax-error-reject",
    "abstract-syntax-error-ignore-and-notify",
    "message-not-compatible-with-receiver-state",
    "semantic-error",
    "abstract-syntax-error-falsely-constructed-message",
    "unspecified",
];
const MISC_ROOT: &[&str] = &[
    "control-processing-overload",
    "not-enough-user-plane-processing-resources",
    "hardware-failure",
    "om-intervention",
    "unknown-PLMN-or-SNPN",
    "unspecified",
];

pub const RADIO_UNKNOWN_LOCAL_UE_NGAP_ID: u8 = 14;
pub const RADIO_INCONSISTENT_REMOTE_UE_NGAP_ID: u8 = 15;
pub const NAS_NORMAL_RELEASE: u8 = 0;
pub const NAS_UNSPECIFIED: u8 = 3;
pub const PROTOCOL_TRANSFER_SYNTAX_ERROR: u8 = 0;
pub const PROTOCOL_ABSTRACT_SYNTAX_ERROR_REJECT: u8 = 1;
pub const PROTOCOL_MESSAGE_NOT_COMPATIBLE_WITH_RECEIVER_STATE: u8 = 3;
pub const PROTOCOL_SEMANTIC_ERROR: u8 = 4;
pub const PROTOCOL_UNSPECIFIED: u8 = 6;
pub const MISC_CONTROL_PROCESSING_OVERLOAD: u8 = 0;
pub const MISC_HARDWARE_FAILURE: u8 = 2;
pub const MISC_OM_INTERVENTION: u8 = 3;
pub const MISC_UNKNOWN_PLMN: u8 = 4;
pub const MISC_UNSPECIFIED: u8 = 5;

impl CauseGroup {
    const ALL: [CauseGroup; 5] = [
        CauseGroup::RadioNetwork,
        CauseGroup::Transport,
        CauseGroup::Nas,
        CauseGroup::Protocol,
        CauseGroup::Misc,
    ];

    pub fn name(self) -> &'static str {
        match self {
            CauseGroup::RadioNetwork => "radioNetwork",
            CauseGroup::Transport => "transport",
            CauseGroup::Nas => "nas",
            CauseGroup::Protocol => "protocol",
            CauseGroup::Misc => "misc",
        }
    }

    fn tables(self) -> (&'static [&'static str], &'static [&'static str]) {
        match self {
            CauseGroup::RadioNetwork => (RADIO_NETWORK_ROOT, RADIO_NETWORK_EXT),
            CauseGroup::Transport => (TRANSPORT_ROOT, &[]),
            CauseGroup::Nas => (NAS_ROOT, NAS_EXT),
            CauseGroup::Protocol => (PROTOCOL_ROOT, &[]),
            CauseGroup::Misc => (MISC_ROOT, &[]),
        }
    }
}

/// An NGAP Cause: a group and an index in that group's root (or, when `extended`, its extension
/// list).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cause {
    pub group: CauseGroup,
    pub extended: bool,
    pub index: u8,
}

fn normalize(s: &str) -> String {
    s.trim().to_ascii_lowercase().replace('_', "-")
}

impl Cause {
    pub fn protocol(index: u8) -> Self {
        Cause {
            group: CauseGroup::Protocol,
            extended: false,
            index,
        }
    }
    pub fn misc(index: u8) -> Self {
        Cause {
            group: CauseGroup::Misc,
            extended: false,
            index,
        }
    }
    pub fn radio(index: u8) -> Self {
        Cause {
            group: CauseGroup::RadioNetwork,
            extended: false,
            index,
        }
    }
    pub fn nas(index: u8) -> Self {
        Cause {
            group: CauseGroup::Nas,
            extended: false,
            index,
        }
    }

    pub fn value_name(&self) -> String {
        let (root, ext) = self.group.tables();
        let table = if self.extended { ext } else { root };
        table
            .get(self.index as usize)
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("{}{}", if self.extended { "ext-" } else { "" }, self.index))
    }

    /// `group/value`, the form logs and errors use.
    pub fn label(&self) -> String {
        format!("{}/{}", self.group.name(), self.value_name())
    }

    pub fn to_json(&self) -> Value {
        json!({"group": self.group.name(), "value": self.value_name()})
    }

    /// Accepts `{"group": "misc", "value": "unknown-PLMN-or-SNPN"}` or `"misc/unknown-PLMN-or-SNPN"`.
    /// Names match case-insensitively and with `_` for `-`. A bare value name is accepted when it
    /// is unambiguous across the groups.
    pub fn from_json(v: &Value) -> EncodeResult<Cause> {
        let (group, value) = match v {
            Value::String(s) => match s.split_once('/') {
                Some((g, val)) => (Some(g.to_string()), val.to_string()),
                None => (None, s.clone()),
            },
            Value::Object(m) => (
                m.get("group").and_then(Value::as_str).map(str::to_string),
                m.get("value")
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .ok_or_else(|| EncodeError("cause.value must be a string".into()))?,
            ),
            _ => return enc_err("cause must be \"group/value\" or {\"group\", \"value\"}"),
        };
        let wanted = normalize(&value);
        let groups: Vec<CauseGroup> = match &group {
            Some(g) => {
                let g = normalize(g).replace('-', "");
                let found = CauseGroup::ALL
                    .iter()
                    .copied()
                    .find(|c| c.name().to_ascii_lowercase() == g);
                match found {
                    Some(c) => vec![c],
                    None => {
                        return enc_err(format!(
                        "cause group {g:?} is not one of radioNetwork, transport, nas, protocol, misc"
                    ))
                    }
                }
            }
            None => CauseGroup::ALL.to_vec(),
        };
        let mut hits = Vec::new();
        for g in groups {
            let (root, ext) = g.tables();
            for (i, name) in root.iter().enumerate() {
                if normalize(name) == wanted {
                    hits.push(Cause {
                        group: g,
                        extended: false,
                        index: i as u8,
                    });
                }
            }
            for (i, name) in ext.iter().enumerate() {
                if normalize(name) == wanted {
                    hits.push(Cause {
                        group: g,
                        extended: true,
                        index: i as u8,
                    });
                }
            }
        }
        match hits.len() {
            1 => Ok(hits[0]),
            0 => enc_err(format!(
                "cause value {value:?} is not defined{}; e.g. misc/unknown-PLMN-or-SNPN, \
                 misc/control-processing-overload, nas/normal-release, \
                 radioNetwork/unspecified, protocol/semantic-error",
                group.map(|g| format!(" in group {g}")).unwrap_or_default()
            )),
            _ => enc_err(format!(
                "cause value {value:?} exists in more than one group; write it as group/value"
            )),
        }
    }

    fn encode(&self, w: &mut Writer) -> EncodeResult<()> {
        let gi = CauseGroup::ALL
            .iter()
            .position(|g| *g == self.group)
            .unwrap_or(0) as u64;
        // Cause ::= CHOICE { radioNetwork, transport, nas, protocol, misc, choice-Extensions }:
        // six root alternatives and no extension marker.
        put_choice(w, gi, 6, "Cause")?;
        let (root, ext) = self.group.tables();
        let limit = if self.extended { ext.len() } else { root.len() };
        if self.index as usize >= limit {
            return enc_err(format!("cause index {} out of range", self.index));
        }
        // Every group's ENUMERATED is extensible.
        w.enumerated(
            self.index as u64,
            self.extended,
            root.len() as u64,
            true,
            "Cause",
        )?;
        Ok(())
    }

    fn decode(r: &mut Reader) -> CodecResult<Cause> {
        let gi = choice(r, 6, "Cause")? as usize;
        let group = CauseGroup::ALL[gi];
        let (root, _) = group.tables();
        let (extended, index) = r.enumerated(root.len() as u64, true, "Cause value")?;
        Ok(Cause {
            group,
            extended,
            index: index as u8,
        })
    }
}

// ============================================================================
// PDU framing
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PduKind {
    Initiating,
    Successful,
    Unsuccessful,
}

impl PduKind {
    pub fn name(self) -> &'static str {
        match self {
            PduKind::Initiating => "initiatingMessage",
            PduKind::Successful => "successfulOutcome",
            PduKind::Unsuccessful => "unsuccessfulOutcome",
        }
    }
    fn index(self) -> u64 {
        match self {
            PduKind::Initiating => 0,
            PduKind::Successful => 1,
            PduKind::Unsuccessful => 2,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Criticality {
    Reject,
    Ignore,
    Notify,
}

impl Criticality {
    fn from_index(i: u64) -> Criticality {
        match i {
            0 => Criticality::Reject,
            1 => Criticality::Ignore,
            _ => Criticality::Notify,
        }
    }
    fn index(self) -> u64 {
        match self {
            Criticality::Reject => 0,
            Criticality::Ignore => 1,
            Criticality::Notify => 2,
        }
    }
    pub fn name(self) -> &'static str {
        match self {
            Criticality::Reject => "reject",
            Criticality::Ignore => "ignore",
            Criticality::Notify => "notify",
        }
    }
}

/// One `ProtocolIE-Field`, its value still an encoded open type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ie {
    pub id: u16,
    pub criticality: Criticality,
    pub value: Vec<u8>,
}

impl Ie {
    pub fn new(id: u16, criticality: Criticality, value: Vec<u8>) -> Self {
        Ie {
            id,
            criticality,
            value,
        }
    }
}

/// One NGAP PDU with its IEs framed but not interpreted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pdu {
    pub kind: PduKind,
    pub procedure_code: u8,
    pub criticality: Criticality,
    pub ies: Vec<Ie>,
}

impl Pdu {
    pub fn new(kind: PduKind, procedure_code: u8, criticality: Criticality, ies: Vec<Ie>) -> Self {
        Pdu {
            kind,
            procedure_code,
            criticality,
            ies,
        }
    }

    pub fn ie(&self, id: u16) -> Option<&Ie> {
        self.ies.iter().find(|ie| ie.id == id)
    }

    /// `"NGSetup initiatingMessage"`, or the code when NetGet has no name for it.
    pub fn label(&self) -> String {
        match procedure_name(self.procedure_code) {
            Some(n) => format!("{n} {}", self.kind.name()),
            None => format!("procedure {} {}", self.procedure_code, self.kind.name()),
        }
    }

    /// The ids of IEs NetGet did not interpret for this message, for events.
    pub fn uninterpreted_ies(&self, interpreted: &[u16]) -> Vec<Value> {
        self.ies
            .iter()
            .filter(|ie| !interpreted.contains(&ie.id))
            .map(|ie| {
                json!({
                    "id": ie.id,
                    "name": ie_name(ie.id),
                    "criticality": ie.criticality.name(),
                    "length": ie.value.len(),
                })
            })
            .collect()
    }

    /// The mandatory IE `id`, or the abstract-syntax refusal 38.413 section 10.3.5 prescribes.
    pub fn require(&self, id: u16) -> CodecResult<&Ie> {
        self.ie(id).ok_or_else(|| {
            abstract_reject(format!(
                "{} is missing mandatory IE {} ({})",
                self.label(),
                id,
                ie_name(id).unwrap_or("?")
            ))
        })
    }
}

/// Decode the outer structure of one NGAP PDU.
pub fn decode_pdu(bytes: &[u8]) -> CodecResult<Pdu> {
    if bytes.is_empty() {
        return Err(AperError("empty PDU".into()).into());
    }
    if bytes.len() > MAX_PDU_LEN {
        return Err(AperError(format!(
            "PDU of {} octets exceeds {MAX_PDU_LEN}",
            bytes.len()
        ))
        .into());
    }
    let mut r = Reader::new(bytes);
    if r.extension_bit("NGAP-PDU")? {
        return Err(AperError("NGAP-PDU choice extension".into()).into());
    }
    let kind = match r.constrained(0, 2, "NGAP-PDU")? {
        0 => PduKind::Initiating,
        1 => PduKind::Successful,
        _ => PduKind::Unsuccessful,
    };
    let procedure_code = r.constrained(0, 255, "procedureCode")? as u8;
    let criticality = Criticality::from_index(r.constrained(0, 2, "criticality")?);
    let content = r.open_type("message value")?;
    if !r.at_end() {
        return Err(AperError("octets after the PDU".into()).into());
    }

    let mut c = Reader::new(content);
    let extended = c.extension_bit("message")?;
    let count = c.size(0, 65_535, "ProtocolIE-Container")?;
    if count > MAX_IES {
        return Err(AperError(format!(
            "{count} IEs in one message exceeds the bound of {MAX_IES}"
        ))
        .into());
    }
    let mut ies = Vec::with_capacity(count);
    for _ in 0..count {
        let id = c.constrained(0, 65_535, "ProtocolIE-ID")? as u16;
        let crit = Criticality::from_index(c.constrained(0, 2, "IE criticality")?);
        let value = c.open_type("IE value")?.to_vec();
        if ies.iter().any(|ie: &Ie| ie.id == id) {
            // 38.413 section 10.3.6: an IE appearing more than once is a falsely constructed
            // message.
            return Err(ProtocolError {
                cause: Cause::protocol(5),
                detail: format!("IE {id} appears more than once"),
            });
        }
        ies.push(Ie::new(id, crit, value));
    }
    if extended {
        c.skip_extension_additions("message extension additions")?;
    }
    Ok(Pdu {
        kind,
        procedure_code,
        criticality,
        ies,
    })
}

/// Encode one NGAP PDU.
pub fn encode_pdu(pdu: &Pdu) -> EncodeResult<Vec<u8>> {
    if pdu.ies.len() > MAX_IES {
        return enc_err(format!("{} IEs exceeds {MAX_IES}", pdu.ies.len()));
    }
    let mut c = Writer::new();
    c.bit(false);
    c.size(pdu.ies.len(), 0, 65_535, "ProtocolIE-Container")?;
    for ie in &pdu.ies {
        c.constrained(ie.id as u64, 0, 65_535, "ProtocolIE-ID")?;
        c.constrained(ie.criticality.index(), 0, 2, "IE criticality")?;
        c.open_type(&ie.value, "IE value")?;
    }
    let content = c.finish();

    let mut w = Writer::new();
    w.bit(false);
    w.constrained(pdu.kind.index(), 0, 2, "NGAP-PDU")?;
    w.constrained(pdu.procedure_code as u64, 0, 255, "procedureCode")?;
    w.constrained(pdu.criticality.index(), 0, 2, "criticality")?;
    w.open_type(&content, "message value")?;
    let out = w.finish();
    if out.len() > MAX_PDU_LEN {
        return enc_err(format!("PDU of {} octets exceeds {MAX_PDU_LEN}", out.len()));
    }
    Ok(out)
}

/// The procedure code and kind of an encoded PDU, read without decoding the rest.
pub fn peek(bytes: &[u8]) -> Option<(PduKind, u8)> {
    let mut r = Reader::new(bytes);
    if r.extension_bit("NGAP-PDU").ok()? {
        return None;
    }
    let kind = match r.constrained(0, 2, "NGAP-PDU").ok()? {
        0 => PduKind::Initiating,
        1 => PduKind::Successful,
        _ => PduKind::Unsuccessful,
    };
    let code = r.constrained(0, 255, "procedureCode").ok()? as u8;
    Some((kind, code))
}

/// True when the PDU is UE-associated signalling — it carries an AMF or RAN UE NGAP ID — which
/// TS 38.412 section 7 sends on a non-zero SCTP stream. Non-UE-associated signalling (NG Setup,
/// NG Reset, a UE-less Error Indication) uses stream 0.
pub fn is_ue_associated(bytes: &[u8]) -> bool {
    match decode_pdu(bytes) {
        Ok(p) => p.ies.iter().any(|ie| {
            matches!(
                ie.id,
                IE_AMF_UE_NGAP_ID | IE_RAN_UE_NGAP_ID | IE_UE_NGAP_IDS
            )
        }),
        Err(_) => false,
    }
}

// ============================================================================
// A per-decode budget on SEQUENCE OF elements
// ============================================================================

/// Counts list elements across one PDU so nested lists cannot multiply into an unbounded event.
pub struct Budget(usize);

impl Default for Budget {
    fn default() -> Self {
        Budget(MAX_LIST_ITEMS)
    }
}

impl Budget {
    fn take(&mut self, n: usize, what: &str) -> CodecResult<()> {
        if n > self.0 {
            return Err(AperError(format!(
                "{what}: list elements in one PDU exceed the bound of {MAX_LIST_ITEMS}"
            ))
            .into());
        }
        self.0 -= n;
        Ok(())
    }
}

// ============================================================================
// Primitive IEs
// ============================================================================

/// A PLMN identity, three TBCD octets (TS 38.413 section 9.3.3.5, TS 24.008 figure 10.5.13).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Plmn {
    pub mcc: String,
    pub mnc: String,
}

impl Plmn {
    pub fn decode_octets(b: &[u8]) -> CodecResult<Plmn> {
        if b.len() != 3 {
            return Err(semantic("PLMN identity is not three octets"));
        }
        let d = [
            b[0] & 0x0F,
            b[0] >> 4,
            b[1] & 0x0F,
            b[1] >> 4,
            b[2] & 0x0F,
            b[2] >> 4,
        ];
        let digit = |x: u8| -> CodecResult<char> {
            if x > 9 {
                Err(semantic("PLMN identity has a non-decimal digit"))
            } else {
                Ok((b'0' + x) as char)
            }
        };
        let mcc: String = [digit(d[0])?, digit(d[1])?, digit(d[2])?].iter().collect();
        let mnc: String = if d[3] == 0xF {
            [digit(d[4])?, digit(d[5])?].iter().collect()
        } else {
            [digit(d[4])?, digit(d[5])?, digit(d[3])?].iter().collect()
        };
        Ok(Plmn { mcc, mnc })
    }

    pub fn octets(&self) -> [u8; 3] {
        let m: Vec<u8> = self.mcc.bytes().map(|c| c - b'0').collect();
        let n: Vec<u8> = self.mnc.bytes().map(|c| c - b'0').collect();
        let mnc3 = if n.len() == 3 { n[2] } else { 0xF };
        [m[1] << 4 | m[0], mnc3 << 4 | m[2], n[1] << 4 | n[0]]
    }

    pub fn to_json(&self) -> Value {
        json!({"mcc": self.mcc, "mnc": self.mnc})
    }

    /// `{"mcc": "001", "mnc": "01"}`, or a string `"001-01"` / `"00101"` (five digits is a
    /// two-digit MNC, six a three-digit one).
    pub fn from_json(v: &Value) -> EncodeResult<Plmn> {
        let (mcc, mnc) = match v {
            Value::Object(m) => (
                json_digits(m.get("mcc"), "plmn.mcc")?,
                json_digits(m.get("mnc"), "plmn.mnc")?,
            ),
            Value::String(s) => {
                let s = s.trim();
                if let Some((a, b)) = s.split_once(['-', '/']) {
                    (a.to_string(), b.to_string())
                } else if s.len() == 5 || s.len() == 6 {
                    (s[..3].to_string(), s[3..].to_string())
                } else {
                    return enc_err(format!(
                        "plmn {s:?} must be \"MCC-MNC\" or {{\"mcc\", \"mnc\"}}"
                    ));
                }
            }
            _ => return enc_err("plmn must be {\"mcc\": \"001\", \"mnc\": \"01\"}"),
        };
        if mcc.len() != 3 || !mcc.bytes().all(|c| c.is_ascii_digit()) {
            return enc_err(format!("mcc {mcc:?} must be three decimal digits"));
        }
        if !(2..=3).contains(&mnc.len()) || !mnc.bytes().all(|c| c.is_ascii_digit()) {
            return enc_err(format!("mnc {mnc:?} must be two or three decimal digits"));
        }
        Ok(Plmn { mcc, mnc })
    }

    fn decode(r: &mut Reader) -> CodecResult<Plmn> {
        let b = r.fixed_octets(3, "PLMNIdentity")?;
        Plmn::decode_octets(&b)
    }

    fn encode(&self, w: &mut Writer) {
        w.fixed_octets(&self.octets());
    }
}

fn json_digits(v: Option<&Value>, what: &str) -> EncodeResult<String> {
    match v {
        Some(Value::String(s)) => Ok(s.trim().to_string()),
        Some(Value::Number(n)) => enc_err(format!(
            "{what} must be a string so leading zeros survive (got {n})"
        )),
        _ => enc_err(format!("{what} is required")),
    }
}

pub fn json_u64(v: &Value, field: &str, max: u64) -> EncodeResult<u64> {
    let n = match v.get(field) {
        Some(Value::Number(n)) => n
            .as_u64()
            .ok_or_else(|| EncodeError(format!("{field} must be a non-negative integer")))?,
        Some(Value::String(s)) => {
            let s = s.trim();
            if let Some(hex) = s.strip_prefix("0x") {
                u64::from_str_radix(hex, 16)
                    .map_err(|_| EncodeError(format!("{field} {s:?} is not a number")))?
            } else {
                s.parse()
                    .map_err(|_| EncodeError(format!("{field} {s:?} is not a number")))?
            }
        }
        None | Some(Value::Null) => return enc_err(format!("{field} is required")),
        _ => return enc_err(format!("{field} must be a number")),
    };
    if n > max {
        return enc_err(format!("{field} {n} is above its maximum {max}"));
    }
    Ok(n)
}

pub fn json_opt_u64(v: &Value, field: &str, max: u64) -> EncodeResult<Option<u64>> {
    match v.get(field) {
        None | Some(Value::Null) => Ok(None),
        Some(_) => json_u64(v, field, max).map(Some),
    }
}

fn opt_extension_container(r: &mut Reader, present: bool, budget: &mut Budget) -> CodecResult<()> {
    if present {
        let n = r.size(1, 65_535, "ProtocolExtensionContainer")?;
        budget.take(n, "ProtocolExtensionContainer")?;
        for _ in 0..n {
            r.constrained(0, 65_535, "ProtocolExtensionID")?;
            r.constrained(0, 2, "extension criticality")?;
            r.open_type("extension value")?;
        }
    }
    Ok(())
}

fn finish_sequence(r: &mut Reader, extended: bool) -> CodecResult<()> {
    if extended {
        r.skip_extension_additions("extension additions")?;
    }
    Ok(())
}

/// An NGAP CHOICE. 38.413 writes its CHOICEs with a final `choice-Extensions` *root*
/// alternative (a ProtocolIE-SingleContainer) instead of an extension marker, so there is no
/// extension bit: the index is a constrained whole number over every alternative including that
/// one. `alternatives` counts `choice-Extensions`. Selecting it is refused here; callers that can
/// carry on without it check for [`CHOICE_EXTENSIONS`] first.
fn choice(r: &mut Reader, alternatives: u64, what: &str) -> CodecResult<u64> {
    let i = r.constrained(0, alternatives - 1, what)?;
    if i == alternatives - 1 {
        return Err(semantic(format!(
            "{what} selects its choice-Extensions alternative, which NetGet does not decode"
        )));
    }
    Ok(i)
}

/// Marker for the `choice-Extensions` index of a CHOICE with `alternatives` alternatives.
pub const CHOICE_EXTENSIONS: &str = "choice-Extensions";

fn put_choice(w: &mut Writer, index: u64, alternatives: u64, what: &str) -> EncodeResult<()> {
    Ok(w.constrained(index, 0, alternatives - 1, what)?)
}

/// Decode an IE value with `f`, requiring it to consume the whole open type.
fn decode_ie<T>(ie: &Ie, f: impl FnOnce(&mut Reader) -> CodecResult<T>) -> CodecResult<T> {
    let mut r = Reader::new(&ie.value);
    let v = f(&mut r)?;
    if !r.at_end() {
        return Err(AperError(format!(
            "IE {} ({}) has octets after its value",
            ie.id,
            ie_name(ie.id).unwrap_or("?")
        ))
        .into());
    }
    Ok(v)
}

fn encode_ie(
    id: u16,
    crit: Criticality,
    f: impl FnOnce(&mut Writer) -> EncodeResult<()>,
) -> EncodeResult<Ie> {
    let mut w = Writer::new();
    f(&mut w)?;
    Ok(Ie::new(id, crit, w.finish()))
}

pub fn decode_amf_ue_ngap_id(ie: &Ie) -> CodecResult<u64> {
    decode_ie(ie, |r| {
        Ok(r.constrained(0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?)
    })
}

pub fn decode_ran_ue_ngap_id(ie: &Ie) -> CodecResult<u64> {
    decode_ie(ie, |r| {
        Ok(r.constrained(0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?)
    })
}

pub fn amf_ue_ngap_id_ie(id: u64, crit: Criticality) -> EncodeResult<Ie> {
    encode_ie(IE_AMF_UE_NGAP_ID, crit, |w| {
        Ok(w.constrained(id, 0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?)
    })
}

pub fn ran_ue_ngap_id_ie(id: u64, crit: Criticality) -> EncodeResult<Ie> {
    encode_ie(IE_RAN_UE_NGAP_ID, crit, |w| {
        Ok(w.constrained(id, 0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?)
    })
}

pub fn decode_nas_pdu(ie: &Ie) -> CodecResult<Vec<u8>> {
    decode_ie(ie, |r| {
        Ok(r.octet_string(MAX_NAS_PDU_LEN, "NAS-PDU")?.to_vec())
    })
}

pub fn nas_pdu_ie(nas: &[u8]) -> EncodeResult<Ie> {
    if nas.is_empty() || nas.len() > MAX_NAS_PDU_LEN {
        return enc_err(format!(
            "NAS-PDU of {} octets is outside 1..{MAX_NAS_PDU_LEN}",
            nas.len()
        ));
    }
    encode_ie(IE_NAS_PDU, Criticality::Reject, |w| {
        Ok(w.octet_string(nas, "NAS-PDU")?)
    })
}

pub fn decode_cause(ie: &Ie) -> CodecResult<Cause> {
    decode_ie(ie, Cause::decode)
}

pub fn cause_ie(cause: &Cause, crit: Criticality) -> EncodeResult<Ie> {
    encode_ie(IE_CAUSE, crit, |w| cause.encode(w))
}

const TIME_TO_WAIT: &[&str] = &["v1s", "v2s", "v5s", "v10s", "v20s", "v60s"];
const PAGING_DRX: &[&str] = &["v32", "v64", "v128", "v256"];
const RRC_CAUSE_ROOT: &[&str] = &[
    "emergency",
    "highPriorityAccess",
    "mt-Access",
    "mo-Signalling",
    "mo-Data",
    "mo-VoiceCall",
    "mo-VideoCall",
    "mo-SMS",
    "mps-PriorityAccess",
    "mcs-PriorityAccess",
];
const RRC_CAUSE_EXT: &[&str] = &["notAvailable", "mo-ExceptionData"];

fn enum_index(table: &[&str], v: &str, what: &str) -> EncodeResult<u64> {
    let want = normalize(v);
    table
        .iter()
        .position(|n| normalize(n) == want)
        .map(|i| i as u64)
        .ok_or_else(|| EncodeError(format!("{what} {v:?} is not one of {}", table.join(", "))))
}

pub fn time_to_wait_ie(v: &str) -> EncodeResult<Ie> {
    // Seconds are accepted as well as the ASN.1 names: "10" or "10s" mean v10s.
    let name = if v.starts_with('v') {
        v.to_string()
    } else {
        format!("v{}s", v.trim_end_matches('s'))
    };
    let i = enum_index(TIME_TO_WAIT, &name, "time_to_wait")?;
    encode_ie(IE_TIME_TO_WAIT, Criticality::Ignore, |w| {
        Ok(w.enumerated(i, false, 6, true, "TimeToWait")?)
    })
}

pub fn decode_time_to_wait(ie: &Ie) -> CodecResult<String> {
    decode_ie(ie, |r| {
        let (ext, i) = r.enumerated(6, true, "TimeToWait")?;
        Ok(if ext {
            format!("ext-{i}")
        } else {
            TIME_TO_WAIT[i as usize].to_string()
        })
    })
}

fn decode_paging_drx(ie: &Ie) -> CodecResult<String> {
    decode_ie(ie, |r| {
        let (ext, i) = r.enumerated(4, true, "PagingDRX")?;
        Ok(if ext {
            format!("ext-{i}")
        } else {
            PAGING_DRX[i as usize].to_string()
        })
    })
}

fn decode_rrc_cause(ie: &Ie) -> CodecResult<String> {
    decode_ie(ie, |r| {
        let (ext, i) = r.enumerated(10, true, "RRCEstablishmentCause")?;
        let table = if ext { RRC_CAUSE_EXT } else { RRC_CAUSE_ROOT };
        Ok(table
            .get(i as usize)
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("ext-{i}")))
    })
}

fn rrc_cause_ie(v: &str) -> EncodeResult<Ie> {
    let (ext, i) = match enum_index(RRC_CAUSE_ROOT, v, "rrc_establishment_cause") {
        Ok(i) => (false, i),
        Err(_) => (
            true,
            enum_index(RRC_CAUSE_EXT, v, "rrc_establishment_cause").map_err(|_| {
                EncodeError(format!(
                    "rrc_establishment_cause {v:?} is not one of {}, {}",
                    RRC_CAUSE_ROOT.join(", "),
                    RRC_CAUSE_EXT.join(", ")
                ))
            })?,
        ),
    };
    encode_ie(IE_RRC_ESTABLISHMENT_CAUSE, Criticality::Ignore, |w| {
        Ok(w.enumerated(i, ext, 10, true, "RRCEstablishmentCause")?)
    })
}

fn tac_octets(tac: u64) -> [u8; 3] {
    [(tac >> 16) as u8, (tac >> 8) as u8, tac as u8]
}

fn decode_tac(r: &mut Reader) -> CodecResult<u64> {
    let b = r.fixed_octets(3, "TAC")?;
    Ok(((b[0] as u64) << 16) | ((b[1] as u64) << 8) | b[2] as u64)
}

// ============================================================================
// S-NSSAI and slice lists
// ============================================================================

fn decode_snssai(r: &mut Reader, budget: &mut Budget) -> CodecResult<Value> {
    let ext = r.extension_bit("S-NSSAI")?;
    let has_sd = r.bit("S-NSSAI")?;
    let has_ext = r.bit("S-NSSAI")?;
    let sst = r.fixed_octets(1, "SST")?[0];
    let mut v = json!({"sst": sst});
    if has_sd {
        let sd = r.fixed_octets(3, "SD")?;
        v["sd"] = json!(hex::encode(sd));
    }
    opt_extension_container(r, has_ext, budget)?;
    finish_sequence(r, ext)?;
    Ok(v)
}

/// `{"sst": 1, "sd": "010203"}`; `sd` may also be a number.
fn encode_snssai(w: &mut Writer, v: &Value) -> EncodeResult<()> {
    let sst = json_u64(v, "sst", 255)?;
    let sd = match v.get("sd") {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) => {
            let s = s.trim().trim_start_matches("0x");
            if s.len() != 6 {
                return enc_err(format!("sd {s:?} must be six hex digits"));
            }
            Some(
                u32::from_str_radix(s, 16)
                    .map_err(|_| EncodeError(format!("sd {s:?} is not hex")))?,
            )
        }
        Some(Value::Number(_)) => Some(json_u64(v, "sd", 0xFF_FFFF)? as u32),
        Some(_) => return enc_err("sd must be six hex digits"),
    };
    w.bit(false);
    w.bit(sd.is_some());
    w.bit(false);
    w.fixed_octets(&[sst as u8]);
    if let Some(sd) = sd {
        w.fixed_octets(&[(sd >> 16) as u8, (sd >> 8) as u8, sd as u8]);
    }
    Ok(())
}

fn decode_slice_list(r: &mut Reader, budget: &mut Budget) -> CodecResult<Vec<Value>> {
    let n = r.size(1, 1024, "SliceSupportList")?;
    budget.take(n, "SliceSupportList")?;
    let mut out = Vec::with_capacity(n);
    for _ in 0..n {
        let ext = r.extension_bit("SliceSupportItem")?;
        let has_ext = r.bit("SliceSupportItem")?;
        out.push(decode_snssai(r, budget)?);
        opt_extension_container(r, has_ext, budget)?;
        finish_sequence(r, ext)?;
    }
    Ok(out)
}

fn json_list<'a>(v: &'a Value, field: &str) -> EncodeResult<&'a Vec<Value>> {
    v.get(field)
        .and_then(Value::as_array)
        .ok_or_else(|| EncodeError(format!("{field} must be a list")))
}

fn encode_slice_list(w: &mut Writer, slices: &[Value]) -> EncodeResult<()> {
    w.size(slices.len(), 1, 1024, "slices")?;
    for s in slices {
        w.bit(false);
        w.bit(false);
        encode_snssai(w, s)?;
    }
    Ok(())
}

// ============================================================================
// NG Setup IEs
// ============================================================================

/// GlobalRANNodeID — gNB form decoded; ng-eNB and N3IWF forms named only.
pub fn decode_global_ran_node_id(ie: &Ie, budget: &mut Budget) -> CodecResult<Value> {
    decode_ie(ie, |r| match choice(r, 4, "GlobalRANNodeID")? {
        0 => {
            let ext = r.extension_bit("GlobalGNB-ID")?;
            let has_ext = r.bit("GlobalGNB-ID")?;
            let plmn = Plmn::decode(r)?;
            choice(r, 2, "GNB-ID")?;
            let (id, bits) = r.varying_bits(22, 32, "gNB-ID")?;
            opt_extension_container(r, has_ext, budget)?;
            finish_sequence(r, ext)?;
            Ok(json!({"type": "gnb", "plmn": plmn.to_json(), "gnb_id": id, "gnb_id_bits": bits}))
        }
        1 => Err(semantic(
            "an ng-eNB GlobalRANNodeID; NetGet's AMF serves gNBs",
        )),
        _ => Err(semantic(
            "an N3IWF GlobalRANNodeID; NetGet's AMF serves gNBs",
        )),
    })
}

pub fn global_gnb_id_ie(plmn: &Plmn, gnb_id: u64, bits: u32) -> EncodeResult<Ie> {
    encode_ie(IE_GLOBAL_RAN_NODE_ID, Criticality::Reject, |w| {
        put_choice(w, 0, 4, "GlobalRANNodeID")?;
        w.bit(false);
        w.bit(false);
        plmn.encode(w);
        put_choice(w, 0, 2, "GNB-ID")?;
        w.varying_bits(gnb_id, bits, 22, 32, "gnb_id")?;
        Ok(())
    })
}

pub fn decode_name(ie: &Ie) -> CodecResult<String> {
    decode_ie(ie, |r| Ok(r.printable_string(1, 150, "name")?))
}

pub fn name_ie(id: u16, crit: Criticality, name: &str) -> EncodeResult<Ie> {
    encode_ie(id, crit, |w| Ok(w.printable_string(name, 1, 150, "name")?))
}

pub fn decode_supported_ta_list(ie: &Ie, budget: &mut Budget) -> CodecResult<Vec<Value>> {
    decode_ie(ie, |r| {
        let n = r.size(1, 256, "SupportedTAList")?;
        budget.take(n, "SupportedTAList")?;
        let mut out = Vec::with_capacity(n);
        for _ in 0..n {
            let ext = r.extension_bit("SupportedTAItem")?;
            let has_ext = r.bit("SupportedTAItem")?;
            let tac = decode_tac(r)?;
            let m = r.size(1, 12, "BroadcastPLMNList")?;
            budget.take(m, "BroadcastPLMNList")?;
            let mut plmns = Vec::with_capacity(m);
            for _ in 0..m {
                let bext = r.extension_bit("BroadcastPLMNItem")?;
                let bhas = r.bit("BroadcastPLMNItem")?;
                let plmn = Plmn::decode(r)?;
                let slices = decode_slice_list(r, budget)?;
                opt_extension_container(r, bhas, budget)?;
                finish_sequence(r, bext)?;
                plmns.push(json!({"plmn": plmn.to_json(), "slices": slices}));
            }
            opt_extension_container(r, has_ext, budget)?;
            finish_sequence(r, ext)?;
            out.push(json!({"tac": tac, "broadcast_plmns": plmns}));
        }
        Ok(out)
    })
}

/// `[{"tac": 1, "broadcast_plmns": [{"plmn": {...}, "slices": [{"sst": 1}]}]}]`
pub fn supported_ta_list_ie(list: &[Value]) -> EncodeResult<Ie> {
    encode_ie(IE_SUPPORTED_TA_LIST, Criticality::Reject, |w| {
        w.size(list.len(), 1, 256, "supported_ta_list")?;
        for ta in list {
            let tac = json_u64(ta, "tac", 0xFF_FFFF)?;
            let plmns = json_list(ta, "broadcast_plmns")?;
            w.bit(false);
            w.bit(false);
            w.fixed_octets(&tac_octets(tac));
            w.size(plmns.len(), 1, 12, "broadcast_plmns")?;
            for p in plmns {
                let plmn = Plmn::from_json(p.get("plmn").unwrap_or(&Value::Null))?;
                w.bit(false);
                w.bit(false);
                plmn.encode(w);
                encode_slice_list(w, json_list(p, "slices")?)?;
            }
        }
        Ok(())
    })
}

pub fn paging_drx_ie(v: &str) -> EncodeResult<Ie> {
    let i = enum_index(PAGING_DRX, v, "default_paging_drx")?;
    encode_ie(IE_DEFAULT_PAGING_DRX, Criticality::Ignore, |w| {
        Ok(w.enumerated(i, false, 4, true, "PagingDRX")?)
    })
}

pub fn decode_served_guami_list(ie: &Ie, budget: &mut Budget) -> CodecResult<Vec<Value>> {
    decode_ie(ie, |r| {
        let n = r.size(1, 256, "ServedGUAMIList")?;
        budget.take(n, "ServedGUAMIList")?;
        let mut out = Vec::with_capacity(n);
        for _ in 0..n {
            let ext = r.extension_bit("ServedGUAMIItem")?;
            let has_backup = r.bit("ServedGUAMIItem")?;
            let has_ext = r.bit("ServedGUAMIItem")?;
            let mut g = decode_guami(r, budget)?;
            if has_backup {
                g["backup_amf_name"] = json!(r.printable_string(1, 150, "backupAMFName")?);
            }
            opt_extension_container(r, has_ext, budget)?;
            finish_sequence(r, ext)?;
            out.push(g);
        }
        Ok(out)
    })
}

fn decode_guami(r: &mut Reader, budget: &mut Budget) -> CodecResult<Value> {
    let ext = r.extension_bit("GUAMI")?;
    let has_ext = r.bit("GUAMI")?;
    let plmn = Plmn::decode(r)?;
    let region = r.fixed_bits(8, "AMFRegionID")?;
    let set = r.fixed_bits(10, "AMFSetID")?;
    let pointer = r.fixed_bits(6, "AMFPointer")?;
    opt_extension_container(r, has_ext, budget)?;
    finish_sequence(r, ext)?;
    Ok(
        json!({"plmn": plmn.to_json(), "amf_region_id": region, "amf_set_id": set, "amf_pointer": pointer}),
    )
}

/// `[{"plmn": {...}, "amf_region_id": 2, "amf_set_id": 1, "amf_pointer": 0}]`
pub fn served_guami_list_ie(list: &[Value]) -> EncodeResult<Ie> {
    encode_ie(IE_SERVED_GUAMI_LIST, Criticality::Reject, |w| {
        w.size(list.len(), 1, 256, "served_guami")?;
        for g in list {
            let plmn = Plmn::from_json(g.get("plmn").unwrap_or(&Value::Null))?;
            let region = json_u64(g, "amf_region_id", 0xFF)?;
            let set = json_u64(g, "amf_set_id", 0x3FF)?;
            let pointer = json_u64(g, "amf_pointer", 0x3F)?;
            let backup = g.get("backup_amf_name").and_then(Value::as_str);
            w.bit(false);
            w.bit(backup.is_some());
            w.bit(false);
            w.bit(false);
            w.bit(false);
            plmn.encode(w);
            w.fixed_bits(region, 8);
            w.fixed_bits(set, 10);
            w.fixed_bits(pointer, 6);
            if let Some(b) = backup {
                w.printable_string(b, 1, 150, "backup_amf_name")?;
            }
        }
        Ok(())
    })
}

pub fn relative_amf_capacity_ie(c: u64) -> EncodeResult<Ie> {
    encode_ie(IE_RELATIVE_AMF_CAPACITY, Criticality::Ignore, |w| {
        Ok(w.constrained(c, 0, 255, "relative_amf_capacity")?)
    })
}

pub fn decode_relative_amf_capacity(ie: &Ie) -> CodecResult<u64> {
    decode_ie(ie, |r| Ok(r.constrained(0, 255, "RelativeAMFCapacity")?))
}

pub fn decode_plmn_support_list(ie: &Ie, budget: &mut Budget) -> CodecResult<Vec<Value>> {
    decode_ie(ie, |r| {
        let n = r.size(1, 12, "PLMNSupportList")?;
        budget.take(n, "PLMNSupportList")?;
        let mut out = Vec::with_capacity(n);
        for _ in 0..n {
            let ext = r.extension_bit("PLMNSupportItem")?;
            let has_ext = r.bit("PLMNSupportItem")?;
            let plmn = Plmn::decode(r)?;
            let slices = decode_slice_list(r, budget)?;
            opt_extension_container(r, has_ext, budget)?;
            finish_sequence(r, ext)?;
            out.push(json!({"plmn": plmn.to_json(), "slices": slices}));
        }
        Ok(out)
    })
}

/// `[{"plmn": {...}, "slices": [{"sst": 1, "sd": "010203"}]}]`
pub fn plmn_support_list_ie(list: &[Value]) -> EncodeResult<Ie> {
    encode_ie(IE_PLMN_SUPPORT_LIST, Criticality::Reject, |w| {
        w.size(list.len(), 1, 12, "plmn_support")?;
        for p in list {
            let plmn = Plmn::from_json(p.get("plmn").unwrap_or(&Value::Null))?;
            w.bit(false);
            w.bit(false);
            plmn.encode(w);
            encode_slice_list(w, json_list(p, "slices")?)?;
        }
        Ok(())
    })
}

// ============================================================================
// UE-associated IEs
// ============================================================================

/// UserLocationInformation: NR decoded fully, E-UTRA decoded, N3IWF named.
pub fn decode_user_location(ie: &Ie, budget: &mut Budget) -> CodecResult<Value> {
    decode_ie(ie, |r| {
        // EUTRA, NR, N3IWF, choice-Extensions (TNGF / TWIF / W-AGF).
        match r.constrained(0, 3, "UserLocationInformation")? {
            choice @ (0 | 1) => {
                let ext = r.extension_bit("UserLocationInformation")?;
                let has_ts = r.bit("UserLocationInformation")?;
                let has_ext = r.bit("UserLocationInformation")?;
                // E-UTRA-CGI / NR-CGI
                let cext = r.extension_bit("CGI")?;
                let chas = r.bit("CGI")?;
                let cplmn = Plmn::decode(r)?;
                let cell = if choice == 1 {
                    r.fixed_bits(36, "NRCellIdentity")?
                } else {
                    r.fixed_bits(28, "EUTRACellIdentity")?
                };
                opt_extension_container(r, chas, budget)?;
                finish_sequence(r, cext)?;
                // TAI
                let text = r.extension_bit("TAI")?;
                let thas = r.bit("TAI")?;
                let tplmn = Plmn::decode(r)?;
                let tac = decode_tac(r)?;
                opt_extension_container(r, thas, budget)?;
                finish_sequence(r, text)?;
                let mut v = json!({
                    "type": if choice == 1 { "nr" } else { "eutra" },
                    "cgi": {"plmn": cplmn.to_json(), "cell_id": cell},
                    "tai": {"plmn": tplmn.to_json(), "tac": tac},
                });
                if has_ts {
                    let ts = r.fixed_octets(4, "TimeStamp")?;
                    v["time_stamp"] = json!(u32::from_be_bytes([ts[0], ts[1], ts[2], ts[3]]));
                }
                opt_extension_container(r, has_ext, budget)?;
                finish_sequence(r, ext)?;
                Ok(v)
            }
            other => {
                // N3IWF or a choice extension: not interpreted. The open type already bounded it
                // and this value is the whole IE, so the rest is consumed unread.
                while !r.at_end() {
                    r.bits(8, "UserLocationInformation")?;
                }
                Ok(json!({"type": if other == 2 { "n3iwf" } else { CHOICE_EXTENSIONS }}))
            }
        }
    })
}

/// NR user location: `{"cgi": {"plmn", "cell_id"}, "tai": {"plmn", "tac"}}`.
pub fn user_location_nr_ie(v: &Value, crit: Criticality) -> EncodeResult<Ie> {
    let cgi = v
        .get("cgi")
        .ok_or_else(|| EncodeError("user_location.cgi is required".into()))?;
    let tai = v
        .get("tai")
        .ok_or_else(|| EncodeError("user_location.tai is required".into()))?;
    let cplmn = Plmn::from_json(cgi.get("plmn").unwrap_or(&Value::Null))?;
    let cell = json_u64(cgi, "cell_id", (1 << 36) - 1)?;
    let tplmn = Plmn::from_json(tai.get("plmn").unwrap_or(&Value::Null))?;
    let tac = json_u64(tai, "tac", 0xFF_FFFF)?;
    encode_ie(IE_USER_LOCATION_INFORMATION, crit, |w| {
        put_choice(w, 1, 4, "UserLocationInformation")?;
        w.bit(false);
        w.bit(false);
        w.bit(false);
        w.bit(false);
        w.bit(false);
        cplmn.encode(w);
        w.fixed_bits(cell, 36);
        w.bit(false);
        w.bit(false);
        tplmn.encode(w);
        w.fixed_octets(&tac_octets(tac));
        Ok(())
    })
}

fn decode_five_g_s_tmsi(ie: &Ie, budget: &mut Budget) -> CodecResult<Value> {
    decode_ie(ie, |r| {
        let ext = r.extension_bit("FiveG-S-TMSI")?;
        let has_ext = r.bit("FiveG-S-TMSI")?;
        let set = r.fixed_bits(10, "AMFSetID")?;
        let pointer = r.fixed_bits(6, "AMFPointer")?;
        let t = r.fixed_octets(4, "FiveG-TMSI")?;
        opt_extension_container(r, has_ext, budget)?;
        finish_sequence(r, ext)?;
        Ok(json!({"amf_set_id": set, "amf_pointer": pointer,
                  "tmsi": u32::from_be_bytes([t[0], t[1], t[2], t[3]])}))
    })
}

/// UE-NGAP-IDs: `(amf_ue_ngap_id, Some(ran_ue_ngap_id))` for the pair form.
pub fn decode_ue_ngap_ids(ie: &Ie, budget: &mut Budget) -> CodecResult<(u64, Option<u64>)> {
    decode_ie(ie, |r| {
        if choice(r, 3, "UE-NGAP-IDs")? == 0 {
            let ext = r.extension_bit("UE-NGAP-ID-pair")?;
            let has_ext = r.bit("UE-NGAP-ID-pair")?;
            let amf = r.constrained(0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?;
            let ran = r.constrained(0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?;
            opt_extension_container(r, has_ext, budget)?;
            finish_sequence(r, ext)?;
            Ok((amf, Some(ran)))
        } else {
            Ok((
                r.constrained(0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?,
                None,
            ))
        }
    })
}

pub fn ue_ngap_ids_ie(amf: u64, ran: Option<u64>) -> EncodeResult<Ie> {
    encode_ie(IE_UE_NGAP_IDS, Criticality::Reject, |w| {
        match ran {
            Some(ran) => {
                put_choice(w, 0, 3, "UE-NGAP-IDs")?;
                w.bit(false);
                w.bit(false);
                w.constrained(amf, 0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?;
                w.constrained(ran, 0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?;
            }
            None => {
                put_choice(w, 1, 3, "UE-NGAP-IDs")?;
                w.constrained(amf, 0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?;
            }
        }
        Ok(())
    })
}

/// One `UE-associatedLogicalNG-connectionItem`: either id may be absent.
pub type ConnectionItem = (Option<u64>, Option<u64>);

fn decode_connection_list(r: &mut Reader, budget: &mut Budget) -> CodecResult<Vec<ConnectionItem>> {
    let n = r.size(1, 65_536, "UE-associatedLogicalNG-connectionList")?;
    budget.take(n, "UE-associatedLogicalNG-connectionList")?;
    let mut out = Vec::with_capacity(n);
    for _ in 0..n {
        let ext = r.extension_bit("UE-associatedLogicalNG-connectionItem")?;
        let has_amf = r.bit("item")?;
        let has_ran = r.bit("item")?;
        let has_ext = r.bit("item")?;
        let amf = if has_amf {
            Some(r.constrained(0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?)
        } else {
            None
        };
        let ran = if has_ran {
            Some(r.constrained(0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?)
        } else {
            None
        };
        opt_extension_container(r, has_ext, budget)?;
        finish_sequence(r, ext)?;
        out.push((amf, ran));
    }
    Ok(out)
}

fn encode_connection_list(w: &mut Writer, items: &[ConnectionItem]) -> EncodeResult<()> {
    w.size(items.len(), 1, 65_536, "connection list")?;
    for (amf, ran) in items {
        w.bit(false);
        w.bit(amf.is_some());
        w.bit(ran.is_some());
        w.bit(false);
        if let Some(a) = amf {
            w.constrained(*a, 0, MAX_AMF_UE_NGAP_ID, "AMF-UE-NGAP-ID")?;
        }
        if let Some(r) = ran {
            w.constrained(*r, 0, MAX_RAN_UE_NGAP_ID, "RAN-UE-NGAP-ID")?;
        }
    }
    Ok(())
}

/// ResetType: `None` is reset-all, `Some(items)` the partial form.
pub fn decode_reset_type(ie: &Ie, budget: &mut Budget) -> CodecResult<Option<Vec<ConnectionItem>>> {
    decode_ie(ie, |r| {
        if choice(r, 3, "ResetType")? == 0 {
            r.enumerated(1, true, "ResetAll")?;
            Ok(None)
        } else {
            Ok(Some(decode_connection_list(r, budget)?))
        }
    })
}

pub fn reset_type_ie(partial: Option<&[ConnectionItem]>) -> EncodeResult<Ie> {
    encode_ie(IE_RESET_TYPE, Criticality::Reject, |w| {
        match partial {
            None => {
                put_choice(w, 0, 3, "ResetType")?;
                w.enumerated(0, false, 1, true, "ResetAll")?;
            }
            Some(items) => {
                put_choice(w, 1, 3, "ResetType")?;
                encode_connection_list(w, items)?;
            }
        }
        Ok(())
    })
}

pub fn decode_connection_list_ie(ie: &Ie, budget: &mut Budget) -> CodecResult<Vec<ConnectionItem>> {
    decode_ie(ie, |r| decode_connection_list(r, budget))
}

pub fn connection_list_ie(items: &[ConnectionItem]) -> EncodeResult<Ie> {
    encode_ie(
        IE_UE_ASSOCIATED_LOGICAL_NG_CONNECTION_LIST,
        Criticality::Ignore,
        |w| encode_connection_list(w, items),
    )
}

// ============================================================================
// Decoded messages
// ============================================================================

/// NG Setup Request, decoded for the model (TS 38.413 section 9.2.6.1).
pub fn parse_ng_setup_request(pdu: &Pdu) -> CodecResult<Value> {
    let mut budget = Budget::default();
    let node = decode_global_ran_node_id(pdu.require(IE_GLOBAL_RAN_NODE_ID)?, &mut budget)?;
    let tas = decode_supported_ta_list(pdu.require(IE_SUPPORTED_TA_LIST)?, &mut budget)?;
    let drx = decode_paging_drx(pdu.require(IE_DEFAULT_PAGING_DRX)?)?;
    let name = match pdu.ie(IE_RAN_NODE_NAME) {
        Some(ie) => Some(decode_name(ie)?),
        None => None,
    };
    Ok(json!({
        "global_ran_node_id": node,
        "ran_node_name": name,
        "supported_ta_list": tas,
        "default_paging_drx": drx,
        "uninterpreted_ies": pdu.uninterpreted_ies(&[
            IE_GLOBAL_RAN_NODE_ID, IE_SUPPORTED_TA_LIST, IE_DEFAULT_PAGING_DRX, IE_RAN_NODE_NAME
        ]),
    }))
}

/// NG Setup Response, decoded for the gNB's model (TS 38.413 section 9.2.6.2).
pub fn parse_ng_setup_response(pdu: &Pdu) -> CodecResult<Value> {
    let mut budget = Budget::default();
    let name = decode_name(pdu.require(IE_AMF_NAME)?)?;
    let guamis = decode_served_guami_list(pdu.require(IE_SERVED_GUAMI_LIST)?, &mut budget)?;
    let capacity = decode_relative_amf_capacity(pdu.require(IE_RELATIVE_AMF_CAPACITY)?)?;
    let plmns = decode_plmn_support_list(pdu.require(IE_PLMN_SUPPORT_LIST)?, &mut budget)?;
    Ok(json!({
        "amf_name": name,
        "served_guami": guamis,
        "relative_amf_capacity": capacity,
        "plmn_support": plmns,
        "uninterpreted_ies": pdu.uninterpreted_ies(&[
            IE_AMF_NAME, IE_SERVED_GUAMI_LIST, IE_RELATIVE_AMF_CAPACITY, IE_PLMN_SUPPORT_LIST
        ]),
    }))
}

/// NG Setup Failure, or any message carrying an optional Cause and Time to Wait.
pub fn parse_cause_message(pdu: &Pdu) -> CodecResult<Value> {
    let mut v = Map::new();
    if let Some(ie) = pdu.ie(IE_CAUSE) {
        v.insert("cause".into(), decode_cause(ie)?.to_json());
    }
    if let Some(ie) = pdu.ie(IE_TIME_TO_WAIT) {
        v.insert("time_to_wait".into(), json!(decode_time_to_wait(ie)?));
    }
    if let Some(ie) = pdu.ie(IE_AMF_UE_NGAP_ID) {
        v.insert("amf_ue_ngap_id".into(), json!(decode_amf_ue_ngap_id(ie)?));
    }
    if let Some(ie) = pdu.ie(IE_RAN_UE_NGAP_ID) {
        v.insert("ran_ue_ngap_id".into(), json!(decode_ran_ue_ngap_id(ie)?));
    }
    v.insert(
        "uninterpreted_ies".into(),
        json!(pdu.uninterpreted_ies(&[
            IE_CAUSE,
            IE_TIME_TO_WAIT,
            IE_AMF_UE_NGAP_ID,
            IE_RAN_UE_NGAP_ID
        ])),
    );
    Ok(Value::Object(v))
}

/// The UE-associated fields of an Initial UE Message.
pub struct InitialUe {
    pub ran_ue_ngap_id: u64,
    pub nas: Vec<u8>,
    pub user_location: Value,
    pub rrc_establishment_cause: String,
    pub five_g_s_tmsi: Option<Value>,
    pub uninterpreted: Vec<Value>,
}

/// Initial UE Message (TS 38.413 section 9.2.5.1).
pub fn parse_initial_ue_message(pdu: &Pdu) -> CodecResult<InitialUe> {
    let mut budget = Budget::default();
    let ran = decode_ran_ue_ngap_id(pdu.require(IE_RAN_UE_NGAP_ID)?)?;
    let nas = decode_nas_pdu(pdu.require(IE_NAS_PDU)?)?;
    if nas.is_empty() {
        return Err(semantic("empty NAS-PDU"));
    }
    let uli = decode_user_location(pdu.require(IE_USER_LOCATION_INFORMATION)?, &mut budget)?;
    let cause = decode_rrc_cause(pdu.require(IE_RRC_ESTABLISHMENT_CAUSE)?)?;
    let tmsi = match pdu.ie(IE_FIVE_G_S_TMSI) {
        Some(ie) => Some(decode_five_g_s_tmsi(ie, &mut budget)?),
        None => None,
    };
    Ok(InitialUe {
        ran_ue_ngap_id: ran,
        nas,
        user_location: uli,
        rrc_establishment_cause: cause,
        five_g_s_tmsi: tmsi,
        uninterpreted: pdu.uninterpreted_ies(&[
            IE_RAN_UE_NGAP_ID,
            IE_NAS_PDU,
            IE_USER_LOCATION_INFORMATION,
            IE_RRC_ESTABLISHMENT_CAUSE,
            IE_FIVE_G_S_TMSI,
        ]),
    })
}

/// The fields of a Downlink or Uplink NAS Transport.
pub struct NasTransport {
    pub amf_ue_ngap_id: u64,
    pub ran_ue_ngap_id: u64,
    pub nas: Vec<u8>,
    pub user_location: Option<Value>,
    pub uninterpreted: Vec<Value>,
}

/// Downlink (9.2.5.2) or Uplink (9.2.5.3) NAS Transport.
pub fn parse_nas_transport(pdu: &Pdu) -> CodecResult<NasTransport> {
    let mut budget = Budget::default();
    let amf = decode_amf_ue_ngap_id(pdu.require(IE_AMF_UE_NGAP_ID)?)?;
    let ran = decode_ran_ue_ngap_id(pdu.require(IE_RAN_UE_NGAP_ID)?)?;
    let nas = decode_nas_pdu(pdu.require(IE_NAS_PDU)?)?;
    if nas.is_empty() {
        return Err(semantic("empty NAS-PDU"));
    }
    let uli = match pdu.ie(IE_USER_LOCATION_INFORMATION) {
        Some(ie) => Some(decode_user_location(ie, &mut budget)?),
        None if pdu.procedure_code == PROC_UPLINK_NAS_TRANSPORT => {
            return Err(abstract_reject(
                "UplinkNASTransport is missing mandatory IE 121 (UserLocationInformation)",
            ))
        }
        None => None,
    };
    Ok(NasTransport {
        amf_ue_ngap_id: amf,
        ran_ue_ngap_id: ran,
        nas,
        user_location: uli,
        uninterpreted: pdu.uninterpreted_ies(&[
            IE_AMF_UE_NGAP_ID,
            IE_RAN_UE_NGAP_ID,
            IE_NAS_PDU,
            IE_USER_LOCATION_INFORMATION,
        ]),
    })
}

// ============================================================================
// Builders
// ============================================================================

fn build(kind: PduKind, code: u8, crit: Criticality, ies: Vec<Ie>) -> EncodeResult<Vec<u8>> {
    encode_pdu(&Pdu::new(kind, code, crit, ies))
}

/// NG Setup Response from the model's fields.
pub fn ng_setup_response(
    amf_name: &str,
    served_guami: &[Value],
    relative_amf_capacity: u64,
    plmn_support: &[Value],
) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Successful,
        PROC_NG_SETUP,
        Criticality::Reject,
        vec![
            name_ie(IE_AMF_NAME, Criticality::Reject, amf_name)?,
            served_guami_list_ie(served_guami)?,
            relative_amf_capacity_ie(relative_amf_capacity)?,
            plmn_support_list_ie(plmn_support)?,
        ],
    )
}

pub fn ng_setup_failure(cause: &Cause, time_to_wait: Option<&str>) -> EncodeResult<Vec<u8>> {
    let mut ies = vec![cause_ie(cause, Criticality::Ignore)?];
    if let Some(t) = time_to_wait {
        ies.push(time_to_wait_ie(t)?);
    }
    build(
        PduKind::Unsuccessful,
        PROC_NG_SETUP,
        Criticality::Reject,
        ies,
    )
}

pub fn ng_setup_request(
    plmn: &Plmn,
    gnb_id: u64,
    gnb_id_bits: u32,
    ran_node_name: Option<&str>,
    supported_ta_list: &[Value],
    paging_drx: &str,
) -> EncodeResult<Vec<u8>> {
    let mut ies = vec![global_gnb_id_ie(plmn, gnb_id, gnb_id_bits)?];
    if let Some(n) = ran_node_name {
        ies.push(name_ie(IE_RAN_NODE_NAME, Criticality::Ignore, n)?);
    }
    ies.push(supported_ta_list_ie(supported_ta_list)?);
    ies.push(paging_drx_ie(paging_drx)?);
    build(PduKind::Initiating, PROC_NG_SETUP, Criticality::Reject, ies)
}

pub fn downlink_nas_transport(amf: u64, ran: u64, nas: &[u8]) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Initiating,
        PROC_DOWNLINK_NAS_TRANSPORT,
        Criticality::Ignore,
        vec![
            amf_ue_ngap_id_ie(amf, Criticality::Reject)?,
            ran_ue_ngap_id_ie(ran, Criticality::Reject)?,
            nas_pdu_ie(nas)?,
        ],
    )
}

pub fn uplink_nas_transport(
    amf: u64,
    ran: u64,
    nas: &[u8],
    user_location: &Value,
) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Initiating,
        PROC_UPLINK_NAS_TRANSPORT,
        Criticality::Ignore,
        vec![
            amf_ue_ngap_id_ie(amf, Criticality::Reject)?,
            ran_ue_ngap_id_ie(ran, Criticality::Reject)?,
            nas_pdu_ie(nas)?,
            user_location_nr_ie(user_location, Criticality::Ignore)?,
        ],
    )
}

pub fn initial_ue_message(
    ran: u64,
    nas: &[u8],
    user_location: &Value,
    rrc_establishment_cause: &str,
) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Initiating,
        PROC_INITIAL_UE_MESSAGE,
        Criticality::Ignore,
        vec![
            ran_ue_ngap_id_ie(ran, Criticality::Reject)?,
            nas_pdu_ie(nas)?,
            user_location_nr_ie(user_location, Criticality::Reject)?,
            rrc_cause_ie(rrc_establishment_cause)?,
        ],
    )
}

pub fn error_indication(
    amf: Option<u64>,
    ran: Option<u64>,
    cause: Option<&Cause>,
) -> EncodeResult<Vec<u8>> {
    let mut ies = Vec::new();
    if let Some(a) = amf {
        ies.push(amf_ue_ngap_id_ie(a, Criticality::Ignore)?);
    }
    if let Some(r) = ran {
        ies.push(ran_ue_ngap_id_ie(r, Criticality::Ignore)?);
    }
    if let Some(c) = cause {
        ies.push(cause_ie(c, Criticality::Ignore)?);
    }
    build(
        PduKind::Initiating,
        PROC_ERROR_INDICATION,
        Criticality::Ignore,
        ies,
    )
}

pub fn ng_reset(cause: &Cause, partial: Option<&[ConnectionItem]>) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Initiating,
        PROC_NG_RESET,
        Criticality::Reject,
        vec![
            cause_ie(cause, Criticality::Ignore)?,
            reset_type_ie(partial)?,
        ],
    )
}

/// NG Reset Acknowledge; for a partial reset the list of connections reset is echoed (38.413
/// section 8.7.4.2.1).
pub fn ng_reset_acknowledge(partial: Option<&[ConnectionItem]>) -> EncodeResult<Vec<u8>> {
    let mut ies = Vec::new();
    if let Some(items) = partial {
        ies.push(connection_list_ie(items)?);
    }
    build(PduKind::Successful, PROC_NG_RESET, Criticality::Reject, ies)
}

pub fn ue_context_release_command(
    amf: u64,
    ran: Option<u64>,
    cause: &Cause,
) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Initiating,
        PROC_UE_CONTEXT_RELEASE,
        Criticality::Reject,
        vec![
            ue_ngap_ids_ie(amf, ran)?,
            cause_ie(cause, Criticality::Ignore)?,
        ],
    )
}

pub fn ue_context_release_complete(amf: u64, ran: u64) -> EncodeResult<Vec<u8>> {
    build(
        PduKind::Successful,
        PROC_UE_CONTEXT_RELEASE,
        Criticality::Reject,
        vec![
            amf_ue_ngap_id_ie(amf, Criticality::Ignore)?,
            ran_ue_ngap_id_ie(ran, Criticality::Ignore)?,
        ],
    )
}

/// Every IE id of an encoded PDU, for logs; `None` when it does not decode.
pub fn summarize(bytes: &[u8]) -> Option<String> {
    let p = decode_pdu(bytes).ok()?;
    Some(p.label())
}

/// Re-export so callers name one error type for "the peer sent garbage".
pub use aper::AperError as WireError;