epics-base-rs 0.29.1

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
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
use crate::error::{CaError, CaResult};
use std::time::SystemTime;

use super::{DbFieldType, EpicsValue, PvString, WallTime, c_cast};

// db_access.h constants
const MAX_UNITS_SIZE: usize = 8;
const MAX_ENUM_STATES: usize = 16;
const MAX_ENUM_STRING_SIZE: usize = 26;

const EPICS_UNIX_EPOCH_OFFSET_SECS: u64 = 631_152_000;

pub fn serialize_dbr(
    dbr_type: u16,
    value: &EpicsValue,
    status: u16,
    severity: u16,
    timestamp: impl Into<WallTime>,
) -> CaResult<Vec<u8>> {
    let timestamp: WallTime = timestamp.into();
    // DBR_CLASS_NAME (38) carries a single 40-byte string with the
    // record's recordType. The metadata-free encoding mirrors the C
    // `dbChannel_classify` reply path. `value` here is expected to
    // already be a String. Used only by `serialize_dbr` callers; the
    // server-driven path (`encode_dbr`) reads `Snapshot::class_name`.
    if dbr_type == super::DBR_CLASS_NAME {
        let mut buf = [0u8; 40];
        if let EpicsValue::String(s) = value {
            let bytes = s.as_bytes();
            let len = bytes.len().min(39);
            buf[..len].copy_from_slice(&bytes[..len]);
        }
        return Ok(buf.to_vec());
    }
    let native = super::native_type_for_dbr(dbr_type)?;
    let val_bytes = convert_and_serialize(native, value)?;
    match dbr_type {
        0..=6 => Ok(val_bytes),
        7..=13 => serialize_sts(native, &val_bytes, status, severity),
        14..=20 => serialize_time(native, &val_bytes, status, severity, timestamp),
        21..=27 => serialize_gr_ctrl(native, &val_bytes, status, severity, false),
        28..=34 => serialize_gr_ctrl(native, &val_bytes, status, severity, true),
        _ => Err(CaError::UnsupportedType(dbr_type)),
    }
}

/// `(secPastEpoch, nsec)` exactly as C computes them, wrap included.
///
/// C `epicsTimeFromTime_t`
/// (`$EPICS_BASE/modules/libcom/src/osi/epicsTime.cpp:305-310` at `R7.0.10`)
/// computes `epicsInt64(src) - POSIX_TIME_AT_EPICS_EPOCH` and assigns it into
/// an `epicsUInt32`, so a pre-1990 or post-2106 clock WRAPS and the call still
/// returns `epicsTimeOK`. This does the same arithmetic and yields the same
/// bytes. What it replaces is a clamp — `saturating_sub(..).min(u32::MAX)` —
/// which was a third answer, neither C's nor better than C's: it put every
/// stamp from a dead-RTC board at exactly `0` or `0xFFFF_FFFF`, values a
/// client cannot tell from a real reading at those instants.
///
/// The out-of-range clock is worth reporting, but not from here: this runs
/// once per value per client, while the condition is constant for the life of
/// the boot — on the RTEMS target it comes from the build-time
/// `EPICS_RTEMS_BOOT_EPOCH` (`epics-rtems-boot/csrc/rtems_init.c`).
/// [`wall_clock_range_warning`] is the report, and init is its caller.
///
/// [`WallTime::UNIX_EPOCH`] is exempt and encodes as `{0, 0}`. That is not a
/// boundary special case: it is this port's *unset* stamp, and `{0, 0}` is
/// exactly what C carries for a record that has not processed — the value C's
/// own "uninitialized time stamp" test looks for (`epicsTime.cpp:176`).
fn epics_timestamp_parts(timestamp: WallTime) -> (u32, u32) {
    if timestamp == WallTime::UNIX_EPOCH {
        return (0, 0);
    }
    let unix = timestamp.since_unix_epoch();
    // Wrapping, not saturating: C's `epicsInt64` subtraction assigned into an
    // `epicsUInt32` is modulo 2^32, and truncating the u64 difference gives
    // the identical low 32 bits.
    let sec_past_epoch = unix.as_secs().wrapping_sub(EPICS_UNIX_EPOCH_OFFSET_SECS) as u32;
    (sec_past_epoch, unix.subsec_nanos())
}

/// One line naming a wall clock the EPICS time stamp cannot hold, or `None`
/// when the clock is in range.
///
/// Every stamp on the wire is an `epicsUInt32 secPastEpoch`, so a clock
/// outside 1990-01-01 .. 2106-02-07 is encoded wrapped, and a client or an
/// archiver takes the wrapped value for a real instant. C wraps identically
/// and never says so. The whole of the difference this port makes is that it
/// is said once, at the only moment an operator can act on it: the epoch is
/// fixed for the life of the boot, so a per-read message would be noise and a
/// per-read refusal would take the IOC off the air for a condition it cannot
/// fix.
pub fn wall_clock_range_warning(now: impl Into<WallTime>) -> Option<String> {
    let now: WallTime = now.into();
    if now == WallTime::UNIX_EPOCH {
        return None;
    }
    let secs = now.since_unix_epoch().as_secs();
    // Both ends, not just the far one: the board this exists for is the one
    // whose clock reads BEFORE 1990, where `checked_sub` yields nothing.
    let in_range = secs
        .checked_sub(EPICS_UNIX_EPOCH_OFFSET_SECS)
        .is_some_and(|past_epoch| past_epoch <= u32::MAX as u64);
    if in_range {
        return None;
    }
    Some(format!(
        "wall clock reads {secs} s past the Unix epoch, which is outside the \
         EPICS time stamp's range (1990-01-01 .. 2106-02-07); every time \
         stamp this IOC serves will be wrapped modulo 2^32 seconds, as C's \
         epicsTimeFromTime_t wraps it. Set the board's clock, or its \
         build-time epoch, before trusting any archived time from it."
    ))
}

/// Convert value to the target native type and serialize to bytes.
fn convert_and_serialize(native: DbFieldType, value: &EpicsValue) -> CaResult<Vec<u8>> {
    let mut buf = Vec::new();
    convert_and_serialize_into(native, value, &mut buf)?;
    Ok(buf)
}

/// [`convert_and_serialize`] appending into a caller-owned buffer. When the
/// value already has the requested native type — every monitor on an
/// unconverted field — the bytes go straight onto `dst` with no intermediate.
fn convert_and_serialize_into(
    native: DbFieldType,
    value: &EpicsValue,
    dst: &mut Vec<u8>,
) -> CaResult<()> {
    if value.dbr_type() == native {
        value.write_into(dst);
    } else {
        value.get_convert(native)?.write_into(dst);
    }
    Ok(())
}

// precision-aware `*_STRING` rendering of a numeric field.
//
// A `*_STRING` DBR request of a Double/Float field is converted by the C
// IOC with `cvtDoubleToString` / `cvtFloatToString` (libCom cvtFast.c)
// using the record's `get_precision` (PREC). `EpicsValue::convert_to` has
// no record context, so the precision-aware conversion lives here where
// `encode_dbr` holds the snapshot.

/// libCom cvtFast.c `frac_multiplier` — fractional scale by precision 0..=8.
const FRAC_MULTIPLIER: [i32; 9] = [
    1,
    10,
    100,
    1_000,
    10_000,
    100_000,
    1_000_000,
    10_000_000,
    100_000_000,
];

/// Render a numeric value as its DBR_STRING form, applying `precision` to
/// Float/Double exactly as C `getDoubleString`/`getFloatString` do. Integer
/// and string values keep the plain `convert_to(String)` path (their C
/// conversions carry no precision, so the default `Display` already matches).
fn convert_value_to_dbr_string(
    value: &EpicsValue,
    snapshot: &crate::server::snapshot::Snapshot,
) -> CaResult<EpicsValue> {
    // C `getDoubleString` (`dbConvert.c:772-790`) opens with
    // `long precision = 6;` and overwrites it only `if (prset &&
    // prset->get_precision)`. The 6 is therefore the answer for every record
    // type that NULLs the slot — `biRecord.c:58` is literally
    // `#define get_precision NULL`, and sixteen siblings say the same — and
    // `Snapshot::precision` is what reports that, `None` for an unsupplied
    // slot. Reading `display.precision` raw could not: `DisplayInfo` is minted
    // for every snapshot (the DESC leaf, which pvxs fills for every record
    // type), so its `Option` says nothing about the rset and the seed was
    // unreachable.
    //
    // A NEGATIVE PREC is not clamped: C hands the `long precision` straight to
    // `cvtDoubleToString(double, char*, epicsUInt16 precision)`
    // (`dbConvert.c:786`), and the implicit conversion REINTERPRETS it — PREC=-1
    // arrives as 65535, which takes the `precision > 8` branch, caps at 17 and
    // renders `%*.*e` (compiled: `caget -S` of a PREC=-1 ai gives
    // ` 3.70000000000000018e+00`). Clamping to 0 printed `4` instead.
    let prec = snapshot.precision().map(|p| p as u16).unwrap_or(6);
    if let Some(rendered) = dbr_string_at_precision(value, prec) {
        return Ok(rendered);
    }
    Ok(match value {
        // C `getEnumString` (dbConvert.c, `[DBF_ENUM][DBR_STRING]`) hands the
        // value to the field's own string source — the record's `get_enum_str`
        // rset, a menu's choice list, a device's choice list — and renders what
        // comes back. See `enum_label`.
        EpicsValue::Enum(v) => EpicsValue::String(enum_label(snapshot, *v)),
        EpicsValue::EnumArray(a) => {
            EpicsValue::StringArray(a.iter().map(|v| enum_label(snapshot, *v)).collect())
        }
        other => other.get_convert(DbFieldType::String)?,
    })
}

/// The float/double rows of C's `DBR_STRING` column, **in both directions**.
///
/// `getFloatString`/`getDoubleString` (`dbConvert.c:735`/`:772`),
/// `putFloatString`/`putDoubleString` (`:1558`/`:1600`) and the scalar twins
/// `cvt_f_st`/`cvt_d_st` (`dbFastLinkConv.c:1216`/`:1333`) are four copies of
/// one body: seed `long precision = 6`, overwrite it from
/// `prset->get_precision`, render through `cvtFloatToString` /
/// `cvtDoubleToString`. Every other numeric row of that column —
/// `cvtCharToString` through `cvtUInt64ToString` — carries no precision at
/// all, which is why this answers `None` for them and leaves them to the
/// plain `convert_to` / `get_convert` projection.
///
/// One function because the two directions have to agree: the put path used
/// Rust's `Display` and stored `1.0` into a `PREC=3` `DESC` as `"1"` where
/// `dbtpf` gave `"1.000"` — one field reading back two ways depending on which
/// door the value came through.
pub(crate) fn dbr_string_at_precision(value: &EpicsValue, prec: u16) -> Option<EpicsValue> {
    Some(match value {
        EpicsValue::Double(v) => EpicsValue::String(cvt_double_to_string(*v, prec).into()),
        EpicsValue::Float(v) => EpicsValue::String(cvt_float_to_string(*v, prec).into()),
        EpicsValue::DoubleArray(a) => EpicsValue::StringArray(
            a.iter()
                .map(|v| cvt_double_to_string(*v, prec).into())
                .collect(),
        ),
        EpicsValue::FloatArray(a) => EpicsValue::StringArray(
            a.iter()
                .map(|v| cvt_float_to_string(*v, prec).into())
                .collect(),
        ),
        _ => return None,
    })
}

/// Render an enum index as C's `get_enum_str` does, through the channel's
/// [`crate::server::snapshot::EnumStringForm`] — the one owner
/// of "what string this enum value is".
///
/// There is no decimal fallback, because C has no path that produces one: a
/// value with no matching slot renders as the record's out-of-range sentinel
/// (empty for a menu), and a channel with no enum source at all is `S_db_noRSET`
/// in C — an error, never the number. The port answers empty rather than invent
/// a digit string that no C IOC can emit.
fn enum_label(snapshot: &crate::server::snapshot::Snapshot, idx: u16) -> PvString {
    snapshot
        .enums
        .as_ref()
        .map(|e| e.string_form.render(idx))
        .unwrap_or_default()
}

/// Port of libCom `cvtDoubleToString` (cvtFast.c:111-190).
///
/// `pub(crate)` so records that mirror C's `cvtDoubleToString(value, str,
/// prec)` (e.g. `sseq` refreshing `STRn` from a numeric `DOLn`,
/// sseqRecord.c:676) format through the exact same converter the DBR-string
/// wire encoder uses, instead of a divergent `format!` that rounds
/// differently.
pub(crate) fn cvt_double_to_string(val: f64, precision: u16) -> String {
    if val.is_nan() || precision > 8 || val > 1e7 || val < -1e7 {
        if precision > 8 || val > 1e16 || val < -1e16 {
            let p = precision.min(17) as usize;
            return fmt_exp_c(val, p, p + 7);
        }
        return fmt_fixed_c(val, precision.min(3) as usize);
    }
    let mut val = val;
    let mut out = String::new();
    if val < 0.0 {
        out.push('-');
        val = -val;
    }
    let mut whole = val as i32;
    let ftemp = val - whole as f64;
    let fplace_full = FRAC_MULTIPLIER[precision as usize];
    let mut fraction = (ftemp * fplace_full as f64 * 10.0) as i32;
    fraction = (fraction + 5) / 10; // round half up
    if fraction / fplace_full >= 1 {
        whole += 1;
        fraction -= fplace_full;
    }
    push_fixed_digits(&mut out, whole, fraction, fplace_full, precision);
    out
}

/// Port of libCom `cvtFloatToString` (cvtFast.c:32-109). The fast path runs
/// in f32 to match the C float arithmetic; the overflow branches cast to
/// double exactly as the C `sprintf((double) flt_value)` does.
fn cvt_float_to_string(val: f32, precision: u16) -> String {
    if val.is_nan() || precision > 8 || val > 1e7 || val < -1e7 {
        if precision > 8 || val >= 1e8 || val <= -1e8 {
            let p = precision.min(12) as usize;
            return fmt_exp_c(val as f64, p, p + 6);
        }
        return fmt_fixed_c(val as f64, precision.min(3) as usize);
    }
    let mut val = val;
    let mut out = String::new();
    if val < 0.0 {
        out.push('-');
        val = -val;
    }
    let mut whole = val as i32;
    let ftemp = val - whole as f32;
    let fplace_full = FRAC_MULTIPLIER[precision as usize];
    let mut fraction = (ftemp * fplace_full as f32 * 10.0) as i32;
    fraction = (fraction + 5) / 10; // round half up
    if fraction / fplace_full >= 1 {
        whole += 1;
        fraction -= fplace_full;
    }
    push_fixed_digits(&mut out, whole, fraction, fplace_full, precision);
    out
}

/// Emit the whole-number then fractional digits, shared by the float/double
/// fast paths (cvtFast.c:75-105 / :156-186).
fn push_fixed_digits(
    out: &mut String,
    mut whole: i32,
    mut fraction: i32,
    fplace_full: i32,
    precision: u16,
) {
    let mut got_one = false;
    let mut iplace = 10_000_000i32;
    while iplace >= 1 {
        if whole >= iplace {
            got_one = true;
            let number = whole / iplace;
            whole -= number * iplace;
            out.push((b'0' + number as u8) as char);
        } else if got_one {
            out.push('0');
        }
        iplace /= 10;
    }
    if !got_one {
        out.push('0');
    }
    if precision > 0 {
        out.push('.');
        let mut fplace = fplace_full / 10;
        for _ in 0..precision {
            let number = fraction / fplace;
            fraction -= number * fplace;
            out.push((b'0' + number as u8) as char);
            fplace /= 10;
        }
    }
}

/// C `sprintf("%.*f", precision, val)`, with glibc NaN/Inf spellings.
fn fmt_fixed_c(val: f64, precision: usize) -> String {
    if val.is_nan() {
        return "nan".to_string();
    }
    if val.is_infinite() {
        return if val < 0.0 { "-inf" } else { "inf" }.to_string();
    }
    format!("{val:.precision$}")
}

/// C `sprintf("%*.*e", width, precision, val)`: scientific notation with a
/// signed, ≥2-digit exponent, right-justified in `width`. glibc NaN/Inf
/// spellings.
fn fmt_exp_c(val: f64, precision: usize, width: usize) -> String {
    let body = if val.is_nan() {
        "nan".to_string()
    } else if val.is_infinite() {
        if val < 0.0 { "-inf" } else { "inf" }.to_string()
    } else {
        // Rust `{:.*e}` rounds the mantissa half-to-even (matching glibc)
        // and emits `<mantissa>e<exp>` with no exponent sign / leading
        // zero; reformat the exponent to C's `e±dd`.
        let raw = format!("{val:.precision$e}");
        let (mantissa, exp) = raw.split_once('e').unwrap_or((raw.as_str(), "0"));
        let exp_num: i32 = exp.parse().unwrap_or(0);
        let sign = if exp_num < 0 { '-' } else { '+' };
        format!("{mantissa}e{sign}{:02}", exp_num.abs())
    };
    // Right-justify in `width` (C `%*.*e` pads with leading spaces).
    format!("{body:>width$}")
}

/// RISC alignment padding bytes required between metadata header and value.
pub(crate) fn sts_pad(native: DbFieldType) -> &'static [u8] {
    match native {
        // status(2)+severity(2) = 4 → short/enum need 0 pad.
        // `dbr_sts_char` (db_access.h:218-223): `dbr_char_t RISC_pad`
        // (epicsInt8, 1 byte) between severity and value. DBF_UCHAR promotes
        // to DBR_CHAR (db_convert.h dbDBRnewToDBRold) so it shares the pad.
        DbFieldType::Char | DbFieldType::UChar => &[0],
        // `dbr_sts_double` (db_access.h:233-238): `dbr_long_t RISC_pad`
        // (epicsInt32, **4 bytes** — `db_access.h:45 typedef epicsInt32
        // dbr_long_t`) between severity and value. Layout is
        // status(2)+severity(2)+RISC_pad(4)+value(8) → value at offset 8.
        // Int64/UInt64 are served over CA as DBR_DOUBLE so they share the pad;
        // DBF_ULONG promotes to DBR_DOUBLE (db_convert.h dbDBRnewToDBRold) too.
        // DBF_USHORT promotes to DBR_LONG, which has no STS pad, so it stays
        // in the `_` arm with Short/Long/Float.
        DbFieldType::Double | DbFieldType::Int64 | DbFieldType::UInt64 | DbFieldType::ULong => {
            &[0, 0, 0, 0]
        }
        _ => &[],
    }
}

/// RISC alignment padding bytes for TIME structs (after 12-byte metadata header).
pub(crate) fn time_pad(native: DbFieldType) -> &'static [u8] {
    match native {
        // 12 bytes header → short/enum need 2-pad, char needs 2+1=3 pad.
        // DBF_UCHAR promotes to DBR_CHAR so it shares the char pad.
        DbFieldType::Short | DbFieldType::Enum => &[0, 0],
        DbFieldType::Char | DbFieldType::UChar => &[0, 0, 0],
        // double: 12 → pad 4 to reach 16-byte boundary for 8-byte double.
        // DBF_ULONG promotes to DBR_DOUBLE (db_convert.h dbDBRnewToDBRold) so
        // it shares the 4-byte pad; DBF_USHORT promotes to DBR_LONG (4-byte-
        // aligned at offset 12, no pad) and stays in the `_` arm with Long.
        DbFieldType::Double | DbFieldType::ULong => &[0, 0, 0, 0],
        _ => &[],
    }
}

/// Metadata byte count that precedes `value[0]` for a GR (`ctrl=false`)
/// or CTRL (`ctrl=true`) DBR struct. this is the single source
/// of truth shared with [`serialize_gr_ctrl`] / `write_gr_ctrl_meta` — every component below is the exact byte sequence
/// those writers emit before the value, so the sizer cannot drift from
/// the encoder. `n_limits` is 6 for GR (display/alarm limits) and 8 for
/// CTRL (plus upper/lower control limits).
fn gr_ctrl_meta_size(native: DbFieldType, ctrl: bool) -> usize {
    let n_limits = if ctrl { 8 } else { 6 };
    // status(2) + severity(2) is common to every GR/CTRL struct.
    let head = 4;
    match native {
        // "not implemented; use dbr_sts_string" — only the common head.
        DbFieldType::String => head + sts_pad(native).len(),
        // no_str(u16) + char[MAX_ENUM_STATES][MAX_ENUM_STRING_SIZE].
        DbFieldType::Enum => head + 2 + MAX_ENUM_STATES * MAX_ENUM_STRING_SIZE,
        // precision(2) + RISC_pad(2) + units[8] + n limits (f32).
        DbFieldType::Float => head + 4 + MAX_UNITS_SIZE + n_limits * 4,
        // precision(2) + RISC_pad(2) + units[8] + n limits (f64). Int64/
        // UInt64/ULong have no CA GR/CTRL type and reuse the Double layout
        // (DBF_ULONG promotes to DBR_DOUBLE, db_convert.h dbDBRnewToDBRold).
        DbFieldType::Double | DbFieldType::Int64 | DbFieldType::UInt64 | DbFieldType::ULong => {
            head + 4 + MAX_UNITS_SIZE + n_limits * 8
        }
        // units[8] + n limits (i16).
        DbFieldType::Short => head + MAX_UNITS_SIZE + n_limits * 2,
        // units[8] + n limits (i32). DBF_USHORT promotes to DBR_LONG, so it
        // reuses the Long GR/CTRL layout.
        DbFieldType::Long | DbFieldType::UShort => head + MAX_UNITS_SIZE + n_limits * 4,
        // units[8] + n limits (u8) + RISC_pad(1). DBF_UCHAR promotes to
        // DBR_CHAR (db_convert.h dbDBRnewToDBRold), reusing the Char layout.
        DbFieldType::Char | DbFieldType::UChar => head + MAX_UNITS_SIZE + n_limits + 1,
    }
}

/// Number of metadata bytes that precede `value[0]` for a DBR type —
/// the single size owner mirrored from the serializers in this module.
/// `dbr_buffer_size` derives payload sizing from this so the
/// explicit-count pad/truncate and no-read-access frame paths match the
/// bytes the encoder actually writes (C `dbr_size_n` parity), instead of
/// a parallel table that drifted on TIME/GR/CTRL layouts.
///
/// `DBR_CLASS_NAME` (38) is intentionally not handled here — it carries
/// no `value[]` array and is sized as a flat 40-byte string by the
/// caller. Returns the value-preceding metadata length for everything
/// in the plain/STS/TIME/GR/CTRL ranges plus the alarm-ack variants.
pub(crate) fn dbr_meta_size(dbr_type: u16, native: DbFieldType) -> usize {
    match dbr_type {
        // Plain value, no metadata.
        0..=6 => 0,
        // STS: status(2) + severity(2) + per-type RISC pad.
        7..=13 => 4 + sts_pad(native).len(),
        // TIME: status(2) + severity(2) + stamp(8) + per-type RISC pad.
        14..=20 => 12 + time_pad(native).len(),
        // GR: display/alarm limits.
        21..=27 => gr_ctrl_meta_size(native, false),
        // CTRL: GR plus control limits.
        28..=34 => gr_ctrl_meta_size(native, true),
        // PUT_ACKT / PUT_ACKS carry only a bare u16 value (no metadata);
        // the server emits them with `Ok(val_bytes)`.
        super::DBR_PUT_ACKT | super::DBR_PUT_ACKS => 0,
        // STSACK_STRING: status(2) + severity(2) + ackt(2) + acks(2)
        // before the 40-byte value string.
        super::DBR_STSACK_STRING => 8,
        // CLASS_NAME and anything else: no value-preceding metadata model.
        _ => 0,
    }
}

/// Append the STS metadata prefix (`status`, `severity`, RISC pad).
fn write_sts_meta(dst: &mut Vec<u8>, native: DbFieldType, status: u16, severity: u16) {
    dst.extend_from_slice(&status.to_be_bytes());
    dst.extend_from_slice(&severity.to_be_bytes());
    dst.extend_from_slice(sts_pad(native));
}

/// Append the TIME metadata prefix (STS plus the EPICS timestamp).
fn write_time_meta(
    dst: &mut Vec<u8>,
    native: DbFieldType,
    status: u16,
    severity: u16,
    timestamp: WallTime,
) {
    let (secs, nanos) = epics_timestamp_parts(timestamp);
    dst.extend_from_slice(&status.to_be_bytes());
    dst.extend_from_slice(&severity.to_be_bytes());
    dst.extend_from_slice(&secs.to_be_bytes());
    dst.extend_from_slice(&nanos.to_be_bytes());
    dst.extend_from_slice(time_pad(native));
}

fn serialize_sts(
    native: DbFieldType,
    val_bytes: &[u8],
    status: u16,
    severity: u16,
) -> CaResult<Vec<u8>> {
    let mut buf = Vec::with_capacity(4 + sts_pad(native).len() + val_bytes.len());
    write_sts_meta(&mut buf, native, status, severity);
    buf.extend_from_slice(val_bytes);
    Ok(buf)
}

fn serialize_time(
    native: DbFieldType,
    val_bytes: &[u8],
    status: u16,
    severity: u16,
    timestamp: WallTime,
) -> CaResult<Vec<u8>> {
    let mut buf = Vec::with_capacity(12 + time_pad(native).len() + val_bytes.len());
    write_time_meta(&mut buf, native, status, severity, timestamp);
    buf.extend_from_slice(val_bytes);
    Ok(buf)
}

/// Serialize value with GR or CTRL metadata for a channel that carries no
/// record metadata at all.
///
/// Routed through the same [`write_gr_ctrl_meta`] the server path uses
/// rather than a second hand-written zero layout. "No metadata" is not the
/// same as "all bytes zero" — C's `get_alarm` seeds its four limits with
/// `epicsNAN` and copies them into the reply even when the rset slot is
/// missing (`dbAccess.c:294`, `:318-323`), so a duplicate layout here would
/// disagree with `encode_dbr` on exactly the case it exists to mirror.
fn serialize_gr_ctrl(
    native: DbFieldType,
    val_bytes: &[u8],
    status: u16,
    severity: u16,
    ctrl: bool,
) -> CaResult<Vec<u8>> {
    let mut buf = Vec::with_capacity(96 + val_bytes.len());
    // A channel supplying nothing: `PropertySupport::default()` leaves every
    // rset slot false, which is what makes every group take its seed.
    let bare = crate::server::snapshot::Snapshot::new(
        EpicsValue::Double(0.0),
        status,
        severity,
        SystemTime::UNIX_EPOCH,
    );
    write_gr_ctrl_meta(&mut buf, native, &bare, if ctrl { 8 } else { 6 });
    buf.extend_from_slice(val_bytes);
    Ok(buf)
}

/// Encode a DBR response from a Snapshot. GR/CTRL types include real metadata.
/// Plain/Sts/Time are byte-identical to serialize_dbr output.
///
/// Thin wrapper over [`encode_dbr_into`] — use that on any path that already
/// owns the buffer the bytes are headed for.
pub fn encode_dbr(
    dbr_type: u16,
    snapshot: &crate::server::snapshot::Snapshot,
) -> CaResult<Vec<u8>> {
    let mut buf = Vec::new();
    encode_dbr_into(&mut buf, dbr_type, snapshot)?;
    Ok(buf)
}

/// Append the DBR wire body for `snapshot` to `dst`, leaving whatever `dst`
/// already holds untouched.
///
/// This is the shape C uses. `read_reply` never builds a standalone payload:
/// `cas_copy_in_header` reserves the header *and* the payload inside the
/// client's existing send buffer and hands back `pPayload`
/// (`rsrv/camessage.c:516`), then `dbGet`'s `!dbfl_has_copy(pfl)` arm converts
/// the record's live field straight into that space (`dbAccess.c:1020`). So the
/// caller reserves its header room in `dst` and the metadata plus the converted
/// value land after it — a 1 MiB waveform is materialised once, not built here
/// and copied into a frame.
///
/// One deviation remains and is deliberate: a request whose DBR type differs
/// from the value's native type still builds a converted `EpicsValue` first
/// (`convert_and_serialize` → `EpicsValue::convert_to`), because the port's
/// conversion is value-to-value where C's `convert()` is field-to-buffer. The
/// native-type case — every monitor on an unconverted field, including the
/// array fan-out this exists for — takes the zero-copy path.
pub fn encode_dbr_into(
    dst: &mut Vec<u8>,
    dbr_type: u16,
    snapshot: &crate::server::snapshot::Snapshot,
) -> CaResult<()> {
    // CLASS_NAME (38) emits a fixed 40-byte string from
    // snapshot.class_name and ignores snapshot.value entirely.
    // Early-return BEFORE convert_and_serialize so a waveform PV's
    // value (potentially N elements wide) is not Display'd into a
    // throwaway joined string. Mirrors the same shortcut in
    // serialize_dbr (line ~25).
    if dbr_type == super::DBR_CLASS_NAME {
        let mut buf = [0u8; 40];
        if let Some(ref name) = snapshot.class_name {
            let bytes = name.as_bytes();
            let len = bytes.len().min(39);
            buf[..len].copy_from_slice(&bytes[..len]);
        }
        dst.extend_from_slice(&buf);
        return Ok(());
    }
    let native = super::native_type_for_dbr(dbr_type)?;
    let status = snapshot.alarm.status;
    let severity = snapshot.alarm.severity;

    // Metadata first — it precedes the value in every DBR layout — so the
    // value can then be converted directly onto the tail of `dst`.
    match dbr_type {
        0..=6 => {}
        7..=13 => write_sts_meta(dst, native, status, severity),
        14..=20 => write_time_meta(dst, native, status, severity, snapshot.timestamp),
        21..=27 => write_gr_meta(dst, native, snapshot),
        28..=34 => write_ctrl_meta(dst, native, snapshot),
        // PUT_ACKT (35) and PUT_ACKS (36) are write-only on the wire:
        // the server should never produce them in a read response. We
        // expose a no-op encoding so callers that round-trip through
        // encode_dbr (e.g. forwarders) don't fail loudly.
        super::DBR_PUT_ACKT | super::DBR_PUT_ACKS => {}
        // STSACK_STRING — alarm acknowledge string response. Layout:
        //   status(2) severity(2) ackt(2) acks(2) value(40) = 48 bytes.
        // ackt/acks are taken from snapshot.alarm if available; the
        // value itself comes from the encoded native String.
        super::DBR_STSACK_STRING => {
            let ackt = snapshot.alarm.ackt.unwrap_or(0);
            let acks = snapshot.alarm.acks.unwrap_or(0);
            dst.extend_from_slice(&status.to_be_bytes());
            dst.extend_from_slice(&severity.to_be_bytes());
            dst.extend_from_slice(&ackt.to_be_bytes());
            dst.extend_from_slice(&acks.to_be_bytes());
        }
        // CLASS_NAME (38) handled by the early-return above.
        _ => return Err(CaError::UnsupportedType(dbr_type)),
    }

    // a `*_STRING` request of a Double/Float field must honor the
    // record's precision (C `getDoubleString` → `cvtDoubleToString`).
    // `EpicsValue::convert_to(String)` (value.rs) has no record context, so
    // route string requests through the precision-aware converter here.
    if native == DbFieldType::String {
        convert_value_to_dbr_string(&snapshot.value, snapshot)?.write_into(dst);
    } else {
        convert_and_serialize_into(native, &snapshot.value, dst)?;
    }
    Ok(())
}

/// Append GR (graphic/display) metadata — the real snapshot values, not the
/// zeroed layout `serialize_gr_ctrl` emits.
fn write_gr_meta(
    dst: &mut Vec<u8>,
    native: DbFieldType,
    snapshot: &crate::server::snapshot::Snapshot,
) {
    write_gr_ctrl_meta(dst, native, snapshot, 6)
}

/// Append CTRL (control) metadata. Same as GR but with 8 limits (adds
/// upper/lower ctrl).
fn write_ctrl_meta(
    dst: &mut Vec<u8>,
    native: DbFieldType,
    snapshot: &crate::server::snapshot::Snapshot,
) {
    write_gr_ctrl_meta(dst, native, snapshot, 8)
}

/// The one GR/CTRL metadata layout owner; `n_limits` (6 vs 8) is the only
/// difference between the two DBR classes.
fn write_gr_ctrl_meta(
    dst: &mut Vec<u8>,
    native: DbFieldType,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    dst.extend_from_slice(&snapshot.alarm.status.to_be_bytes());
    dst.extend_from_slice(&snapshot.alarm.severity.to_be_bytes());

    match native {
        DbFieldType::String => {
            dst.extend_from_slice(sts_pad(native));
        }
        DbFieldType::Enum => {
            encode_enum_metadata(dst, snapshot);
        }
        DbFieldType::Float => {
            encode_prec_units_limits_f32(dst, snapshot, n_limits);
        }
        DbFieldType::Double => {
            encode_prec_units_limits_f64(dst, snapshot, n_limits);
        }
        DbFieldType::Short => {
            encode_units_limits_i16(dst, snapshot, n_limits);
        }
        // DBF_USHORT promotes to DBR_LONG; use the Long GR/CTRL layout.
        DbFieldType::Long | DbFieldType::UShort => {
            encode_units_limits_i32(dst, snapshot, n_limits);
        }
        // DBF_UCHAR promotes to DBR_CHAR; use the Char GR/CTRL layout.
        DbFieldType::Char | DbFieldType::UChar => {
            encode_units_limits_u8(dst, snapshot, n_limits);
            dst.push(0); // RISC_pad
        }
        // Int64/UInt64/ULong have no CA GR/CTRL type; use Double layout
        // (DBF_ULONG promotes to DBR_DOUBLE).
        DbFieldType::Int64 | DbFieldType::UInt64 | DbFieldType::ULong => {
            encode_prec_units_limits_f64(dst, snapshot, n_limits);
        }
    }
}

/// Write units field (8 bytes, null-padded).
fn encode_units(buf: &mut Vec<u8>, snapshot: &crate::server::snapshot::Snapshot) {
    let mut units_buf = [0u8; MAX_UNITS_SIZE];
    if let Some(units) = snapshot.units() {
        let bytes = units.as_bytes();
        let len = bytes.len().min(MAX_UNITS_SIZE - 1);
        units_buf[..len].copy_from_slice(&bytes[..len]);
    }
    buf.extend_from_slice(&units_buf);
}

/// Index range of the four alarm limits inside a limit array, shared by the
/// GR (6 limits) and CTRL (8 limits) layouts.
const ALARM_LIMITS: std::ops::Range<usize> = 2..6;

/// What a limit slot holds when the record type does not supply its group.
///
/// The three groups do NOT share a seed, and that is the whole of this
/// defect. `dbAccess.c` fills the reply group by group and each filler
/// brings its own initialiser: `get_graphics` starts from `0.0` and
/// `memset`s the buffer when the slot is NULL (`:215`, `:231`, `:243`),
/// `get_control` does the same (`:256`, `:270`, `:282`) — but `get_alarm`
/// starts from `struct dbr_alDouble ald = {epicsNAN, epicsNAN, epicsNAN,
/// epicsNAN}` (`:294`) and copies `ald` into the buffer whether or not the
/// record supplied anything (`:318-323`). It clears the option bit for a
/// missing slot exactly as the other two do, but it never `memset`s, so the
/// four NaNs stay in the reply.
///
/// A CA client therefore reads four NaNs off any DBR_GR/CTRL_DOUBLE or
/// _FLOAT reply whose record type has no `get_alarm_double` — `bo`, `bi`,
/// `mbbi`, `stringin`, `waveform` and the rest — while the same reply's
/// display and control limits read zero. Measured against C softIoc:
/// `caget -d DBR_CTRL_DOUBLE <bo>.HIGH` prints `nan` for all four.
const LIMIT_SEED: [f64; 8] = [
    0.0,      // upper display limit   `get_graphics`
    0.0,      // lower display limit
    f64::NAN, // upper alarm limit     `get_alarm`
    f64::NAN, // upper warning limit
    f64::NAN, // lower warning limit
    f64::NAN, // lower alarm limit
    0.0,      // upper control limit   `get_control`
    0.0,      // lower control limit
];

/// Get the 6 display limits + optional 2 control limits from snapshot.
///
/// Each group comes from its own supply-gated accessor, because each is a
/// SEPARATE rset slot: `dbAccess.c:336-427` clears the option bit of every
/// NULL slot. One `Option` on `DisplayInfo` cannot say which of
/// `get_graphic_double` and `get_alarm_double` the record type supplies,
/// and what an unsupplied slot leaves behind is [`LIMIT_SEED`], not zero.
pub(crate) fn get_limits(
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) -> [f64; 8] {
    let mut limits = LIMIT_SEED;
    if let Some((lower, upper)) = snapshot.graphic_limits() {
        limits[0] = upper;
        limits[1] = lower;
    }
    if let Some((lolo, low, high, hihi)) = snapshot.alarm_limits() {
        limits[2] = hihi;
        limits[3] = high;
        limits[4] = low;
        limits[5] = lolo;
    }
    if n_limits > 6
        && let Some((lower, upper)) = snapshot.control_limits()
    {
        limits[6] = upper;
        limits[7] = lower;
    }
    limits
}

/// The limit block as C's integral GR/CTRL options deliver it.
///
/// Every integral reply is built in two steps and only the first is a float
/// conversion. `dbAccess.c` fills a block of `epicsInt32` for the
/// `DBR_GR_LONG` / `DBR_CTRL_LONG` / `DBR_AL_LONG` options (`:222-223`,
/// `:262-263`, `:305-312`), and `db_access.c` then assigns each field into
/// the reply struct's own width — `dbr_short_t` for the SHORT family,
/// `dbr_char_t` for CHAR (`:450-455`, `:509-514`). That second step is an
/// ordinary C integer conversion, i.e. modular truncation, so the callers
/// narrow this with a plain `as` and must not spend a second saturating
/// float cast. Measured against C softIoc at the R7.0.10 pin, `ai` with
/// `HOPR = 100000, LOW = -40000`:
///
/// ```text
/// caget -d DBR_CTRL_SHORT : Hi disp limit -31072   Lo warn limit  25536
/// caget -d DBR_CTRL_CHAR  : Hi disp limit    -96   Lo warn limit    -64
/// ```
///
/// A direct `100000.0 as i16` gives 32767 and `as i8` gives 127, neither of
/// which C can produce. Routing the float step through `c_cast` also keeps
/// the port's one deviation from C's undefined out-of-range cast in the one
/// place that owns it.
///
/// The alarm four are the only group C guards — `finite(x) ? (epicsInt32) x
/// : 0` (`:305-312`) — because they are the only limits it seeds non-finite
/// (see [`LIMIT_SEED`]). `get_graphics` and `get_control` cast unguarded, so
/// an infinite HOPR saturates here exactly as it would in C's `(epicsInt32)`.
pub(crate) fn limits_as_integers(limits: [f64; 8]) -> [i32; 8] {
    let mut out = limits.map(c_cast::f64_to_i32);
    for i in ALARM_LIMITS {
        if !limits[i].is_finite() {
            out[i] = 0;
        }
    }
    out
}

/// precision(2) + pad(2) + units(8) + n limits as f64.
///
/// Unlike the `DBR_STRING` conversion, this reply carries the memset zero for
/// a NULL `get_precision`: `dbAccess.c` clears `DBR_PRECISION` before the
/// buffer is filled, so the 6 that `getDoubleString` seeds never reaches here.
fn encode_prec_units_limits_f64(
    buf: &mut Vec<u8>,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    let prec = snapshot.precision().unwrap_or(0);
    buf.extend_from_slice(&prec.to_be_bytes());
    buf.extend_from_slice(&[0, 0]); // RISC_pad
    encode_units(buf, snapshot);
    let limits = get_limits(snapshot, n_limits);
    for l in &limits[..n_limits] {
        buf.extend_from_slice(&l.to_be_bytes());
    }
}

/// precision(2) + pad(2) + units(8) + n limits as f32
fn encode_prec_units_limits_f32(
    buf: &mut Vec<u8>,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    let prec = snapshot.precision().unwrap_or(0);
    buf.extend_from_slice(&prec.to_be_bytes());
    buf.extend_from_slice(&[0, 0]); // RISC_pad
    encode_units(buf, snapshot);
    let limits = get_limits(snapshot, n_limits);
    for l in &limits[..n_limits] {
        buf.extend_from_slice(&c_cast::f64_to_f32(*l).to_be_bytes());
    }
}

/// units(8) + n limits as i16.
///
/// See [`limits_as_integers`] for why the narrowing to `dbr_short_t` is a
/// truncation and not a second saturating cast: a `HOPR` of 100000 reaches
/// a `DBR_CTRL_SHORT` client as -31072, measured against C softIoc.
fn encode_units_limits_i16(
    buf: &mut Vec<u8>,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    encode_units(buf, snapshot);
    let limits = limits_as_integers(get_limits(snapshot, n_limits));
    for l in &limits[..n_limits] {
        buf.extend_from_slice(&(*l as i16).to_be_bytes());
    }
}

/// units(8) + n limits as i32
fn encode_units_limits_i32(
    buf: &mut Vec<u8>,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    encode_units(buf, snapshot);
    let limits = limits_as_integers(get_limits(snapshot, n_limits));
    for l in &limits[..n_limits] {
        buf.extend_from_slice(&l.to_be_bytes());
    }
}

/// units(8) + n limits as one byte each (`dbr_char_t`, `db_access.h:40`).
///
/// The narrowing is modular, per [`limits_as_integers`], so a negative limit
/// reaches the wire as its two's-complement byte (-10 as 0xF6) rather than
/// the 0 a direct `(-10.0_f64) as u8` would give, and an out-of-range one
/// keeps C's low byte (100000 as 0xA0, which a client renders -96).
fn encode_units_limits_u8(
    buf: &mut Vec<u8>,
    snapshot: &crate::server::snapshot::Snapshot,
    n_limits: usize,
) {
    encode_units(buf, snapshot);
    let limits = limits_as_integers(get_limits(snapshot, n_limits));
    for l in &limits[..n_limits] {
        buf.push(*l as u8);
    }
}

/// no_str(2) + strs(16x26)
fn encode_enum_metadata(buf: &mut Vec<u8>, snapshot: &crate::server::snapshot::Snapshot) {
    if let Some(ref ei) = snapshot.enums {
        let no_str = ei.strings.len().min(MAX_ENUM_STATES) as u16;
        buf.extend_from_slice(&no_str.to_be_bytes());
        for i in 0..MAX_ENUM_STATES {
            let mut slot = [0u8; MAX_ENUM_STRING_SIZE];
            if let Some(s) = ei.strings.get(i) {
                let bytes = s.as_bytes();
                let len = bytes.len().min(MAX_ENUM_STRING_SIZE - 1);
                slot[..len].copy_from_slice(&bytes[..len]);
            }
            buf.extend_from_slice(&slot);
        }
    } else {
        // No enum info — zero everything (backward compatible)
        buf.extend_from_slice(&0u16.to_be_bytes());
        buf.extend_from_slice(&[0u8; MAX_ENUM_STATES * MAX_ENUM_STRING_SIZE]);
    }
}

// ---------------------------------------------------------------------------
// Decode (deserialize) DBR wire bytes → Snapshot
// ---------------------------------------------------------------------------

use crate::server::snapshot::*;

fn read_u16(data: &[u8], off: usize) -> CaResult<u16> {
    if off + 2 > data.len() {
        return Err(CaError::Protocol("buffer too short for u16".into()));
    }
    Ok(u16::from_be_bytes([data[off], data[off + 1]]))
}

fn read_i16(data: &[u8], off: usize) -> CaResult<i16> {
    if off + 2 > data.len() {
        return Err(CaError::Protocol("buffer too short for i16".into()));
    }
    Ok(i16::from_be_bytes([data[off], data[off + 1]]))
}

fn read_u32(data: &[u8], off: usize) -> CaResult<u32> {
    if off + 4 > data.len() {
        return Err(CaError::Protocol("buffer too short for u32".into()));
    }
    Ok(u32::from_be_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
    ]))
}

fn read_i32(data: &[u8], off: usize) -> CaResult<i32> {
    if off + 4 > data.len() {
        return Err(CaError::Protocol("buffer too short for i32".into()));
    }
    Ok(i32::from_be_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
    ]))
}

fn read_f32(data: &[u8], off: usize) -> CaResult<f32> {
    if off + 4 > data.len() {
        return Err(CaError::Protocol("buffer too short for f32".into()));
    }
    Ok(f32::from_be_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
    ]))
}

fn read_f64(data: &[u8], off: usize) -> CaResult<f64> {
    if off + 8 > data.len() {
        return Err(CaError::Protocol("buffer too short for f64".into()));
    }
    Ok(f64::from_be_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
        data[off + 4],
        data[off + 5],
        data[off + 6],
        data[off + 7],
    ]))
}

/// Decode a NUL-terminated fixed-width CA string field into a lossy `String`.
/// Used for metadata **labels** (units, enum-state strings) that are internal
/// ASCII-grammar identifiers, not arbitrary wire values — lossy decoding is
/// the documented policy for labels. For string **values** use
/// [`read_pv_string`], which preserves the raw bytes.
/// Decode a NUL-terminated fixed-width CA string field into a byte-preserving
/// [`PvString`]. CA `DBR_STRING` slots are historically Latin-1 / arbitrary
/// bytes; preserving them verbatim (no UTF-8 validation) matches pvxs and
/// keeps a gateway pass-through lossless.
fn read_pv_string(data: &[u8], off: usize, max_len: usize) -> PvString {
    let end = data.len().min(off + max_len);
    if off >= end {
        return PvString::new();
    }
    let slice = &data[off..end];
    let nul = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
    PvString::from_bytes(&slice[..nul])
}

fn epics_secs_to_wall_time(secs: u32, nanos: u32) -> WallTime {
    let unix_secs = secs as u64 + EPICS_UNIX_EPOCH_OFFSET_SECS;
    // Build from the exact wire integers: a `SystemTime` would round `nanos`
    // to 100 ns on Windows, dropping the low nsec a CA TIME response carries.
    WallTime::from_unix(unix_secs, nanos)
}

/// Decode a DBR wire response into a Snapshot.
///
/// This is the inverse of `encode_dbr()`. It parses status/severity, timestamp,
/// display/control metadata, and the value payload from the raw bytes.
pub fn decode_dbr(dbr_type: u16, data: &[u8], count: usize) -> CaResult<Snapshot> {
    // DBR_CLASS_NAME (38): a fixed-40-byte string with the record's
    // recordType. Decoded into Snapshot.class_name so callers can read
    // it without touching `value` (which stays empty/Default).
    // Strict length check — a short payload is a malformed CA frame,
    // not a partial result we should silently truncate to garbage.
    if dbr_type == super::DBR_CLASS_NAME {
        if data.len() < 40 {
            return Err(CaError::Protocol(format!(
                "DBR_CLASS_NAME requires 40-byte payload, got {}",
                data.len()
            )));
        }
        let name = read_pv_string(data, 0, 40);
        let mut snap = Snapshot::new(
            EpicsValue::String(name.clone()),
            0,
            0,
            SystemTime::UNIX_EPOCH,
        );
        snap.class_name = Some(name.as_str_lossy().into_owned());
        return Ok(snap);
    }
    // DBR_STSACK_STRING (37): alarm-acknowledge string. Layout per
    // `dbr_stsack_string` (db_access.h:184-190):
    //   status(2) severity(2) ackt(2) acks(2) value(40) = 48 bytes.
    // The inverse of the `encode_dbr` STSACK_STRING arm — without
    // this the encode/decode pair is asymmetric.
    if dbr_type == super::DBR_STSACK_STRING {
        if data.len() < 48 {
            return Err(CaError::Protocol(format!(
                "DBR_STSACK_STRING requires 48-byte payload, got {}",
                data.len()
            )));
        }
        let status = read_u16(data, 0)?;
        let severity = read_u16(data, 2)?;
        let ackt = read_u16(data, 4)?;
        let acks = read_u16(data, 6)?;
        let value = read_pv_string(data, 8, 40);
        let mut snap = Snapshot::new(
            EpicsValue::String(value),
            status,
            severity,
            SystemTime::UNIX_EPOCH,
        );
        snap.alarm.ackt = Some(ackt);
        snap.alarm.acks = Some(acks);
        return Ok(snap);
    }
    // These bytes came off the CA wire, so the value carrier is the wire's,
    // not the database's: `wire_carrier` is the single owner of that one
    // differing row (`DBR_CHAR` is `epicsUInt8`). Every struct-layout
    // question below — `sts_pad`, `time_pad`, `gr_ctrl_meta_size`,
    // `decode_gr_ctrl`'s arms — already treats `Char` and `UChar` as the
    // same wire form, so the substitution moves the value's signedness and
    // nothing else.
    let native = super::native_type_for_dbr(dbr_type)?.wire_carrier();
    // Guard a truncated metadata-prefixed payload before any decode_*
    // helper slices `&data[meta..]`. `dbr_meta_size` is the exact count
    // of metadata bytes preceding `value[0]` for this (type, native) — it
    // equals the offset `decode_sts` / `decode_time` / `decode_gr_ctrl`
    // advance to (including the latter's unconditional `off`-advancing
    // loops), so this single check makes every value-slice site in-bounds.
    // A short frame is a malformed/hostile CA payload, not a partial
    // result: return `Protocol` rather than panicking with a
    // slice-out-of-bounds (a remotely-triggerable client DoS on the
    // monitor and GET-metadata decode paths). C casts the struct unchecked
    // (heap over-read UB); we reject. For plain values (0..=6) the size is
    // 0, so this is a no-op and `from_bytes_array` handles its own sizing.
    let meta = dbr_meta_size(dbr_type, native);
    if data.len() < meta {
        return Err(CaError::Protocol(format!(
            "DBR type {dbr_type} requires at least {meta} metadata bytes, got {}",
            data.len()
        )));
    }
    match dbr_type {
        0..=6 => {
            let value = EpicsValue::from_bytes_array(native, data, count)?;
            Ok(Snapshot::new(value, 0, 0, SystemTime::UNIX_EPOCH))
        }
        7..=13 => decode_sts(native, data, count),
        14..=20 => decode_time(native, data, count),
        21..=27 => decode_gr_ctrl(native, data, count, false),
        28..=34 => decode_gr_ctrl(native, data, count, true),
        _ => Err(CaError::UnsupportedType(dbr_type)),
    }
}

fn decode_sts(native: DbFieldType, data: &[u8], count: usize) -> CaResult<Snapshot> {
    let status = read_u16(data, 0)?;
    let severity = read_u16(data, 2)?;
    let pad_len = sts_pad(native).len();
    let val_off = 4 + pad_len;
    let value = EpicsValue::from_bytes_array(native, &data[val_off..], count)?;
    Ok(Snapshot::new(
        value,
        status,
        severity,
        SystemTime::UNIX_EPOCH,
    ))
}

fn decode_time(native: DbFieldType, data: &[u8], count: usize) -> CaResult<Snapshot> {
    let status = read_u16(data, 0)?;
    let severity = read_u16(data, 2)?;
    let secs = read_u32(data, 4)?;
    let nanos = read_u32(data, 8)?;
    let timestamp = epics_secs_to_wall_time(secs, nanos);
    let pad_len = time_pad(native).len();
    let val_off = 12 + pad_len;
    let value = EpicsValue::from_bytes_array(native, &data[val_off..], count)?;
    Ok(Snapshot::new(value, status, severity, timestamp))
}

fn decode_gr_ctrl(
    native: DbFieldType,
    data: &[u8],
    count: usize,
    ctrl: bool,
) -> CaResult<Snapshot> {
    let status = read_u16(data, 0)?;
    let severity = read_u16(data, 2)?;
    let mut off = 4;

    let mut display = None;
    let mut control = None;
    let mut enums = None;

    match native {
        DbFieldType::String => {
            off += sts_pad(native).len();
        }
        DbFieldType::Enum => {
            let (ei, new_off) = decode_enum_metadata(data, off)?;
            enums = Some(ei);
            off = new_off;
        }
        DbFieldType::Float => {
            let precision = read_i16(data, off)?;
            off += 4; // precision(2) + pad(2)
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                limits[i] = read_f32(data, off)? as f64;
                off += 4;
            }
            display = Some(DisplayInfo {
                units,
                precision,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
        DbFieldType::Double => {
            let precision = read_i16(data, off)?;
            off += 4; // precision(2) + pad(2)
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                limits[i] = read_f64(data, off)?;
                off += 8;
            }
            display = Some(DisplayInfo {
                units,
                precision,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
        DbFieldType::Short => {
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                limits[i] = read_i16(data, off)? as f64;
                off += 2;
            }
            display = Some(DisplayInfo {
                units,
                precision: 0,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
        // DBF_USHORT promotes to DBR_LONG; decode with the Long GR/CTRL layout.
        DbFieldType::Long | DbFieldType::UShort => {
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                limits[i] = read_i32(data, off)? as f64;
                off += 4;
            }
            display = Some(DisplayInfo {
                units,
                precision: 0,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
        // DBF_UCHAR promotes to DBR_CHAR over CA (identical GR/CTRL wire
        // form: 1-byte limits), so it decodes with the Char layout.
        DbFieldType::Char | DbFieldType::UChar => {
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                if off < data.len() {
                    // Decode as SIGNED i8 → f64 (DBF_CHAR is
                    // epicsInt8 per libca 7cb80d5a1). The previous
                    // `data[off] as f64` route read 0xF6 as 246.0
                    // instead of -10.0, silently flipping signs on
                    // CTRL_CHAR / GR_CHAR negative DRVL/LOPR limits.
                    limits[i] = (data[off] as i8) as f64;
                }
                off += 1;
            }
            off += 1; // RISC_pad
            display = Some(DisplayInfo {
                units,
                precision: 0,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
        // Int64/UInt64/ULong have no CA GR/CTRL type; decode as Double layout
        // (DBF_ULONG promotes to DBR_DOUBLE).
        DbFieldType::Int64 | DbFieldType::UInt64 | DbFieldType::ULong => {
            let precision = read_i16(data, off)?;
            off += 4; // precision(2) + pad(2)
            let units = read_pv_string(data, off, MAX_UNITS_SIZE);
            off += MAX_UNITS_SIZE;
            let n_limits = if ctrl { 8 } else { 6 };
            let mut limits = [0.0f64; 8];
            for i in 0..n_limits {
                limits[i] = read_f64(data, off)?;
                off += 8;
            }
            display = Some(DisplayInfo {
                units,
                precision,
                upper_disp_limit: limits[0],
                lower_disp_limit: limits[1],
                upper_alarm_limit: limits[2],
                upper_warning_limit: limits[3],
                lower_warning_limit: limits[4],
                lower_alarm_limit: limits[5],
                ..Default::default()
            });
            if ctrl {
                control = Some(ControlInfo {
                    upper_ctrl_limit: limits[6],
                    lower_ctrl_limit: limits[7],
                });
            }
        }
    }

    let value = EpicsValue::from_bytes_array(native, &data[off..], count)?;
    let mut snap = Snapshot::new(value, status, severity, SystemTime::UNIX_EPOCH);
    // The CA wire carries no supply mask — `dbAccess.c` clears the option bit
    // BEFORE the reply is filled, so an unsupplied leaf arrives as the memset
    // zero and is indistinguishable from a supplied zero. What a client CAN
    // say is which leaves this reply class carried, and that is the mask: the
    // same rule `Pv::apply_metadata` applies to a bare PV. Assigned by the one
    // owner that mints the blocks, so mask and values cannot disagree.
    snap.properties = crate::server::snapshot::PropertySupport {
        units: display.is_some(),
        precision: display.is_some(),
        graphic_double: display.is_some(),
        alarm_double: display.is_some(),
        control_double: control.is_some(),
        enum_strs: enums.is_some(),
    }
    .narrowed_to_field(snap.value.db_field_type(), false);
    snap.display = display;
    snap.control = control;
    snap.enums = enums;
    Ok(snap)
}

fn decode_enum_metadata(data: &[u8], off: usize) -> CaResult<(EnumInfo, usize)> {
    let no_str = read_u16(data, off)? as usize;
    let mut pos = off + 2;
    let mut strings = Vec::with_capacity(no_str.min(MAX_ENUM_STATES));
    for i in 0..MAX_ENUM_STATES {
        let s = read_pv_string(data, pos, MAX_ENUM_STRING_SIZE);
        if i < no_str {
            strings.push(s);
        }
        pos += MAX_ENUM_STRING_SIZE;
    }
    // Decoding a server's `DBR_GR_ENUM` reply: the `no_str` labels it sent are
    // all a CLIENT has, so they are both its label list and its string table.
    Ok((EnumInfo::new(strings), pos))
}

#[cfg(test)]
mod wire_format_tests {
    use super::*;
    use crate::types::dbr::{
        DBR_CTRL_CHAR, DBR_CTRL_DOUBLE, DBR_DOUBLE, DBR_GR_DOUBLE, DBR_GR_ENUM, DBR_STS_CHAR,
        DBR_STS_DOUBLE, DBR_TIME_DOUBLE, dbr_buffer_size, native_type_for_dbr,
    };

    /// A truncated metadata-prefixed DBR payload must return `Err`, never
    /// panic with a slice-out-of-bounds. Pre-fix `decode_sts` /
    /// `decode_time` / `decode_gr_ctrl` sliced `&data[meta..]` after
    /// proving only `data.len() >= 4`/`>= 12`, so a short frame from the
    /// monitor / GET-metadata paths panicked — a remotely-triggerable
    /// client DoS. Boundary per metadata category: exactly
    /// `dbr_meta_size - 1` bytes is the largest payload that still must be
    /// rejected; a full metadata payload still decodes.
    #[test]
    fn decode_dbr_truncated_metadata_rejected_not_panic() {
        // One representative per metadata category (STS pad, TIME pad,
        // GR enum-string region, CTRL char limits) plus the cited
        // STS_DOUBLE / STS_CHAR / TIME_DOUBLE cases.
        for dbr_type in [
            DBR_STS_DOUBLE,
            DBR_STS_CHAR,
            DBR_TIME_DOUBLE,
            DBR_GR_ENUM,
            DBR_CTRL_CHAR,
        ] {
            let native = native_type_for_dbr(dbr_type).unwrap();
            let meta = dbr_meta_size(dbr_type, native);
            assert!(meta >= 1, "metadata types have a non-zero prefix");

            // Every length in [0, meta) must be rejected (not panic).
            for len in [0usize, meta - 1] {
                let truncated = vec![0u8; len];
                let r = decode_dbr(dbr_type, &truncated, 1);
                assert!(
                    matches!(r, Err(CaError::Protocol(_))),
                    "dbr_type {dbr_type}: {len}-byte payload (meta={meta}) must be Protocol Err, got {r:?}"
                );
            }

            // A full metadata + value payload still decodes.
            let full = vec![0u8; meta + 64];
            assert!(
                decode_dbr(dbr_type, &full, 1).is_ok(),
                "dbr_type {dbr_type}: full meta+value payload must decode"
            );
        }
    }

    /// Structural invariant: the encoded DBR length must equal
    /// `dbr_buffer_size` for every (dbr_type, native, count). This pins
    /// the sizer ([`dbr_meta_size`]) to the bytes the serializer
    /// actually writes, so the two can never drift again. Covers plain /
    /// STS / TIME / GR / CTRL layers for all seven CA native types, at
    /// scalar and multi-element counts.
    #[test]
    fn metadata_matches_encoded_length() {
        // (native, scalar value, 3-element array value)
        let cases: &[(DbFieldType, EpicsValue, EpicsValue)] = &[
            (
                DbFieldType::String,
                EpicsValue::String("x".into()),
                EpicsValue::StringArray(vec!["x".into(), "y".into(), "z".into()]),
            ),
            (
                DbFieldType::Short,
                EpicsValue::Short(7),
                EpicsValue::ShortArray(vec![1, 2, 3]),
            ),
            (
                DbFieldType::Float,
                EpicsValue::Float(1.5),
                EpicsValue::FloatArray(vec![1.0, 2.0, 3.0]),
            ),
            (
                DbFieldType::Enum,
                EpicsValue::Enum(2),
                EpicsValue::EnumArray(vec![0, 1, 2]),
            ),
            (
                DbFieldType::Char,
                EpicsValue::Char(9),
                EpicsValue::CharArray(vec![1, 2, 3]),
            ),
            (
                DbFieldType::Long,
                EpicsValue::Long(11),
                EpicsValue::LongArray(vec![1, 2, 3]),
            ),
            (
                DbFieldType::Double,
                EpicsValue::Double(2.5),
                EpicsValue::DoubleArray(vec![1.0, 2.0, 3.0]),
            ),
        ];
        let now = SystemTime::now();
        for (native, scalar, array) in cases {
            let base = *native as u16;
            // layer 0=plain, 1=STS, 2=TIME, 3=GR, 4=CTRL
            for layer in 0u16..=4 {
                let dbr_type = base + 7 * layer;
                for (value, count) in [(scalar, 1usize), (array, 3usize)] {
                    let encoded = serialize_dbr(dbr_type, value, 0, 0, now)
                        .expect("serialize_dbr")
                        .len();
                    let sized = dbr_buffer_size(dbr_type, *native, count);
                    assert_eq!(
                        encoded, sized,
                        "len mismatch dbr_type={dbr_type} native={native:?} count={count}"
                    );
                }
            }
        }
    }

    /// The server-driven `encode_dbr` path (real metadata) must size the
    /// same as `dbr_buffer_size` — proving both encoders share the one
    /// `dbr_meta_size` owner, not just the zeroed `serialize_dbr` path.
    #[test]
    fn encode_dbr_length_matches_sizer() {
        use crate::server::snapshot::Snapshot;
        let layers = [
            DBR_DOUBLE,
            DBR_STS_DOUBLE,
            DBR_TIME_DOUBLE,
            DBR_GR_DOUBLE,
            DBR_CTRL_DOUBLE,
        ];
        let snap = Snapshot::new(EpicsValue::Double(3.25), 0, 0, SystemTime::now());
        for dbr_type in layers {
            let encoded = encode_dbr(dbr_type, &snap).expect("encode_dbr").len();
            let sized = dbr_buffer_size(dbr_type, DbFieldType::Double, 1);
            assert_eq!(
                encoded, sized,
                "encode_dbr len mismatch dbr_type={dbr_type}"
            );
        }
    }

    /// `DBR_STS_DOUBLE` (type 13) wire layout is
    /// `status(2) + severity(2) + RISC_pad(4) + value(8)` — the
    /// `RISC_pad` is `dbr_long_t` (epicsInt32, 4 bytes) per
    /// `db_access.h:233-238`. Total 16 bytes, value at offset 8.
    #[test]
    fn sts_double_value_at_offset_8() {
        let v = EpicsValue::Double(3.5);
        let buf = serialize_dbr(
            super::super::DBR_STS_DOUBLE,
            &v,
            1,
            2,
            SystemTime::UNIX_EPOCH,
        )
        .unwrap();
        assert_eq!(
            buf.len(),
            16,
            "STS_DOUBLE must be 16 bytes (4 meta + 4 pad + 8 value)"
        );
        // status(2) + severity(2)
        assert_eq!(&buf[0..2], &1u16.to_be_bytes());
        assert_eq!(&buf[2..4], &2u16.to_be_bytes());
        // RISC_pad(4) — all zero
        assert_eq!(&buf[4..8], &[0, 0, 0, 0]);
        // value(8) at offset 8
        assert_eq!(&buf[8..16], &3.5f64.to_be_bytes());
    }

    /// STS_DOUBLE encode→decode round-trips with the 4-byte pad.
    #[test]
    fn sts_double_round_trip() {
        let v = EpicsValue::Double(-12.75);
        let buf = serialize_dbr(
            super::super::DBR_STS_DOUBLE,
            &v,
            7,
            3,
            SystemTime::UNIX_EPOCH,
        )
        .unwrap();
        let snap = decode_dbr(super::super::DBR_STS_DOUBLE, &buf, 1).unwrap();
        assert_eq!(snap.value, EpicsValue::Double(-12.75));
        assert_eq!(snap.alarm.status, 7);
        assert_eq!(snap.alarm.severity, 3);
    }

    /// Cross-check: STS_CHAR keeps its 1-byte `RISC_pad`
    /// (`dbr_sts_char`, db_access.h:218-223) — value at offset 5.
    #[test]
    fn sts_char_value_at_offset_5() {
        let v = EpicsValue::Char(0x41);
        let buf =
            serialize_dbr(super::super::DBR_STS_CHAR, &v, 0, 0, SystemTime::UNIX_EPOCH).unwrap();
        assert_eq!(
            buf.len(),
            6,
            "STS_CHAR must be 6 bytes (4 meta + 1 pad + 1 value)"
        );
        assert_eq!(buf[4], 0, "RISC_pad");
        assert_eq!(buf[5], 0x41, "value at offset 5");
    }

    /// STS_SHORT has no RISC pad — value immediately after the
    /// 4-byte status/severity header (`dbr_sts_short`).
    #[test]
    fn sts_short_no_pad() {
        let v = EpicsValue::Short(0x1234);
        let buf = serialize_dbr(
            super::super::DBR_STS_SHORT,
            &v,
            0,
            0,
            SystemTime::UNIX_EPOCH,
        )
        .unwrap();
        assert_eq!(buf.len(), 6, "STS_SHORT is 4 meta + 2 value, no pad");
        assert_eq!(&buf[4..6], &0x1234i16.to_be_bytes());
    }

    /// `DBR_STSACK_STRING` (37) must decode, not just encode.
    /// Layout: status(2) severity(2) ackt(2) acks(2) value(40).
    #[test]
    fn stsack_string_decodes() {
        let mut buf = Vec::with_capacity(48);
        buf.extend_from_slice(&5u16.to_be_bytes()); // status
        buf.extend_from_slice(&2u16.to_be_bytes()); // severity
        buf.extend_from_slice(&1u16.to_be_bytes()); // ackt
        buf.extend_from_slice(&3u16.to_be_bytes()); // acks
        let mut value = [0u8; 40];
        value[..5].copy_from_slice(b"HIHI\0");
        buf.extend_from_slice(&value);
        assert_eq!(buf.len(), 48);

        let snap = decode_dbr(super::super::DBR_STSACK_STRING, &buf, 1).unwrap();
        assert_eq!(snap.value, EpicsValue::String("HIHI".into()));
        assert_eq!(snap.alarm.status, 5);
        assert_eq!(snap.alarm.severity, 2);
        assert_eq!(snap.alarm.ackt, Some(1));
        assert_eq!(snap.alarm.acks, Some(3));
    }

    /// A short STSACK_STRING payload is a malformed frame, rejected.
    #[test]
    fn stsack_string_short_payload_errors() {
        let buf = [0u8; 16];
        assert!(decode_dbr(super::super::DBR_STSACK_STRING, &buf, 1).is_err());
    }
}

#[cfg(test)]
mod r57_string_precision_tests {
    //! Numeric→DBR_STRING must match C `cvtDoubleToString` /
    //! `cvtFloatToString` (libCom cvtFast.c), including the round-half-up
    //! fast path and the `%.*f` / `%*.*e` overflow fallbacks.
    use super::{cvt_double_to_string, cvt_float_to_string};

    #[test]
    fn double_fixed_point_applies_precision() {
        assert_eq!(cvt_double_to_string(3.14, 3), "3.140");
        assert_eq!(cvt_double_to_string(1.0, 3), "1.000");
        assert_eq!(cvt_double_to_string(1.0, 0), "1");
        assert_eq!(cvt_double_to_string(0.0, 3), "0.000");
        assert_eq!(cvt_double_to_string(-3.14159, 2), "-3.14");
        assert_eq!(cvt_double_to_string(123.456, 2), "123.46");
        assert_eq!(cvt_double_to_string(123.456, 0), "123");
    }

    #[test]
    fn double_fast_path_rounds_half_up() {
        // C cvtFast.c uses `(fraction + 5) / 10` — round half *up*, unlike
        // Rust's default round-half-to-even.
        assert_eq!(cvt_double_to_string(0.125, 2), "0.13");
        assert_eq!(cvt_double_to_string(2.5, 0), "3");
        assert_eq!(cvt_double_to_string(0.5, 0), "1");
    }

    #[test]
    fn double_exp_path_for_huge_or_highprec() {
        // |val| > 1e16 → "%*.*e" with width = precision + 7.
        assert_eq!(cvt_double_to_string(1e20, 6), " 1.000000e+20");
        // precision > 8 → exponential, precision clamped to 17.
        assert_eq!(cvt_double_to_string(3.14159, 10), " 3.1415900000e+00");
    }

    #[test]
    fn double_mid_range_uses_fixed_with_clamped_prec() {
        // 1e7 < |val| <= 1e16 → "%.*f" with precision clamped to 3.
        assert_eq!(cvt_double_to_string(5e7, 0), "50000000");
    }

    #[test]
    fn double_nan_inf_glibc_spelling() {
        // NaN takes the `%.*f` branch (NaN compares false against the e-path
        // thresholds) → unpadded glibc "nan".
        assert_eq!(cvt_double_to_string(f64::NAN, 3), "nan");
        // ±Inf exceeds 1e16 → "%*.*e" branch: glibc spelling right-justified
        // in width = precision + 7 (= 13 here), matching C `cvtDoubleToString`.
        assert_eq!(cvt_double_to_string(f64::INFINITY, 6), "          inf");
        assert_eq!(cvt_double_to_string(f64::NEG_INFINITY, 6), "         -inf");
        assert_eq!(cvt_double_to_string(f64::INFINITY, 6).trim(), "inf");
    }

    #[test]
    fn float_fixed_point_applies_precision() {
        assert_eq!(cvt_float_to_string(3.5_f32, 2), "3.50");
        assert_eq!(cvt_float_to_string(1.0_f32, 3), "1.000");
        assert_eq!(cvt_float_to_string(-2.0_f32, 1), "-2.0");
    }
}

#[cfg(test)]
mod r58_enum_label_tests {
    //! An enum value requested as a `*_STRING` DBR must render the
    //! state label (C `getEnumString` → `get_enum_str`), not the index.
    use super::{EpicsValue, convert_value_to_dbr_string};
    use crate::server::snapshot::{EnumInfo, Snapshot};
    use std::time::SystemTime;

    fn snap_with_enum(value: EpicsValue, labels: &[&str]) -> Snapshot {
        let mut s = Snapshot::new(value, 0, 0, SystemTime::UNIX_EPOCH);
        s.enums = Some(EnumInfo::new(labels.iter().map(|x| (*x).into()).collect()));
        s
    }

    #[test]
    fn enum_renders_label_not_index() {
        let s = snap_with_enum(EpicsValue::Enum(1), &["Off", "On"]);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("On".into())
        );
        let s0 = snap_with_enum(EpicsValue::Enum(0), &["Off", "On"]);
        assert_eq!(
            convert_value_to_dbr_string(&s0.value, &s0).unwrap(),
            EpicsValue::String("Off".into())
        );
    }

    #[test]
    fn enum_array_renders_labels() {
        let s = snap_with_enum(EpicsValue::EnumArray(vec![0, 1, 0]), &["Off", "On"]);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::StringArray(vec!["Off".into(), "On".into(), "Off".into()])
        );
    }

    /// CORRECTED (was `enum_out_of_range_falls_back_to_index`, asserting
    /// `"5"`). No C conversion row renders an enum as its number. A channel
    /// whose string table is a plain label list has no out-of-range sentinel —
    /// C `getMenuString` fails the `dbGet` with `S_db_badChoice` — so the port
    /// answers empty. Ground truth, compiled `softIoc`: an `mbbi` put to an
    /// index with no state string answers `caget -t` with an empty line.
    #[test]
    fn enum_out_of_range_renders_the_overflow_never_the_index() {
        let s = snap_with_enum(EpicsValue::Enum(5), &["Off", "On"]);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("".into())
        );
    }

    /// The record sentinel reaches the wire when the field HAS one: `mbbi`'s
    /// `get_enum_str` answers `"Illegal Value"` past state 15
    /// (`mbbiRecord.c:252`). Measured: `caput E:MBBI.VAL 20` then
    /// `caget -t E:MBBI` prints `Illegal Value`.
    #[test]
    fn enum_past_the_slots_renders_the_records_sentinel() {
        use crate::server::snapshot::EnumStringForm;
        let mut s = Snapshot::new(EpicsValue::Enum(20), 0, 0, SystemTime::UNIX_EPOCH);
        let mut slots: Vec<crate::types::PvString> = vec!["zero".into(), "one".into()];
        slots.resize(16, crate::types::PvString::new());
        s.enums = Some(EnumInfo::with_string_form(
            vec!["zero".into(), "one".into()],
            EnumStringForm::states(slots, "Illegal Value".into()),
        ));
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("Illegal Value".into())
        );
    }

    /// An UNDEFINED state inside the slot range is the empty string, not the
    /// sentinel and not the index: C `strncpy`s the empty state
    /// (`mbbiRecord.c:246-250`). Measured: `caput E:MBBI.VAL 5` -> `caget -t`
    /// prints an empty line, while `caget -t -n` still prints `5`.
    #[test]
    fn enum_undefined_slot_renders_empty() {
        use crate::server::snapshot::EnumStringForm;
        let mut s = Snapshot::new(EpicsValue::Enum(5), 0, 0, SystemTime::UNIX_EPOCH);
        let mut slots: Vec<crate::types::PvString> = vec!["zero".into(), "one".into()];
        slots.resize(16, crate::types::PvString::new());
        s.enums = Some(EnumInfo::with_string_form(
            vec!["zero".into(), "one".into()],
            EnumStringForm::states(slots, "Illegal Value".into()),
        ));
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("".into())
        );
    }

    /// CORRECTED (was `enum_without_metadata_falls_back_to_index`, asserting
    /// `"1"`). A channel with no enum source at all is `S_db_noRSET` in C — an
    /// ERROR, never the number. Empty is the closest the port can answer
    /// without inventing a string no C IOC emits.
    #[test]
    fn enum_without_metadata_renders_empty_never_the_index() {
        let s = Snapshot::new(EpicsValue::Enum(1), 0, 0, SystemTime::UNIX_EPOCH);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("".into())
        );
    }
}

#[cfg(test)]
mod r17_1_negative_precision_tests {
    //! R17-1: a NEGATIVE `PREC` is REINTERPRETED as `epicsUInt16`, never
    //! clamped. C `getDoubleString` (dbConvert.c:786) passes the `long
    //! precision` its `get_precision` RSET returned straight into
    //! `cvtDoubleToString(double, char*, epicsUInt16 precision)`, and the
    //! implicit conversion makes `PREC=-1` a precision of 65535 — the
    //! `precision > 8` branch (cvtFast.c:111), capped at 17, `%*.*e`.
    //!
    //! Ground truth, compiled libCom (`cvtDoubleToString(3.7, b, (short)-1)`):
    //! ` 3.70000000000000018e+00`; `cvtFloatToString(3.7f, b, (short)-1)`:
    //! `3.700000047684e+00` (its own cap is 12).
    use super::{EpicsValue, convert_value_to_dbr_string};
    use crate::server::snapshot::{DisplayInfo, PropertySupport, Snapshot};
    use std::time::SystemTime;

    /// A channel whose record type SUPPLIES `get_precision` — the mask says so,
    /// because `display.is_some()` cannot: every snapshot carries a
    /// `DisplayInfo` for its DESC leaf.
    fn snap_with_prec(value: EpicsValue, precision: i16) -> Snapshot {
        let mut s = Snapshot::new(value, 0, 0, SystemTime::UNIX_EPOCH);
        s.display = Some(DisplayInfo {
            precision,
            ..Default::default()
        });
        s.properties = PropertySupport {
            precision: true,
            ..PropertySupport::NONE
        };
        s
    }

    #[test]
    fn double_with_negative_prec_renders_seventeen_digit_exponential() {
        let s = snap_with_prec(EpicsValue::Double(3.7), -1);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String(" 3.70000000000000018e+00".into()),
            "PREC=-1 is epicsUInt16 65535, not a clamp to 0"
        );
    }

    #[test]
    fn float_with_negative_prec_renders_twelve_digit_exponential() {
        let s = snap_with_prec(EpicsValue::Float(3.7), -1);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("3.700000047684e+00".into()),
            "cvtFloatToString caps the reinterpreted precision at 12"
        );
    }

    #[test]
    fn non_negative_prec_is_unchanged() {
        let s = snap_with_prec(EpicsValue::Double(3.7), 2);
        assert_eq!(
            convert_value_to_dbr_string(&s.value, &s).unwrap(),
            EpicsValue::String("3.70".into())
        );
    }
}

#[cfg(test)]
mod alarm_limit_seed_tests {
    //! What a DBR_GR/CTRL reply carries in its four alarm-limit slots when
    //! the record type has NO `get_alarm_double` — the `bo`, `bi`, `mbbi`,
    //! `stringin`, `waveform` case.
    //!
    //! C answers it in two different ways depending on the DBR class, and
    //! neither is "zero for both": `get_alarm` seeds `ald` with four
    //! `epicsNAN` (`dbAccess.c:294`) and copies them into the reply even
    //! when the slot is missing, so the DOUBLE and FLOAT classes carry NaN;
    //! the LONG arm converts each through `finite(x) ? (epicsInt32) x : 0`
    //! (`:305-312`), so the SHORT, LONG and CHAR classes carry 0. The
    //! display and control groups are zero on every class, because their
    //! own fillers seed 0.0 and `memset` the missing case.
    //!
    //! Measured against C softIoc at the R7.0.10 pin:
    //! `caget -d DBR_CTRL_DOUBLE <bo>.HIGH` reports all four as `nan`.
    //!
    //! One case per boundary: supplied vs unsupplied, float class vs
    //! integer class, and the non-finite value an integer class must NOT
    //! saturate.
    use super::{decode_dbr, encode_dbr};
    use crate::server::snapshot::{ControlInfo, DisplayInfo, PropertySupport, Snapshot};
    use crate::types::EpicsValue;
    use crate::types::dbr::{
        DBR_CTRL_CHAR, DBR_CTRL_DOUBLE, DBR_CTRL_FLOAT, DBR_CTRL_LONG, DBR_CTRL_SHORT,
        DBR_GR_DOUBLE,
    };
    use std::time::SystemTime;

    /// A `bo`-shaped channel: units, precision, graphic and control limits,
    /// but NO `get_alarm_double` (`record_trait.rs::default_property_support`
    /// gives `bo` `alarm_double: false`). The `DisplayInfo` still carries
    /// alarm-limit fields — every snapshot does — and the point of the gate
    /// is that they must not reach the wire.
    fn bo_shaped(value: EpicsValue) -> Snapshot {
        let mut s = Snapshot::new(value, 0, 0, SystemTime::UNIX_EPOCH);
        s.display = Some(DisplayInfo {
            upper_disp_limit: 100.0,
            lower_disp_limit: 0.0,
            // Deliberately non-zero: if the encoder ever read these past
            // the gate the assertions below would see 7.0, not NaN.
            upper_alarm_limit: 7.0,
            upper_warning_limit: 7.0,
            lower_warning_limit: 7.0,
            lower_alarm_limit: 7.0,
            ..Default::default()
        });
        s.control = Some(ControlInfo {
            upper_ctrl_limit: 100.0,
            lower_ctrl_limit: 0.0,
        });
        s.properties = PropertySupport {
            units: true,
            precision: true,
            graphic_double: true,
            control_double: true,
            alarm_double: false,
            enum_strs: false,
        };
        s
    }

    /// The same channel with the slot supplied, and one alarm limit set to
    /// `f64::INFINITY` — the value C's `finite` guard sends to 0 on an
    /// integer class where a bare Rust `as i32` would saturate to `i32::MAX`.
    fn alarm_supplied(hihi: f64) -> Snapshot {
        let mut s = bo_shaped(EpicsValue::Double(1.0));
        s.display = Some(DisplayInfo {
            upper_disp_limit: 100.0,
            lower_disp_limit: 0.0,
            upper_alarm_limit: hihi,
            upper_warning_limit: 80.0,
            lower_warning_limit: 20.0,
            lower_alarm_limit: 10.0,
            ..Default::default()
        });
        s.properties.alarm_double = true;
        s
    }

    /// `(hihi, high, low, lolo)` as a client reads them back off the wire.
    fn wire_alarm_limits(dbr: u16, snap: &Snapshot) -> (f64, f64, f64, f64) {
        let bytes = encode_dbr(dbr, snap).unwrap();
        let d = decode_dbr(dbr, &bytes, 1)
            .unwrap()
            .display
            .expect("a GR/CTRL reply always decodes a DisplayInfo");
        (
            d.upper_alarm_limit,
            d.upper_warning_limit,
            d.lower_warning_limit,
            d.lower_alarm_limit,
        )
    }

    #[test]
    fn a_record_with_no_alarm_slot_sends_four_nans_on_the_double_classes() {
        for dbr in [DBR_CTRL_DOUBLE, DBR_GR_DOUBLE] {
            let (hihi, high, low, lolo) =
                wire_alarm_limits(dbr, &bo_shaped(EpicsValue::Double(1.0)));
            for (name, v) in [("hihi", hihi), ("high", high), ("low", low), ("lolo", lolo)] {
                assert!(v.is_nan(), "dbr {dbr}: {name} is {v}, C sends nan");
            }
        }
    }

    #[test]
    fn the_float_class_carries_the_nan_through_the_narrowing_convert() {
        // `epicsConvertDoubleToFloat` returns `(float) value` unchanged for a
        // non-finite input (`epicsConvert.c:22-23`), so the f32 slots are NaN
        // too — not the 0 a saturating narrowing would give.
        let (hihi, high, low, lolo) =
            wire_alarm_limits(DBR_CTRL_FLOAT, &bo_shaped(EpicsValue::Float(1.0)));
        for (name, v) in [("hihi", hihi), ("high", high), ("low", low), ("lolo", lolo)] {
            assert!(v.is_nan(), "{name} is {v}, C sends nan");
        }
    }

    #[test]
    fn the_integer_classes_send_zero_for_the_same_record() {
        // `db_access.c` asks the integer classes for `DBR_AL_LONG` (`:444`,
        // `:502`, `:529`), whose filler converts each NaN to 0.
        for (dbr, value) in [
            (DBR_CTRL_LONG, EpicsValue::Long(1)),
            (DBR_CTRL_SHORT, EpicsValue::Short(1)),
            (DBR_CTRL_CHAR, EpicsValue::Char(1)),
        ] {
            let (hihi, high, low, lolo) = wire_alarm_limits(dbr, &bo_shaped(value));
            assert_eq!(
                (hihi, high, low, lolo),
                (0.0, 0.0, 0.0, 0.0),
                "dbr {dbr}: C's DBR_AL_LONG arm sends 0, not nan"
            );
        }
    }

    #[test]
    fn the_display_and_control_groups_stay_zero_when_unsupplied() {
        // Only the alarm group is seeded non-finite. A record type with no
        // `get_graphic_double` / `get_control_double` still reads back 0,
        // because C `memset`s those two groups (`dbAccess.c:231`, `:270`).
        let mut s = bo_shaped(EpicsValue::Double(1.0));
        s.properties.graphic_double = false;
        s.properties.control_double = false;
        let bytes = encode_dbr(DBR_CTRL_DOUBLE, &s).unwrap();
        let back = decode_dbr(DBR_CTRL_DOUBLE, &bytes, 1).unwrap();
        let d = back.display.unwrap();
        let c = back.control.unwrap();
        assert_eq!(d.upper_disp_limit, 0.0);
        assert_eq!(d.lower_disp_limit, 0.0);
        assert_eq!(c.upper_ctrl_limit, 0.0);
        assert_eq!(c.lower_ctrl_limit, 0.0);
    }

    #[test]
    fn a_supplied_slot_still_sends_the_records_own_limits() {
        assert_eq!(
            wire_alarm_limits(DBR_CTRL_DOUBLE, &alarm_supplied(90.0)),
            (90.0, 80.0, 20.0, 10.0),
            "the seed must not survive a record that supplies the slot"
        );
        assert_eq!(
            wire_alarm_limits(DBR_CTRL_LONG, &alarm_supplied(90.0)),
            (90.0, 80.0, 20.0, 10.0),
            "the integer arm converts, it does not blank"
        );
    }

    #[test]
    fn an_infinite_supplied_limit_is_zero_on_an_integer_class() {
        // C guards on `finite`, which is false for +/-inf as well as NaN, so
        // both go to 0. A bare `as i32` would saturate to `i32::MAX` here.
        let (hihi, ..) = wire_alarm_limits(DBR_CTRL_LONG, &alarm_supplied(f64::INFINITY));
        assert_eq!(hihi, 0.0, "finite(inf) is false, so C writes 0");
        // The double class has no such guard and carries the raw value.
        let (hihi, ..) = wire_alarm_limits(DBR_CTRL_DOUBLE, &alarm_supplied(f64::INFINITY));
        assert!(hihi.is_infinite(), "the DBR_AL_DOUBLE arm copies raw");
    }

    #[test]
    fn the_ctrl_double_wire_bytes_are_the_ones_c_softioc_sends() {
        // status(2) + severity(2) + precision(2) + RISC_pad(2) + units(8),
        // then eight f64 limits: upper/lower display, hihi, high, low, lolo,
        // upper/lower control. Asserted on the bytes rather than through the
        // decoder so this case cannot pass on a symmetric encode/decode bug.
        let bytes = encode_dbr(DBR_CTRL_DOUBLE, &bo_shaped(EpicsValue::Double(1.0))).unwrap();
        let at = |i: usize| {
            let off = 16 + i * 8;
            f64::from_be_bytes(bytes[off..off + 8].try_into().unwrap())
        };
        assert_eq!(at(0), 100.0, "upper display");
        assert_eq!(at(1), 0.0, "lower display");
        for i in 2..6 {
            assert!(at(i).is_nan(), "limit {i} must be nan on the wire");
        }
        assert_eq!(at(6), 100.0, "upper control");
        assert_eq!(at(7), 0.0, "lower control");
    }
}

#[cfg(test)]
mod integer_limit_narrowing_tests {
    //! An out-of-range limit on an integral DBR class TRUNCATES to the reply
    //! struct's width, it does not saturate.
    //!
    //! C narrows in two steps and only the first is a float conversion:
    //! `dbAccess.c` produces `epicsInt32` for the `*_LONG` options, then the
    //! struct assignment in `db_access.c` converts that to `dbr_short_t` /
    //! `dbr_char_t`. The port had a single saturating `f64 as i16` / `as i8`,
    //! which can reach 32767 and 127 — values C cannot produce.
    //!
    //! Measured against C softIoc at the R7.0.10 pin, `ai` with
    //! `HOPR = 100000, LOPR = -100000, HIGH = 40000, LOW = -40000` and every
    //! `*SV` set so the alarm slot is supplied.
    use super::{encode_dbr, limits_as_integers};
    use crate::server::snapshot::{ControlInfo, DisplayInfo, PropertySupport, Snapshot};
    use crate::types::EpicsValue;
    use crate::types::dbr::{DBR_CTRL_CHAR, DBR_CTRL_LONG, DBR_CTRL_SHORT};
    use std::time::SystemTime;

    /// An `ai`-shaped channel supplying every numeric slot, with the limits
    /// the A/B database used.
    fn ai_big(value: EpicsValue) -> Snapshot {
        let mut s = Snapshot::new(value, 0, 0, SystemTime::UNIX_EPOCH);
        s.display = Some(DisplayInfo {
            upper_disp_limit: 100000.0,
            lower_disp_limit: -100000.0,
            upper_alarm_limit: 100000.0,
            upper_warning_limit: 40000.0,
            lower_warning_limit: -40000.0,
            lower_alarm_limit: -100000.0,
            ..Default::default()
        });
        s.control = Some(ControlInfo {
            upper_ctrl_limit: 100000.0,
            lower_ctrl_limit: -100000.0,
        });
        s.properties = PropertySupport {
            units: true,
            precision: true,
            graphic_double: true,
            control_double: true,
            alarm_double: true,
            enum_strs: false,
        };
        s
    }

    #[test]
    fn the_short_family_keeps_the_low_sixteen_bits() {
        // status(2) + severity(2) + units[8], then eight i16 limits.
        let bytes = encode_dbr(DBR_CTRL_SHORT, &ai_big(EpicsValue::Short(1))).unwrap();
        let at = |i: usize| i16::from_be_bytes(bytes[12 + i * 2..14 + i * 2].try_into().unwrap());
        assert_eq!(at(0), -31072, "100000 truncates, C prints -31072");
        assert_eq!(at(1), 31072, "-100000 truncates");
        assert_eq!(at(3), 40000_i32 as i16, "40000 already exceeds i16");
        assert_eq!(at(4), 25536, "-40000 truncates, C prints 25536");
    }

    #[test]
    fn the_char_family_keeps_the_low_byte() {
        // status(2) + severity(2) + units[8], then eight raw bytes.
        let bytes = encode_dbr(DBR_CTRL_CHAR, &ai_big(EpicsValue::Char(1))).unwrap();
        assert_eq!(bytes[12], 0xA0, "100000 & 0xff; a client renders it -96");
        assert_eq!(bytes[13], 0x60, "-100000 & 0xff, rendered 96");
        assert_eq!(bytes[16], 0xC0, "-40000 & 0xff, rendered -64");
    }

    #[test]
    fn a_negative_limit_inside_the_byte_is_its_twos_complement() {
        // The case the old saturating path got right for the wrong reason:
        // a direct `(-10.0_f64) as u8` is 0, `as i8 as u8` is 0xF6, and so is
        // the two-step. Kept as a boundary so the modular rule cannot regress
        // into a clamp that only looks right for small negatives.
        let mut s = ai_big(EpicsValue::Char(1));
        s.display.as_mut().unwrap().lower_disp_limit = -10.0;
        let bytes = encode_dbr(DBR_CTRL_CHAR, &s).unwrap();
        assert_eq!(bytes[13], 0xF6);
    }

    #[test]
    fn the_long_family_is_the_intermediate_itself_and_does_not_truncate() {
        let bytes = encode_dbr(DBR_CTRL_LONG, &ai_big(EpicsValue::Long(1))).unwrap();
        let at = |i: usize| i32::from_be_bytes(bytes[12 + i * 4..16 + i * 4].try_into().unwrap());
        assert_eq!(at(0), 100000);
        assert_eq!(at(1), -100000);
    }

    #[test]
    fn only_the_alarm_group_is_guarded_against_a_non_finite_limit() {
        // C's `finite` guard is in the `DBR_AL_LONG` arm alone. An infinite
        // display or control limit reaches the unguarded `(epicsInt32)` cast,
        // which this port resolves by saturation rather than C's UB.
        let mut limits = [f64::INFINITY; 8];
        limits[1] = f64::NEG_INFINITY;
        let out = limits_as_integers(limits);
        assert_eq!(out[0], i32::MAX, "display limits are cast unguarded");
        assert_eq!(out[1], i32::MIN);
        assert_eq!(&out[2..6], &[0, 0, 0, 0], "the alarm four are guarded");
        assert_eq!(out[6], i32::MAX, "control limits are cast unguarded");
    }
}