socketcan 4.0.0

Linux SocketCAN library. Send and receive CAN frames via CANbus on Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
// socketcan/src/errors.rs
//
// Implements errors for Rust SocketCAN library on Linux.
//
// This file is part of the Rust 'socketcan-rs' library.
//
// Licensed under the MIT license:
//   <LICENSE or http://opensource.org/licenses/MIT>
// This file may not be copied, modified, or distributed except according
// to those terms.

//! CAN bus errors.
//!
//! Most information about the errors on the CANbus are determined from an
//! error frame. To receive them, the error mask must be set on the socket
//! for the types of errors that the application would like to receive.
//!
//! See [RAW Socket Option CAN_RAW_ERR_FILTER](https://docs.kernel.org/networking/can.html#raw-socket-option-can-raw-err-filter)
//!
//! # Layout of an error frame
//!
//! The general classes of error are encoded as bits in the error field of
//! the CAN ID of an error frame. Several classes can be — and routinely
//! are — set at once. Most classes point at a data byte holding further
//! detail:
//!
//! ```text
//! TX Timeout         (0x001)
//! Lost Arbitration   (0x002) => data[0]   bit number, 0 = unspecified
//! Controller Problem (0x004) => data[1]   BITFIELD
//! Protocol Violation (0x008) => data[2]   BITFIELD  (type)
//!                               data[3]   scalar    (location)
//! Transceiver Status (0x010) => data[4]   two nibbles: CANL | CANH
//! No ACK             (0x020)
//! Bus Off            (0x040)
//! Bus Error          (0x080)
//! Restarted          (0x100)
//! Error Counters     (0x200) => data[6]   TX error counter
//!                               data[7]   RX error counter
//!
//! data[5] is reserved by the kernel and is never decoded here.
//! ```
//!
//! # One error may have several causes
//!
//! A single error frame generally describes **one** error event, but that
//! event can have several distinct causes, at two levels:
//!
//! 1. Several class bits can be set in the CAN ID at once. `CAN_ERR_CRTL |
//!    CAN_ERR_CNT` accompanies essentially every controller state change,
//!    and drivers such as `sja1000` can set five classes on one frame.
//! 2. `data[1]` and `data[2]` are themselves **bitfields**, so one class can
//!    describe several simultaneous conditions. The kernel's shared
//!    `can_change_state()` helper ORs both the TX and RX state codes into
//!    `data[1]` whenever the two states are equal, so `data[1] = 0x0C`
//!    (`RX_WARNING | TX_WARNING`) is the normal encoding of a symmetric
//!    warning transition. `data[4]` is similarly split into two independent
//!    nibbles for the CAN High and CAN Low lines.
//!
//! Decoding therefore yields a single [`CanError`] holding one [`ErrorCause`]
//! per class bit. The two bitfield facets ([`ErrorCause::Controller`],
//! [`ErrorCause::Protocol`]) and the two-nibble [`ErrorCause::Transceiver`]
//! each carry a *set* of conditions in one cause, rather than separate
//! sibling entries. A [`CanError`] is non-empty by construction: there is
//! **always** a [`first`](CanError::first) cause, in ascending class-bit order.
//!
//! All of this error information is not well documented, but can be
//! extracted from the Linux kernel header file:
//! [linux/can/error.h](https://raw.githubusercontent.com/torvalds/linux/master/include/uapi/linux/can/error.h)
//!

use crate::{CanErrorFrame, EmbeddedFrame, Frame};
use smallvec::{SmallVec, smallvec};
use std::{convert::TryFrom, error, fmt, io};
use thiserror::Error;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// The error class bits that can appear in the CAN ID of an error frame.
///
/// Several of these are routinely set at once; see the [module
/// documentation](self). Re-exported so that constructing or inspecting an
/// error frame does not require a direct `libc` dependency.
pub use libc::{
    CAN_ERR_ACK, CAN_ERR_BUSERROR, CAN_ERR_BUSOFF, CAN_ERR_CNT, CAN_ERR_CRTL, CAN_ERR_LOSTARB,
    CAN_ERR_PROT, CAN_ERR_RESTARTED, CAN_ERR_TRX, CAN_ERR_TX_TIMEOUT,
};

/// The error counter value at which a controller enters the "error warning"
/// state. Compare against the counters from [`ErrorCause::Counters`].
pub use libc::CAN_ERROR_WARNING_THRESHOLD;

/// The error counter value at which a controller enters the "error passive"
/// state. Compare against the counters from [`ErrorCause::Counters`].
pub use libc::CAN_ERROR_PASSIVE_THRESHOLD;

/// The error counter value at which a controller goes bus-off.
/// Compare against the counters from [`ErrorCause::Counters`].
pub use libc::CAN_BUS_OFF_THRESHOLD;

/// Mask of every error class bit this crate knows how to decode.
const KNOWN_ERR_CLASSES: u32 = CAN_ERR_TX_TIMEOUT
    | CAN_ERR_LOSTARB
    | CAN_ERR_CRTL
    | CAN_ERR_PROT
    | CAN_ERR_TRX
    | CAN_ERR_ACK
    | CAN_ERR_BUSOFF
    | CAN_ERR_BUSERROR
    | CAN_ERR_RESTARTED
    | CAN_ERR_CNT;

// ===== Composite Error for the crate =====

/// Composite SocketCAN error.
///
/// This can be any of the underlying errors from this library. The two main
/// error sources when interacting with the bus are:
/// - CAN errors detected on the bus or in the kernel driver. These are
///   reported up to the application through error frames and can be extracted
///   into a composite [`CanError`].
/// - Typical system I/O errors as [`io::Error`].
///
/// The parser and netlink error only occur when dealing with those specific
/// modules.
#[derive(Error, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize), serde(from = "ErrorRepr"))]
pub enum Error {
    /// A CAN error decoded from an error frame.
    #[error(transparent)]
    Can(#[from] CanError),
    /// An I/O Error
    #[error(transparent)]
    Io(#[from] io::Error),
    /// Error from the dump-file parser
    #[cfg(feature = "dump")]
    #[error(transparent)]
    Parser(#[from] crate::dump::ParseError),
    /// Non-I/O errors reported by the netlink protocol layer.
    #[cfg(feature = "netlink")]
    #[error(transparent)]
    Nl(#[from] crate::nl::NlError),
}

impl embedded_can::Error for Error {
    fn kind(&self) -> embedded_can::ErrorKind {
        match self {
            Error::Can(err) => err.kind(),
            _ => embedded_can::ErrorKind::Other,
        }
    }
}

impl From<ErrorCause> for Error {
    /// Wraps a single cause, promoting it to a one-cause [`CanError`].
    fn from(cause: ErrorCause) -> Self {
        Error::Can(CanError::new(cause))
    }
}

impl From<CanErrorFrame> for Error {
    /// Converts an error frame into a CAN error.
    fn from(frame: CanErrorFrame) -> Self {
        Error::Can(CanError::from(frame))
    }
}

impl From<io::ErrorKind> for Error {
    /// Creates an Io error straight from an io::ErrorKind
    fn from(kind: io::ErrorKind) -> Self {
        Self::from(io::Error::from(kind))
    }
}

/// Rebuilds an owned [`io::Error`] from a borrowed one, keeping the errno
/// when there is one so the kind survives.
///
/// `io::Error` is not `Clone`, and neli hands out its socket errors behind
/// an `Arc`, so the only way across is to rebuild.
#[cfg(feature = "netlink")]
fn clone_io_error(e: &io::Error) -> io::Error {
    match e.raw_os_error() {
        Some(errno) => io::Error::from_raw_os_error(errno),
        None => io::Error::new(e.kind(), e.to_string()),
    }
}

#[cfg(feature = "netlink")]
impl<T, P> From<neli::err::RouterError<T, P>> for Error
where
    T: neli::consts::nl::NlType,
    P: fmt::Debug,
{
    /// Lifts a netlink error into the crate-level [`enum@Error`], letting
    /// callers `?` netlink results across module boundaries.
    ///
    /// Only the split between the two kinds of failure is decided here: a
    /// genuine I/O failure keeps its [`io::ErrorKind`] — and its errno, when
    /// neli passed one along — as [`Error::Io`], and everything netlink-shaped
    /// is summarized by [`NlError`](crate::nl::NlError), which arrives through
    /// the [`Nl`](Error::Nl) variant's `From`. See
    /// [`From<RouterError> for NlError`](crate::nl::NlError) for what that
    /// summary keeps.
    ///
    /// The neli error itself is deliberately not carried: it is generic over
    /// the message type and payload, 128 bytes wide, and would put neli in
    /// this crate's public API.
    fn from(e: neli::err::RouterError<T, P>) -> Error {
        use neli::err::{RouterError, SocketError};

        match e {
            RouterError::Io(kind) => Self::Io(io::Error::from(kind)),
            RouterError::Socket(SocketError::Io(err)) => Self::Io(clone_io_error(&err)),
            other => Self::Nl(other.into()),
        }
    }
}

/// Maps an `errno` reported by a `nix` call onto an [`Error::Io`],
/// preserving it exactly: `nix::Error` *is* an errno, so nothing is lost.
impl From<nix::Error> for Error {
    fn from(e: nix::Error) -> Self {
        Self::Io(io::Error::from(e))
    }
}

/// Lets the netlink module `?` a socket-level neli error, keeping a genuine
/// I/O failure — with its kind and errno — as [`Error::Io`].
#[cfg(feature = "netlink")]
impl From<neli::err::SocketError> for Error {
    fn from(e: neli::err::SocketError) -> Self {
        use neli::err::SocketError;
        match e {
            SocketError::Io(err) => Self::Io(clone_io_error(&err)),
            other => crate::nl::NlError::Msg(other.to_string()).into(),
        }
    }
}

/// Lets the netlink module `?` a deserialization error from neli. Only the
/// I/O case has structure worth keeping.
#[cfg(feature = "netlink")]
impl From<neli::err::DeError> for Error {
    fn from(e: neli::err::DeError) -> Self {
        use neli::err::DeError;
        match e {
            DeError::Io(kind) => Self::Io(io::Error::from(kind)),
            other => crate::nl::NlError::Msg(other.to_string()).into(),
        }
    }
}

/// Lets the netlink module `?` a serialization error from neli.
#[cfg(feature = "netlink")]
impl From<neli::err::SerError> for Error {
    fn from(e: neli::err::SerError) -> Self {
        crate::nl::NlError::Msg(e.to_string()).into()
    }
}

/// Lets the netlink module `?` a failure to build a netlink attribute. These
/// are programming errors in message construction, so only the text matters.
#[cfg(feature = "netlink")]
impl From<neli::rtnl::RtattrBuilderError> for Error {
    fn from(e: neli::rtnl::RtattrBuilderError) -> Self {
        crate::nl::NlError::Msg(e.to_string()).into()
    }
}

/// A result that can derive from any of the CAN errors.
pub type Result<T> = std::result::Result<T, Error>;

/// An I/O specific error
pub type IoError = io::Error;

/// A kind of I/O error
pub type IoErrorKind = io::ErrorKind;

/// An I/O specific result
pub type IoResult<T> = io::Result<T>;

// --------------------------------------------------------------------------

/// Inline capacity for the cause list.
///
/// Two, and the value is load-bearing in both directions.
///
/// [`enum@Error`] sits in every [`Result`] this crate returns — including
/// `read_frame()` on the receive hot path — and its width is set by this
/// array. With `smallvec`'s `union` feature a `SmallVec` costs
/// `max(8 * N, 16) + 8` bytes, so one and two inline causes are both 24,
/// three is 32, four is 40. Two is therefore the largest capacity that is
/// free relative to one.
///
/// It is also the capacity that matters: the routine controller-state-change
/// frame sets `CAN_ERR_CRTL | CAN_ERR_CNT` and decodes to exactly two causes
/// (see the [module documentation](self)), so a capacity of one would put an
/// allocation in the path of the most common error frame there is. Frames
/// reporting three or more — `sja1000` can set five classes at once — do
/// allocate, which is the right trade when the alternative is a wider
/// `Result` on every success.
///
/// The theoretical maximum is ~13 (ten class bits, an `Unknown`, and two
/// decoding failures) and is synthetic.
const NUM_INLINE_CAUSES: usize = 2;

/// The backing storage for a [`CanError`]'s causes.
type Causes = SmallVec<[ErrorCause; NUM_INLINE_CAUSES]>;

/// The error decoded from a single CAN error frame.
///
/// A SocketCAN error frame reports *one* error event, described by one or
/// more [`ErrorCause`]s — most commonly a controller state change together
/// with the current TX/RX error counter values, or a bus error annotated
/// with several protocol violation types and a location. See the [module
/// documentation](self) for the two levels at which several causes arise.
///
/// `CanError` is **non-empty by construction**: there is always a
/// [`first()`](Self::first) cause. A frame with no recognisable error bits
/// decodes to a single [`ErrorCause::Unknown`] rather than an empty error.
///
/// # Ordering
///
/// Causes appear in a stable, documented order: error classes in ascending
/// numeric order of their CAN ID bit, i.e. TX timeout, lost arbitration,
/// controller problem, protocol violation, transceiver status, no-ACK, bus
/// off, bus error, restarted, counters, followed by any unrecognised class
/// bits as a trailing [`ErrorCause::Unknown`].
///
/// # Implementation
///
/// Up to two causes are held inline, so decoding either a single-cause frame
/// or the routine two-cause controller state change does not allocate. A
/// frame reporting more than that spills to the heap, which keeps this type
/// — and therefore every `Result` in the crate — narrow.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(into = "Vec<ErrorCause>", try_from = "Vec<ErrorCause>")
)]
pub struct CanError {
    causes: Causes,
}

impl CanError {
    /// Creates an error holding exactly one cause.
    ///
    /// This does not allocate.
    pub fn new(cause: ErrorCause) -> Self {
        Self {
            causes: smallvec![cause],
        }
    }

    /// Creates an error from a first cause plus any number of additional
    /// ones.
    ///
    /// Note that we can't simply take a collection of causes, since we
    /// guarantee that an error has at least one cause, and an empty
    /// collection would be invalid.
    pub fn from_multiple(first: ErrorCause, rest: impl IntoIterator<Item = ErrorCause>) -> Self {
        let mut causes = Causes::new();
        causes.push(first);
        causes.extend(rest);
        Self { causes }
    }

    /// Creates an error from an iterator of causes, returning `None` if it is
    /// empty.
    ///
    /// Prefer [`new()`](Self::new) or [`from_multiple()`](Self::from_multiple)
    /// when the non-emptiness is already known statically.
    pub fn from_iter_checked(causes: impl IntoIterator<Item = ErrorCause>) -> Option<Self> {
        let causes: Causes = causes.into_iter().collect();
        (!causes.is_empty()).then_some(Self { causes })
    }

    /// Gets the first cause.
    ///
    /// This is never `None`: the type is non-empty by construction. For a
    /// frame that set several class bits, this is the one belonging to the
    /// lowest-numbered class bit.
    pub fn first(&self) -> &ErrorCause {
        &self.causes[0]
    }

    /// Gets the last cause.
    ///
    /// This is never `None`: the type is non-empty by construction.
    pub fn last(&self) -> &ErrorCause {
        self.causes.last().unwrap()
    }

    /// The number of causes reported.
    ///
    /// This is never zero: the type is non-empty by construction.
    pub fn len(&self) -> usize {
        self.causes.len()
    }

    /// Always `false`; the error is non-empty by construction.
    ///
    /// Provided only because clippy expects `is_empty` alongside `len`.
    pub fn is_empty(&self) -> bool {
        false
    }

    /// Determines whether this holds exactly one cause.
    ///
    /// Note that multi-cause errors are *common*, not exceptional: any
    /// controller state change reports `CAN_ERR_CRTL | CAN_ERR_CNT`, which
    /// is two causes. Do not treat the single case as the norm.
    pub fn is_single(&self) -> bool {
        self.causes.len() == 1
    }

    /// An iterator over the causes, in the order documented on the type.
    pub fn causes(&self) -> impl Iterator<Item = &ErrorCause> + '_ {
        self.causes.iter()
    }

    /// Determines whether any of the causes maps to the given
    /// [`embedded_can::ErrorKind`].
    pub fn contains_kind(&self, kind: embedded_can::ErrorKind) -> bool {
        use embedded_can::Error as _;
        self.causes().any(|c| c.kind() == kind)
    }

    // ----- typed accessors for the data-carrying causes -----

    /// The bit position after which arbitration was lost, if reported.
    ///
    /// Note that the kernel uses zero to mean *unspecified* rather than
    /// literally "bit 0".
    pub fn lost_arbitration(&self) -> Option<u8> {
        self.causes().find_map(|c| match c {
            ErrorCause::LostArbitration(bit) => Some(*bit),
            _ => None,
        })
    }

    /// The controller status flags, if the frame carried them.
    pub fn controller(&self) -> Option<ControllerProblems> {
        self.causes().find_map(|c| match c {
            ErrorCause::Controller(p) => Some(*p),
            _ => None,
        })
    }

    /// The protocol violation type(s) and location, if reported.
    pub fn protocol(&self) -> Option<(ViolationTypes, Location)> {
        self.causes().find_map(|c| match c {
            ErrorCause::Protocol { types, location } => Some((*types, *location)),
            _ => None,
        })
    }

    /// The CAN High and CAN Low line faults, if a transceiver status was
    /// reported.
    pub fn transceiver(&self) -> Option<(Option<CanHighFault>, Option<CanLowFault>)> {
        self.causes().find_map(|c| match c {
            ErrorCause::Transceiver { canh, canl } => Some((*canh, *canl)),
            _ => None,
        })
    }

    /// The TX/RX error counters, if the frame carried a `CAN_ERR_CNT` cause.
    pub fn counters(&self) -> Option<(u8, u8)> {
        self.causes().find_map(|c| match c {
            ErrorCause::Counters { tx, rx } => Some((*tx, *rx)),
            _ => None,
        })
    }
}

/// Generates a boolean predicate over the causes.
macro_rules! cause_predicate {
    ($name:ident, $doc:literal, $pat:pat) => {
        #[doc = $doc]
        pub fn $name(&self) -> bool {
            self.causes().any(|c| matches!(c, $pat))
        }
    };
}

impl CanError {
    cause_predicate!(
        is_transmit_timeout,
        "Whether a TX timeout was reported.",
        ErrorCause::TransmitTimeout
    );
    cause_predicate!(
        is_no_ack,
        "Whether the frame went unacknowledged.",
        ErrorCause::NoAck
    );
    cause_predicate!(
        is_bus_off,
        "Whether the controller reported a bus-off condition.",
        ErrorCause::BusOff
    );
    cause_predicate!(
        is_bus_error,
        "Whether a bus error was reported.",
        ErrorCause::BusError
    );
    cause_predicate!(
        is_restarted,
        "Whether the controller restarted.",
        ErrorCause::Restarted
    );
    cause_predicate!(
        has_counters,
        "Whether error counter values were reported.",
        ErrorCause::Counters { .. }
    );
}

impl From<ErrorCause> for CanError {
    fn from(cause: ErrorCause) -> Self {
        Self::new(cause)
    }
}

impl IntoIterator for CanError {
    type Item = ErrorCause;
    type IntoIter = smallvec::IntoIter<[ErrorCause; NUM_INLINE_CAUSES]>;

    fn into_iter(self) -> Self::IntoIter {
        self.causes.into_iter()
    }
}

impl<'a> IntoIterator for &'a CanError {
    type Item = &'a ErrorCause;
    type IntoIter = std::slice::Iter<'a, ErrorCause>;

    fn into_iter(self) -> Self::IntoIter {
        self.causes.iter()
    }
}

impl error::Error for CanError {}

impl fmt::Display for CanError {
    /// Renders the causes as a single line.
    ///
    /// A lone cause renders exactly as its own `Display`. Multiple causes are
    /// joined with "; ".
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // There is always a first cause; only the rest need a separator.
        write!(f, "{}", self.first())?;
        for cause in self.causes().skip(1) {
            write!(f, "; {}", cause)?;
        }
        Ok(())
    }
}

impl embedded_can::Error for CanError {
    /// Reports the most specific error kind present.
    ///
    /// Scans the causes in order and returns the first kind that is not
    /// [`ErrorKind::Other`](embedded_can::ErrorKind::Other), falling back to
    /// `Other` when every cause is unspecific. The scan is over *kinds*, not
    /// over error classes in declaration order — a frame carrying both a
    /// controller warning and a missing ACK reports `Acknowledge`, since the
    /// warning maps only to `Other`.
    fn kind(&self) -> embedded_can::ErrorKind {
        use embedded_can::ErrorKind;
        self.causes()
            .map(|c| c.kind())
            .find(|k| *k != ErrorKind::Other)
            .unwrap_or(ErrorKind::Other)
    }
}

impl From<CanErrorFrame> for CanError {
    /// Decodes every cause described by an error frame.
    ///
    /// Walks the class bits of the CAN ID in ascending order, producing one
    /// [`ErrorCause`] per class bit. The bitfield facets carry a set, so a
    /// class describing several simultaneous conditions is a single cause.
    fn from(frame: CanErrorFrame) -> Self {
        // Note that the CanErrorFrame is guaranteed to have the full 8-byte
        // data payload.
        let bits = frame.error_bits();
        let data = frame.data();
        let mut causes = Causes::new();

        if bits & CAN_ERR_TX_TIMEOUT != 0 {
            causes.push(ErrorCause::TransmitTimeout);
        }
        if bits & CAN_ERR_LOSTARB != 0 {
            causes.push(ErrorCause::LostArbitration(data[0]));
        }
        if bits & CAN_ERR_CRTL != 0 {
            push_controller(&mut causes, data[1]);
        }
        if bits & CAN_ERR_PROT != 0 {
            // Every bit of data[2] is defined, so this cannot drop bits.
            causes.push(ErrorCause::Protocol {
                types: ViolationTypes::from_bits_truncate(data[2]),
                location: Location::from_raw(data[3]),
            });
        }
        if bits & CAN_ERR_TRX != 0 {
            push_transceiver(&mut causes, data[4]);
        }
        if bits & CAN_ERR_ACK != 0 {
            causes.push(ErrorCause::NoAck);
        }
        if bits & CAN_ERR_BUSOFF != 0 {
            causes.push(ErrorCause::BusOff);
        }
        if bits & CAN_ERR_BUSERROR != 0 {
            causes.push(ErrorCause::BusError);
        }
        if bits & CAN_ERR_RESTARTED != 0 {
            causes.push(ErrorCause::Restarted);
        }
        // Strictly gated on the flag. The kernel leaves data[6..7] undefined
        // when CAN_ERR_CNT is clear; can-utils prints them anyway, but that
        // is a display convenience, not a decoding rule.
        if bits & CAN_ERR_CNT != 0 {
            causes.push(ErrorCause::Counters {
                tx: data[6],
                rx: data[7],
            });
        }

        // Any class bits we do not recognise are reported as a single
        // trailing cause carrying just those bits.
        let unknown = bits & !KNOWN_ERR_CLASSES;

        if unknown != 0 {
            causes.push(ErrorCause::Unknown(unknown));
        }

        // A frame with no class bits at all is malformed; report it rather
        // than violating the non-empty invariant.
        if causes.is_empty() {
            causes.push(ErrorCause::Unknown(0));
        }
        Self { causes }
    }
}

/// Decodes the controller-problem bitfield in `data[1]` into one
/// [`ErrorCause::Controller`]. An empty set is `CAN_ERR_CRTL_UNSPEC`.
///
/// Any bits with no known meaning produce a trailing
/// [`ErrorCause::DecodingFailure`].
fn push_controller(causes: &mut Causes, byte: u8) {
    causes.push(ErrorCause::Controller(
        ControllerProblems::from_bits_truncate(byte),
    ));
    if byte & !ControllerProblems::all().bits() != 0 {
        causes.push(ErrorCause::DecodingFailure(
            CanErrorDecodingFailure::InvalidControllerProblem,
        ));
    }
}

/// Decodes the two nibbles of `data[4]` into one [`ErrorCause::Transceiver`].
///
/// The low nibble describes the CAN High line and the high nibble the CAN Low
/// line, so a fault on both lines is a single byte with both halves set (the
/// kernel's `etas_es58x` driver emits `0x44` for a lost connection on either
/// line). A zero half is absent (`None`). An unrecognised half yields a
/// trailing [`ErrorCause::DecodingFailure`].
fn push_transceiver(causes: &mut Causes, byte: u8) {
    let mut invalid = false;
    let canh = match byte & 0x0F {
        0 => None,
        h => CanHighFault::try_from(h).map(Some).unwrap_or_else(|_| {
            invalid = true;
            None
        }),
    };
    let canl = match byte & 0xF0 {
        0 => None,
        l => CanLowFault::try_from(l).map(Some).unwrap_or_else(|_| {
            invalid = true;
            None
        }),
    };
    causes.push(ErrorCause::Transceiver { canh, canl });
    if invalid {
        causes.push(ErrorCause::DecodingFailure(
            CanErrorDecodingFailure::InvalidTransceiverError,
        ));
    }
}

/////////////////////////////////////////////////////////////////////////////
// serde support for the composite error and the CAN error

/// Serialized form of [`enum@Error`].
///
/// The `Can` half round-trips exactly. The `Io` half cannot: `io::Error`
/// implements neither serde trait and may carry an OS errno or a boxed source,
/// so it is reduced to its kind and message. See [`ErrorRepr::Io`]. The
/// `Parser` half round-trips exactly apart from its own nested `Io` variant,
/// which is reduced the same way.
#[cfg(feature = "serde")]
#[derive(Debug, Serialize, Deserialize)]
pub enum ErrorRepr {
    /// A CAN error
    Can(CanError),
    /// An I/O error, reduced to a kind name and a message.
    ///
    /// This conversion is **lossy**: after a round trip
    /// [`io::Error::raw_os_error()`] returns `None`, any `source()` chain is
    /// gone, and a `kind` name that the reading version does not recognise
    /// degrades to [`io::ErrorKind::Other`].
    Io {
        /// The [`io::ErrorKind`], by name
        kind: String,
        /// The original error's `Display` text
        message: String,
    },
    /// A dump file parse error, in its own serialized form.
    #[cfg(feature = "dump")]
    Parser(crate::dump::ParseErrorRepr),
    /// A netlink error. Round-trips exactly; it is already an owned summary.
    #[cfg(feature = "netlink")]
    Nl(crate::nl::NlError),
}

/// Maps an [`io::ErrorKind`] to a stable name.
///
/// `io::ErrorKind` is `#[non_exhaustive]` and has no stable string form of its
/// own, so this covers the kinds this crate can plausibly produce and falls
/// back to `"Other"`. Round-tripping through [`io_kind_from_name`] is therefore
/// not total, which is documented on [`ErrorRepr::Io`].
///
/// Note that some errnos map to kinds that are not nameable at all — `ENODEV`
/// becomes the unstable `ErrorKind::Uncategorized`, for instance — so those
/// necessarily arrive back as `Other`.
#[cfg(feature = "serde")]
pub(crate) fn io_kind_name(kind: io::ErrorKind) -> &'static str {
    use io::ErrorKind::*;
    match kind {
        NotFound => "NotFound",
        PermissionDenied => "PermissionDenied",
        ConnectionRefused => "ConnectionRefused",
        ConnectionReset => "ConnectionReset",
        ConnectionAborted => "ConnectionAborted",
        NotConnected => "NotConnected",
        NetworkDown => "NetworkDown",
        NetworkUnreachable => "NetworkUnreachable",
        HostUnreachable => "HostUnreachable",
        ResourceBusy => "ResourceBusy",
        AddrInUse => "AddrInUse",
        AddrNotAvailable => "AddrNotAvailable",
        BrokenPipe => "BrokenPipe",
        AlreadyExists => "AlreadyExists",
        WouldBlock => "WouldBlock",
        InvalidInput => "InvalidInput",
        InvalidData => "InvalidData",
        TimedOut => "TimedOut",
        WriteZero => "WriteZero",
        Interrupted => "Interrupted",
        Unsupported => "Unsupported",
        UnexpectedEof => "UnexpectedEof",
        OutOfMemory => "OutOfMemory",
        _ => "Other",
    }
}

/// The inverse of [`io_kind_name`], falling back to
/// [`io::ErrorKind::Other`] for anything unrecognised.
///
/// The fallback is deliberate: a value written by a newer version of this
/// crate must still deserialize in an older one.
#[cfg(feature = "serde")]
pub(crate) fn io_kind_from_name(name: &str) -> io::ErrorKind {
    use io::ErrorKind::*;
    match name {
        "NotFound" => NotFound,
        "PermissionDenied" => PermissionDenied,
        "ConnectionRefused" => ConnectionRefused,
        "ConnectionReset" => ConnectionReset,
        "ConnectionAborted" => ConnectionAborted,
        "NotConnected" => NotConnected,
        "NetworkDown" => NetworkDown,
        "NetworkUnreachable" => NetworkUnreachable,
        "HostUnreachable" => HostUnreachable,
        "ResourceBusy" => ResourceBusy,
        "AddrInUse" => AddrInUse,
        "AddrNotAvailable" => AddrNotAvailable,
        "BrokenPipe" => BrokenPipe,
        "AlreadyExists" => AlreadyExists,
        "WouldBlock" => WouldBlock,
        "InvalidInput" => InvalidInput,
        "InvalidData" => InvalidData,
        "TimedOut" => TimedOut,
        "WriteZero" => WriteZero,
        "Interrupted" => Interrupted,
        "Unsupported" => Unsupported,
        "UnexpectedEof" => UnexpectedEof,
        "OutOfMemory" => OutOfMemory,
        _ => Other,
    }
}

/// Hand-written because `serde(into = ...)` requires `Clone`, and
/// [`enum@Error`] cannot be `Clone`: `io::Error` is not.
///
/// This clones the [`CanError`] to build the repr. Serialization is not a hot
/// path, so the allocation is not worth avoiding with a parallel borrowing
/// repr that would have to be kept in sync by hand.
#[cfg(feature = "serde")]
impl Serialize for Error {
    fn serialize<S: serde::Serializer>(&self, ser: S) -> std::result::Result<S::Ok, S::Error> {
        let repr = match self {
            Error::Can(err) => ErrorRepr::Can(err.clone()),
            Error::Io(e) => ErrorRepr::Io {
                kind: io_kind_name(e.kind()).to_string(),
                message: e.to_string(),
            },
            #[cfg(feature = "dump")]
            Error::Parser(e) => ErrorRepr::Parser(e.into()),
            #[cfg(feature = "netlink")]
            Error::Nl(e) => ErrorRepr::Nl(e.clone()),
        };
        repr.serialize(ser)
    }
}

#[cfg(feature = "serde")]
impl From<ErrorRepr> for Error {
    fn from(repr: ErrorRepr) -> Self {
        match repr {
            ErrorRepr::Can(err) => Self::Can(err),
            ErrorRepr::Io { kind, message } => {
                Self::Io(io::Error::new(io_kind_from_name(&kind), message))
            }
            #[cfg(feature = "dump")]
            ErrorRepr::Parser(repr) => Self::Parser(repr.into()),
            #[cfg(feature = "netlink")]
            ErrorRepr::Nl(e) => Self::Nl(e),
        }
    }
}

#[cfg(feature = "serde")]
impl From<CanError> for Vec<ErrorCause> {
    fn from(err: CanError) -> Self {
        err.into_iter().collect()
    }
}

#[cfg(feature = "serde")]
impl TryFrom<Vec<ErrorCause>> for CanError {
    type Error = EmptyCanError;

    /// Rebuilds the error, rejecting an empty sequence.
    ///
    /// This is what keeps the non-empty invariant intact across
    /// deserialization; without it, serde would be a way to construct an
    /// invalid `CanError` from outside the crate.
    fn try_from(causes: Vec<ErrorCause>) -> std::result::Result<Self, Self::Error> {
        Self::from_iter_checked(causes).ok_or(EmptyCanError)
    }
}

/// Error returned when deserializing a [`CanError`] from an empty sequence.
///
/// [`CanError`] is non-empty by construction, so an empty input is invalid
/// rather than merely unusual.
#[cfg(feature = "serde")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmptyCanError;

#[cfg(feature = "serde")]
impl fmt::Display for EmptyCanError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("a CanError must hold at least one cause")
    }
}

#[cfg(feature = "serde")]
impl error::Error for EmptyCanError {}

// ===== ErrorCause ====

/// A single condition a CAN error frame reported.
///
/// One `ErrorCause` corresponds to one class bit in the frame's CAN ID. The
/// two bitfield facets ([`Controller`](Self::Controller),
/// [`Protocol`](Self::Protocol)) and the two-nibble
/// [`Transceiver`](Self::Transceiver) byte each carry a *set* of conditions
/// in a single cause, rather than exploding into sibling entries.
///
/// A frame as a whole decodes to a [`CanError`], which holds these; see the
/// [module documentation](self).
///
/// This is `#[non_exhaustive]`: new class bits may be added in future kernels,
/// so downstream `match`es should include a wildcard arm.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ErrorCause {
    /// TX timeout (by netdevice driver). `CAN_ERR_TX_TIMEOUT`.
    TransmitTimeout,
    /// Arbitration was lost.
    ///
    /// Contains the bit number after which arbitration was lost. Note that
    /// the kernel uses zero (`CAN_ERR_LOSTARB_UNSPEC`) to mean
    /// *unspecified* rather than literally "bit 0". `CAN_ERR_LOSTARB`.
    LostArbitration(u8),
    /// Controller status flags, from `data[1]`. `CAN_ERR_CRTL`.
    ///
    /// An empty set is `CAN_ERR_CRTL_UNSPEC`.
    Controller(ControllerProblems),
    /// Protocol violation(s) at one location, from `data[2..=3]`.
    /// `CAN_ERR_PROT`.
    Protocol {
        /// The violation type(s); an empty set means "unspecified".
        types: ViolationTypes,
        /// The location (field or bit) of the violation.
        location: Location,
    },
    /// Transceiver line faults, from the two nibbles of `data[4]`.
    /// `CAN_ERR_TRX`.
    Transceiver {
        /// The CAN High line fault (low nibble), if any.
        canh: Option<CanHighFault>,
        /// The CAN Low line fault (high nibble), if any.
        canl: Option<CanLowFault>,
    },
    /// No ACK received for the transmitted frame. `CAN_ERR_ACK`.
    NoAck,
    /// Bus off (due to too many detected errors). `CAN_ERR_BUSOFF`.
    BusOff,
    /// Bus error (due to too many detected errors). `CAN_ERR_BUSERROR`.
    BusError,
    /// The controller has been restarted. `CAN_ERR_RESTARTED`.
    Restarted,
    /// The controller's TX and RX error counter values, from a
    /// `CAN_ERR_CNT` frame (`data[6..=7]`).
    ///
    /// Compare against [`CAN_ERROR_WARNING_THRESHOLD`],
    /// [`CAN_ERROR_PASSIVE_THRESHOLD`] and [`CAN_BUS_OFF_THRESHOLD`] to
    /// interpret the values.
    Counters {
        /// TX error counter, from `data[6]`
        tx: u8,
        /// RX error counter, from `data[7]`
        rx: u8,
    },
    /// A data byte held a bit pattern this crate could not decode.
    DecodingFailure(CanErrorDecodingFailure),
    /// Unknown, possibly invalid, error class bits.
    Unknown(u32),
}

impl error::Error for ErrorCause {}

impl fmt::Display for ErrorCause {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ErrorCause::*;
        match *self {
            TransmitTimeout => write!(f, "transmission timeout"),
            LostArbitration(n) => write!(f, "arbitration lost after {} bits", n),
            Controller(p) => write!(f, "controller problem: {}", p),
            Protocol { types, location } => {
                write!(f, "protocol violation at {}: {}", location, types)
            }
            Transceiver { canh, canl } => {
                write!(f, "transceiver error: ")?;
                match (canh, canl) {
                    (Some(h), Some(l)) => write!(f, "CAN High, {}; CAN Low, {}", h, l),
                    (Some(h), None) => write!(f, "CAN High, {}", h),
                    (None, Some(l)) => write!(f, "CAN Low, {}", l),
                    (None, None) => write!(f, "unspecified"),
                }
            }
            NoAck => write!(f, "no ack"),
            BusOff => write!(f, "bus off"),
            BusError => write!(f, "bus error"),
            Restarted => write!(f, "restarted"),
            Counters { tx, rx } => write!(f, "error counters: tx={}, rx={}", tx, rx),
            DecodingFailure(err) => write!(f, "decoding failure: {}", err),
            Unknown(bits) => write!(f, "unknown error ({:#x})", bits),
        }
    }
}

impl embedded_can::Error for ErrorCause {
    fn kind(&self) -> embedded_can::ErrorKind {
        use embedded_can::ErrorKind;
        match *self {
            ErrorCause::Controller(p) => {
                if p.intersects(ControllerProblems::RX_OVERFLOW | ControllerProblems::TX_OVERFLOW) {
                    ErrorKind::Overrun
                } else {
                    ErrorKind::Other
                }
            }
            ErrorCause::Protocol { types, .. } => {
                if types
                    .intersects(ViolationTypes::BIT | ViolationTypes::BIT0 | ViolationTypes::BIT1)
                {
                    ErrorKind::Bit
                } else if types.contains(ViolationTypes::FORM) {
                    ErrorKind::Form
                } else if types.contains(ViolationTypes::STUFF) {
                    ErrorKind::Stuff
                } else {
                    ErrorKind::Other
                }
            }
            ErrorCause::NoAck => ErrorKind::Acknowledge,
            _ => ErrorKind::Other,
        }
    }
}

// ===== ControllerProblems =====

bitflags::bitflags! {
    /// Error status flags of the CAN controller.
    ///
    /// Decoded from `data[1]` of an error frame, which is a **bitfield** —
    /// several of these can be set at once. The kernel's shared
    /// `can_change_state()` helper ORs the TX and RX state codes together
    /// whenever the two states match, so pairs such as `RX_WARNING` plus
    /// `TX_WARNING` are the normal encoding rather than an anomaly. An empty
    /// set is `CAN_ERR_CRTL_UNSPEC` ("unspecified").
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
    pub struct ControllerProblems: u8 {
        /// RX buffer overflow
        const RX_OVERFLOW = libc::CAN_ERR_CRTL_RX_OVERFLOW as u8;
        /// TX buffer overflow
        const TX_OVERFLOW = libc::CAN_ERR_CRTL_TX_OVERFLOW as u8;
        /// reached warning level for RX errors
        const RX_WARNING = libc::CAN_ERR_CRTL_RX_WARNING as u8;
        /// reached warning level for TX errors
        const TX_WARNING = libc::CAN_ERR_CRTL_TX_WARNING as u8;
        /// reached error-passive status, RX
        const RX_PASSIVE = libc::CAN_ERR_CRTL_RX_PASSIVE as u8;
        /// reached error-passive status, TX
        const TX_PASSIVE = libc::CAN_ERR_CRTL_TX_PASSIVE as u8;
        /// recovered to error-active state
        const ACTIVE = libc::CAN_ERR_CRTL_ACTIVE as u8;
    }
}

/// Writes the names of a set of flags as a comma-separated list, falling back
/// to `unspecified` when there are none.
///
/// Shared by the [`ControllerProblems`] and [`ViolationTypes`] renderings,
/// which differ only in their names and their empty text.
fn write_flag_names<'a>(
    f: &mut fmt::Formatter,
    names: impl IntoIterator<Item = &'a str>,
    unspecified: &str,
) -> fmt::Result {
    let mut names = names.into_iter();
    match names.next() {
        None => f.write_str(unspecified),
        Some(first) => {
            f.write_str(first)?;
            names.try_for_each(|name| write!(f, ", {}", name))
        }
    }
}

impl fmt::Display for ControllerProblems {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        const NAMED: [(ControllerProblems, &str); 7] = [
            (ControllerProblems::RX_OVERFLOW, "receive buffer overflow"),
            (ControllerProblems::TX_OVERFLOW, "transmit buffer overflow"),
            (ControllerProblems::RX_WARNING, "rx warning"),
            (ControllerProblems::TX_WARNING, "tx warning"),
            (ControllerProblems::RX_PASSIVE, "rx passive"),
            (ControllerProblems::TX_PASSIVE, "tx passive"),
            (ControllerProblems::ACTIVE, "back to error active"),
        ];
        let names = NAMED
            .into_iter()
            .filter(|(flag, _)| self.contains(*flag))
            .map(|(_, name)| name);
        write_flag_names(f, names, "unspecified controller problem")
    }
}

// ===== ViolationTypes =====

bitflags::bitflags! {
    /// The type(s) of a protocol violation error.
    ///
    /// Decoded from `data[2]` of an error frame, which is a **bitfield** —
    /// several of these can be set at once. Every bit is defined, so decoding
    /// this byte can never fail. An empty set means "unspecified". Note that
    /// [`TX`](Self::TX) (`CAN_ERR_PROT_TX`) is really a direction annotation
    /// meaning "the error occurred while transmitting"; drivers OR it
    /// alongside a specific type rather than reporting it alone.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
    pub struct ViolationTypes: u8 {
        /// single bit error
        const BIT = libc::CAN_ERR_PROT_BIT as u8;
        /// frame format error
        const FORM = libc::CAN_ERR_PROT_FORM as u8;
        /// bit stuffing error
        const STUFF = libc::CAN_ERR_PROT_STUFF as u8;
        /// unable to send dominant bit
        const BIT0 = libc::CAN_ERR_PROT_BIT0 as u8;
        /// unable to send recessive bit
        const BIT1 = libc::CAN_ERR_PROT_BIT1 as u8;
        /// bus overload
        const OVERLOAD = libc::CAN_ERR_PROT_OVERLOAD as u8;
        /// active error announcement
        const ACTIVE = libc::CAN_ERR_PROT_ACTIVE as u8;
        /// error occurred on transmission
        const TX = libc::CAN_ERR_PROT_TX as u8;
    }
}

impl fmt::Display for ViolationTypes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        const NAMED: [(ViolationTypes, &str); 8] = [
            (ViolationTypes::BIT, "single bit error"),
            (ViolationTypes::FORM, "frame format error"),
            (ViolationTypes::STUFF, "bit stuffing error"),
            (ViolationTypes::BIT0, "unable to send dominant bit"),
            (ViolationTypes::BIT1, "unable to send recessive bit"),
            (ViolationTypes::OVERLOAD, "bus overload"),
            (ViolationTypes::ACTIVE, "active error announcement"),
            (ViolationTypes::TX, "error on transmission"),
        ];
        let names = NAMED
            .into_iter()
            .filter(|(flag, _)| self.contains(*flag))
            .map(|(_, name)| name);
        write_flag_names(f, names, "unspecified")
    }
}

// ===== Location =====

/// The location of a CANbus protocol violation.
///
/// This describes the position inside a received frame (as in the field
/// or bit) at which an error occurred. It is derived from `data[3]` of an
/// error frame, which — unlike `data[2]` — is a scalar code, not a
/// bitfield.
///
/// # Coverage
///
/// Nineteen of these codes are named in `linux/can/error.h`. A further five
/// (`ActiveErrorFlag`, `TolerateDominantBits`, `PassiveErrorFlag`,
/// `ErrorDelimiter`, `OverloadFlag`) are absent from that header but are
/// genuinely emitted: the `sja1000` driver copies the raw 5-bit error code
/// capture segment straight into `data[3]`, and can-utils names them. Any
/// remaining value decodes to [`Reserved`](Self::Reserved), which keeps the
/// raw byte so nothing is lost and so decoding `data[3]` can never fail.
#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Location {
    /// Unspecified
    Unspecified,
    /// Start of frame
    StartOfFrame,
    /// ID bits 28-21 (SFF: 10-3)
    Id2821,
    /// ID bits 20-18 (SFF: 2-0)
    Id2018,
    /// substitute RTR (SFF: RTR)
    SubstituteRtr,
    /// extension of identifier
    IdentifierExtension,
    /// ID bits 17-13
    Id1713,
    /// ID bits 12-5
    Id1205,
    /// ID bits 4-0
    Id0400,
    /// RTR bit
    Rtr,
    /// Reserved bit 1
    Reserved1,
    /// Reserved bit 0
    Reserved0,
    /// Data length
    DataLengthCode,
    /// Data section
    DataSection,
    /// CRC sequence
    CrcSequence,
    /// CRC delimiter
    CrcDelimiter,
    /// ACK slot
    AckSlot,
    /// ACK delimiter
    AckDelimiter,
    /// End-of-frame
    EndOfFrame,
    /// Intermission (between frames)
    Intermission,
    /// Active error flag.
    ///
    /// Not named in `linux/can/error.h`; emitted by controllers that report
    /// the raw error code capture segment.
    ActiveErrorFlag,
    /// Tolerate dominant bits.
    ///
    /// Not named in `linux/can/error.h`; see [`ActiveErrorFlag`](Self::ActiveErrorFlag).
    TolerateDominantBits,
    /// Passive error flag.
    ///
    /// Not named in `linux/can/error.h`; see [`ActiveErrorFlag`](Self::ActiveErrorFlag).
    PassiveErrorFlag,
    /// Error delimiter.
    ///
    /// Not named in `linux/can/error.h`; see [`ActiveErrorFlag`](Self::ActiveErrorFlag).
    ErrorDelimiter,
    /// Overload flag.
    ///
    /// Not named in `linux/can/error.h`; see [`ActiveErrorFlag`](Self::ActiveErrorFlag).
    OverloadFlag,
    /// A `data[3]` value with no known meaning, preserved verbatim.
    Reserved(u8),
}

impl Location {
    /// Decodes the `data[3]` byte of an error frame.
    ///
    /// Total: every one of the 256 possible byte values maps to a variant,
    /// with unknown codes preserved as [`Reserved`](Self::Reserved). This is
    /// why there is no `TryFrom<u8>` — decoding a location cannot fail.
    pub const fn from_raw(val: u8) -> Self {
        use Location::*;
        match val {
            0x00 => Unspecified,
            0x02 => Id2821,
            0x03 => StartOfFrame,
            0x04 => SubstituteRtr,
            0x05 => IdentifierExtension,
            0x06 => Id2018,
            0x07 => Id1713,
            0x08 => CrcSequence,
            0x09 => Reserved0,
            0x0A => DataSection,
            0x0B => DataLengthCode,
            0x0C => Rtr,
            0x0D => Reserved1,
            0x0E => Id0400,
            0x0F => Id1205,
            0x11 => ActiveErrorFlag,
            0x12 => Intermission,
            0x13 => TolerateDominantBits,
            0x16 => PassiveErrorFlag,
            0x17 => ErrorDelimiter,
            0x18 => CrcDelimiter,
            0x19 => AckSlot,
            0x1A => EndOfFrame,
            0x1B => AckDelimiter,
            0x1C => OverloadFlag,
            other => Reserved(other),
        }
    }

    /// The raw `data[3]` byte value for this location.
    ///
    /// Round-trips with [`from_raw()`](Self::from_raw).
    pub const fn as_raw(&self) -> u8 {
        use Location::*;
        match *self {
            Unspecified => 0x00,
            Id2821 => 0x02,
            StartOfFrame => 0x03,
            SubstituteRtr => 0x04,
            IdentifierExtension => 0x05,
            Id2018 => 0x06,
            Id1713 => 0x07,
            CrcSequence => 0x08,
            Reserved0 => 0x09,
            DataSection => 0x0A,
            DataLengthCode => 0x0B,
            Rtr => 0x0C,
            Reserved1 => 0x0D,
            Id0400 => 0x0E,
            Id1205 => 0x0F,
            ActiveErrorFlag => 0x11,
            Intermission => 0x12,
            TolerateDominantBits => 0x13,
            PassiveErrorFlag => 0x16,
            ErrorDelimiter => 0x17,
            CrcDelimiter => 0x18,
            AckSlot => 0x19,
            EndOfFrame => 0x1A,
            AckDelimiter => 0x1B,
            OverloadFlag => 0x1C,
            Reserved(v) => v,
        }
    }
}

impl From<u8> for Location {
    fn from(val: u8) -> Self {
        Self::from_raw(val)
    }
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Location::*;
        let msg = match *self {
            Unspecified => "unspecified location",
            StartOfFrame => "start of frame",
            Id2821 => "ID, bits 28-21",
            Id2018 => "ID, bits 20-18",
            SubstituteRtr => "substitute RTR bit",
            IdentifierExtension => "ID, extension",
            Id1713 => "ID, bits 17-13",
            Id1205 => "ID, bits 12-05",
            Id0400 => "ID, bits 04-00",
            Rtr => "RTR bit",
            Reserved1 => "reserved bit 1",
            Reserved0 => "reserved bit 0",
            DataLengthCode => "data length code",
            DataSection => "data section",
            CrcSequence => "CRC sequence",
            CrcDelimiter => "CRC delimiter",
            AckSlot => "ACK slot",
            AckDelimiter => "ACK delimiter",
            EndOfFrame => "end of frame",
            Intermission => "intermission",
            ActiveErrorFlag => "active error flag",
            TolerateDominantBits => "tolerate dominant bits",
            PassiveErrorFlag => "passive error flag",
            ErrorDelimiter => "error delimiter",
            OverloadFlag => "overload flag",
            Reserved(v) => return write!(f, "reserved location ({:#04x})", v),
        };
        write!(f, "{}", msg)
    }
}

// ===== Transceiver faults =====

/// A fault on the CAN High line.
///
/// Decoded from the low nibble of `data[4]` of an error frame. See
/// [`ErrorCause::Transceiver`].
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
#[repr(u8)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CanHighFault {
    /// no wire
    NoWire = libc::CAN_ERR_TRX_CANH_NO_WIRE as u8,
    /// short to BAT
    ShortToBat = libc::CAN_ERR_TRX_CANH_SHORT_TO_BAT as u8,
    /// short to VCC
    ShortToVcc = libc::CAN_ERR_TRX_CANH_SHORT_TO_VCC as u8,
    /// short to GND
    ShortToGnd = libc::CAN_ERR_TRX_CANH_SHORT_TO_GND as u8,
}

impl TryFrom<u8> for CanHighFault {
    type Error = CanErrorDecodingFailure;

    /// Decodes the CAN High nibble (low nibble of `data[4]`).
    fn try_from(val: u8) -> std::result::Result<Self, Self::Error> {
        use CanHighFault::*;
        Ok(match val {
            0x04 => NoWire,
            0x05 => ShortToBat,
            0x06 => ShortToVcc,
            0x07 => ShortToGnd,
            _ => return Err(CanErrorDecodingFailure::InvalidTransceiverError),
        })
    }
}

impl fmt::Display for CanHighFault {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Self::NoWire => "no wire",
            Self::ShortToBat => "short to BAT",
            Self::ShortToVcc => "short to VCC",
            Self::ShortToGnd => "short to GND",
        })
    }
}

/// A fault on the CAN Low line.
///
/// Decoded from the high nibble of `data[4]` of an error frame. See
/// [`ErrorCause::Transceiver`].
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
#[repr(u8)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CanLowFault {
    /// no wire
    NoWire = libc::CAN_ERR_TRX_CANL_NO_WIRE as u8,
    /// short to BAT
    ShortToBat = libc::CAN_ERR_TRX_CANL_SHORT_TO_BAT as u8,
    /// short to VCC
    ShortToVcc = libc::CAN_ERR_TRX_CANL_SHORT_TO_VCC as u8,
    /// short to GND
    ShortToGnd = libc::CAN_ERR_TRX_CANL_SHORT_TO_GND as u8,
    /// short to CAN High
    ShortToCanHigh = libc::CAN_ERR_TRX_CANL_SHORT_TO_CANH as u8,
}

impl TryFrom<u8> for CanLowFault {
    type Error = CanErrorDecodingFailure;

    /// Decodes the CAN Low nibble (high nibble of `data[4]`).
    fn try_from(val: u8) -> std::result::Result<Self, Self::Error> {
        use CanLowFault::*;
        Ok(match val {
            0x40 => NoWire,
            0x50 => ShortToBat,
            0x60 => ShortToVcc,
            0x70 => ShortToGnd,
            0x80 => ShortToCanHigh,
            _ => return Err(CanErrorDecodingFailure::InvalidTransceiverError),
        })
    }
}

impl fmt::Display for CanLowFault {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Self::NoWire => "no wire",
            Self::ShortToBat => "short to BAT",
            Self::ShortToVcc => "short to VCC",
            Self::ShortToGnd => "short to GND",
            Self::ShortToCanHigh => "short to CAN High",
        })
    }
}

/// Get the controller specific error information.
pub trait ControllerSpecificErrorInformation {
    /// Get the controller specific error information.
    fn get_ctrl_err(&self) -> Option<&[u8]>;
}

impl<T: Frame> ControllerSpecificErrorInformation for T {
    /// Get the controller specific error information.
    fn get_ctrl_err(&self) -> Option<&[u8]> {
        let data = self.data();

        if data.len() == 8 {
            Some(&data[5..])
        } else {
            None
        }
    }
}

// ===== CanErrorDecodingFailure =====

/// Error decoding an [`ErrorCause`] from a [`CanErrorFrame`].
///
/// Only two conditions in an error frame are genuinely undecodable, both of
/// them a data byte holding a bit pattern with no defined meaning. Locations
/// (`data[3]`) and protocol violation types (`data[2]`) cannot fail: the
/// former preserves unknown values as [`Location::Reserved`] and the latter
/// has a named type for every bit of the byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum CanErrorDecodingFailure {
    /// `data[1]` had a bit set that no known controller problem claims.
    InvalidControllerProblem,
    /// One half of `data[4]` held an unrecognised transceiver code.
    InvalidTransceiverError,
}

impl error::Error for CanErrorDecodingFailure {}

impl fmt::Display for CanErrorDecodingFailure {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use CanErrorDecodingFailure::*;
        let msg = match *self {
            InvalidControllerProblem => "not a valid controller problem",
            InvalidTransceiverError => "not a valid transceiver error",
        };
        write!(f, "{}", msg)
    }
}

// ===== ConstructionError =====

#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq)]
/// Error that occurs when creating CAN packets
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ConstructionError {
    /// Trying to create a specific frame type from an incompatible type
    WrongFrameType,
    /// CAN ID was outside the range of valid IDs
    IDTooLarge,
    /// Larger payload reported than can be held in the frame.
    TooMuchData,
}

impl error::Error for ConstructionError {}

impl fmt::Display for ConstructionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ConstructionError::*;
        let msg = match *self {
            WrongFrameType => "Incompatible frame type",
            IDTooLarge => "CAN ID too large",
            TooMuchData => "Payload is too large",
        };
        write!(f, "{}", msg)
    }
}

/////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CanErrorFrame, Error};
    use embedded_can::{Error as _, ErrorKind};
    use std::io;

    /// Builds an error frame from raw class bits and data bytes.
    fn frame(bits: u32, data: [u8; 8]) -> CanErrorFrame {
        CanErrorFrame::new_error(bits, &data).unwrap()
    }

    /// Decodes raw class bits + data into a vector of causes.
    fn decode(bits: u32, data: [u8; 8]) -> Vec<ErrorCause> {
        CanError::from(frame(bits, data)).into_iter().collect()
    }

    #[test]
    fn test_errors() {
        const KIND: io::ErrorKind = io::ErrorKind::TimedOut;

        // From an IO error.
        let err = Error::from(io::Error::from(KIND));
        if let Error::Io(ioerr) = err {
            assert_eq!(ioerr.kind(), KIND);
        } else {
            panic!("Wrong error conversion");
        }

        // Straight from an ErrorKind
        let err = Error::from(KIND);
        if let Error::Io(ioerr) = err {
            assert_eq!(ioerr.kind(), KIND);
        } else {
            panic!("Wrong error conversion");
        }
    }

    /// A netlink failure keeps whatever a caller can act on: an error packet
    /// from the kernel keeps its errno, an I/O failure keeps its kind, and the
    /// protocol conditions each get a variant. Nothing lands in an `Io` error
    /// of kind `Other` with only a message, which is what used to happen.
    #[cfg(feature = "netlink")]
    #[test]
    fn netlink_error_conversion() {
        use crate::nl::NlError;
        use neli::{
            consts::rtnl::Rtm,
            err::{RouterError, SocketError},
            rtnl::Ifinfomsg,
        };
        use std::sync::Arc;

        type RtErr = RouterError<Rtm, Ifinfomsg>;

        assert!(matches!(
            Error::from(RtErr::NoAck),
            Error::Nl(NlError::NoAck)
        ));
        assert!(matches!(
            Error::from(RtErr::ClosedChannel),
            Error::Nl(NlError::ClosedChannel)
        ));

        // A real I/O failure stays an I/O error, with its kind intact.
        let err = Error::from(RtErr::Io(io::ErrorKind::PermissionDenied));
        match err {
            Error::Io(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
            other => panic!("expected an I/O error, got {other:?}"),
        }

        // Same for one that arrives through neli's socket layer, where the
        // errno survives the trip and not just the kind.
        let err = Error::from(RtErr::Socket(SocketError::Io(Arc::new(
            io::Error::from_raw_os_error(libc::ENODEV),
        ))));
        match err {
            Error::Io(e) => assert_eq!(e.raw_os_error(), Some(libc::ENODEV)),
            other => panic!("expected an I/O error, got {other:?}"),
        }

        // A message-level failure has no structure to keep, so it is text.
        assert!(matches!(
            Error::from(RtErr::new("malformed attribute")),
            Error::Nl(NlError::Msg(_))
        ));
    }

    /// An errno from a `nix` call reaches the caller as an `Error::Io` with
    /// the errno intact — opening an interface that does not exist reports
    /// `ENODEV` rather than an opaque message.
    #[cfg(feature = "netlink")]
    #[test]
    fn nix_errno_becomes_an_io_error() {
        use crate::nl::CanInterface;

        match CanInterface::open("nosuchcan0") {
            Err(Error::Io(e)) => assert_eq!(e.raw_os_error(), Some(libc::ENODEV)),
            other => panic!("expected an I/O error, got {other:?}"),
        }
    }

    /// The kernel's errno is reachable as an `io::ErrorKind`, so a netlink
    /// rejection can be tested like any other system error.
    #[cfg(feature = "netlink")]
    #[test]
    fn netlink_errno_is_actionable() {
        use crate::nl::NlError;

        let err = NlError::Netlink { errno: libc::EPERM };
        assert_eq!(err.errno(), Some(libc::EPERM));
        assert_eq!(err.io_kind(), Some(io::ErrorKind::PermissionDenied));
        assert_eq!(NlError::NoAck.errno(), None);
        assert_eq!(NlError::NoAck.io_kind(), None);
    }

    /// The whole reason `Error` summarizes the netlink error instead of
    /// carrying it: a `RouterError` is far larger than every other error this
    /// crate reports, and `Error` sits in every `Result` the crate returns.
    #[cfg(feature = "netlink")]
    #[test]
    fn error_stays_smaller_than_a_router_error() {
        use neli::{consts::rtnl::Rtm, err::RouterError, rtnl::Ifinfomsg};
        use std::mem::size_of;

        type RtErr = RouterError<Rtm, Ifinfomsg>;
        assert!(
            size_of::<Error>() < size_of::<RtErr>(),
            "Error is {} bytes, RouterError is {}",
            size_of::<Error>(),
            size_of::<RtErr>()
        );
    }

    /// Pins the actual width of the error types, not just an upper bound.
    ///
    /// `Error` is returned by every fallible call in the crate, so its size
    /// is paid on success as well as failure. The bound in
    /// `error_stays_smaller_than_a_router_error` is 128 bytes, loose enough
    /// to let a regression through unnoticed — `CanError` was 48 bytes, and
    /// therefore `Error` was too, purely because the inline cause array was
    /// larger than it needed to be.
    ///
    /// If this fails, something changed the storage layout. Check
    /// [`NUM_INLINE_CAUSES`] and that `smallvec`'s `union` feature is still
    /// enabled in `Cargo.toml`; without it the array and the heap pointer
    /// carry a separate discriminant and every size here grows by 8.
    #[test]
    fn error_types_stay_narrow() {
        use std::mem::size_of;

        assert_eq!(size_of::<ErrorCause>(), 8, "ErrorCause");
        assert_eq!(size_of::<CanError>(), 24, "CanError");
        assert_eq!(size_of::<Error>(), 32, "Error");
        assert_eq!(size_of::<Result<()>>(), 32, "Result<()>");

        // Two inline causes must be free relative to one; that is the whole
        // reason the capacity is 2 rather than 1.
        assert_eq!(
            size_of::<SmallVec<[ErrorCause; 1]>>(),
            size_of::<SmallVec<[ErrorCause; 2]>>(),
            "capacity 2 should cost the same as capacity 1"
        );
    }

    /// A dump parse error keeps its identity now that it has a variant of its
    /// own, rather than collapsing into an `Io` error, and stays `?`-able into
    /// the crate-level error.
    #[cfg(feature = "dump")]
    #[test]
    fn parse_error_conversion() {
        use crate::dump::ParseError;

        fn lift() -> Result<()> {
            Err(ParseError::InvalidTimestamp)?
        }

        assert!(matches!(
            Error::from(ParseError::InvalidCanFrame),
            Error::Parser(ParseError::InvalidCanFrame)
        ));
        assert!(matches!(
            lift(),
            Err(Error::Parser(ParseError::InvalidTimestamp))
        ));
    }

    // ----- the non-empty invariant -----

    #[test]
    fn non_empty_invariant() {
        let err = CanError::new(ErrorCause::BusOff);
        assert_eq!(err.len(), 1);
        assert!(err.is_single());
        assert!(!err.is_empty());
        assert_eq!(*err.first(), ErrorCause::BusOff);
        assert_eq!(*err.last(), ErrorCause::BusOff);

        // A frame with no class bits at all still yields one cause.
        let err = CanError::from(frame(0, [0; 8]));
        assert_eq!(err.len(), 1);
        assert_eq!(*err.first(), ErrorCause::Unknown(0));
    }

    #[test]
    fn single_cause_does_not_allocate() {
        let err = CanError::new(ErrorCause::BusOff);
        assert!(!err.causes.spilled());
    }

    /// The routine controller-state-change frame does not allocate either.
    ///
    /// `CAN_ERR_CRTL | CAN_ERR_CNT` accompanies essentially every controller
    /// state change and decodes to two causes, so it — not the single-cause
    /// frame — is the case worth keeping off the heap. See
    /// [`NUM_INLINE_CAUSES`].
    #[test]
    fn two_causes_do_not_allocate() {
        let state_change = frame(
            CAN_ERR_CRTL | CAN_ERR_CNT,
            [
                0,
                ControllerProblems::RX_WARNING.bits(),
                0,
                0,
                0,
                0,
                112,
                96,
            ],
        );
        let err = CanError::from(state_change);

        assert_eq!(err.len(), 2, "decoded: {}", err);
        assert!(
            !err.causes.spilled(),
            "the most common error frame must not allocate"
        );

        // Beyond the inline capacity it does spill, which is the documented
        // trade. `sja1000` really does set five classes on one frame.
        let five = frame(
            CAN_ERR_LOSTARB | CAN_ERR_CRTL | CAN_ERR_PROT | CAN_ERR_BUSERROR | CAN_ERR_CNT,
            [3, 0x0D, 0x86, 0x1C, 0, 0, 200, 190],
        );
        let err = CanError::from(five);
        assert_eq!(err.len(), 5, "decoded: {}", err);
        assert!(err.causes.spilled());
    }

    // ----- level 1: multiple classes per frame -----

    #[test]
    fn multi_class_crtl_and_cnt() {
        // The universal controller-state-change frame. m_can and peak_canfd
        // write `cf->can_id |= CAN_ERR_CRTL | CAN_ERR_CNT` literally.
        let mut data = [0u8; 8];
        data[1] = ControllerProblems::RX_PASSIVE.bits();
        data[6] = 130;
        data[7] = 42;
        assert_eq!(
            decode(CAN_ERR_CRTL | CAN_ERR_CNT, data),
            vec![
                ErrorCause::Controller(ControllerProblems::RX_PASSIVE),
                ErrorCause::Counters { tx: 130, rx: 42 },
            ]
        );
    }

    #[test]
    fn multi_class_prot_and_buserror() {
        let mut data = [0u8; 8];
        data[2] = ViolationTypes::STUFF.bits();
        data[3] = 0x08; // CRC sequence
        assert_eq!(
            decode(CAN_ERR_PROT | CAN_ERR_BUSERROR, data),
            vec![
                ErrorCause::Protocol {
                    types: ViolationTypes::STUFF,
                    location: Location::CrcSequence,
                },
                ErrorCause::BusError,
            ]
        );
    }

    #[test]
    fn unknown_class_bits_trail() {
        // 0x400 is above every class bit we know.
        let causes = decode(CAN_ERR_BUSOFF | 0x400, [0; 8]);
        assert_eq!(causes, vec![ErrorCause::BusOff, ErrorCause::Unknown(0x400)]);
    }

    #[test]
    fn class_bit_ordering_is_ascending() {
        let mut data = [0u8; 8];
        data[0] = 7;
        data[1] = ControllerProblems::RX_OVERFLOW.bits();
        data[2] = ViolationTypes::BIT.bits();
        data[4] = 0x04; // CanHigh, no wire
        data[6] = 1;
        data[7] = 2;
        let causes = decode(
            CAN_ERR_TX_TIMEOUT
                | CAN_ERR_LOSTARB
                | CAN_ERR_CRTL
                | CAN_ERR_PROT
                | CAN_ERR_TRX
                | CAN_ERR_ACK
                | CAN_ERR_BUSOFF
                | CAN_ERR_BUSERROR
                | CAN_ERR_RESTARTED
                | CAN_ERR_CNT,
            data,
        );
        assert_eq!(
            causes,
            vec![
                ErrorCause::TransmitTimeout,
                ErrorCause::LostArbitration(7),
                ErrorCause::Controller(ControllerProblems::RX_OVERFLOW),
                ErrorCause::Protocol {
                    types: ViolationTypes::BIT,
                    location: Location::Unspecified,
                },
                ErrorCause::Transceiver {
                    canh: Some(CanHighFault::NoWire),
                    canl: None,
                },
                ErrorCause::NoAck,
                ErrorCause::BusOff,
                ErrorCause::BusError,
                ErrorCause::Restarted,
                ErrorCause::Counters { tx: 1, rx: 2 },
            ]
        );
    }

    // ----- level 2: multiple bits fold into one cause -----

    #[test]
    fn ctrl_multi_bit_symmetric_warning() {
        // What can_change_state() emits when tx_state == rx_state ==
        // CAN_STATE_ERROR_WARNING. Folds into a single Controller cause.
        let mut data = [0u8; 8];
        data[1] = 0x0C;
        assert_eq!(
            decode(CAN_ERR_CRTL, data),
            vec![ErrorCause::Controller(
                ControllerProblems::RX_WARNING | ControllerProblems::TX_WARNING
            )]
        );
    }

    #[test]
    fn ctrl_multi_bit_symmetric_passive() {
        // can_change_state() with both states ERROR_PASSIVE.
        let mut data = [0u8; 8];
        data[1] = 0x30;
        assert_eq!(
            decode(CAN_ERR_CRTL, data),
            vec![ErrorCause::Controller(
                ControllerProblems::RX_PASSIVE | ControllerProblems::TX_PASSIVE
            )]
        );
    }

    #[test]
    fn ctrl_three_bits_sja1000_overrun_plus_warning() {
        // sja1000 sets data[1] = RX_OVERFLOW on a data overrun, then
        // can_change_state() ORs the warning bits in. One folded cause.
        let mut data = [0u8; 8];
        data[1] = 0x0D;
        assert_eq!(
            decode(CAN_ERR_CRTL, data),
            vec![ErrorCause::Controller(
                ControllerProblems::RX_OVERFLOW
                    | ControllerProblems::RX_WARNING
                    | ControllerProblems::TX_WARNING
            )]
        );
    }

    #[test]
    fn ctrl_zero_is_unspecified_not_a_failure() {
        // CAN_ERR_CRTL_UNSPEC: an empty flag set, not a decoding failure.
        assert_eq!(
            decode(CAN_ERR_CRTL, [0; 8]),
            vec![ErrorCause::Controller(ControllerProblems::empty())]
        );
    }

    #[test]
    fn ctrl_unclaimed_bit_reports_failure_after_known_bits() {
        // Bit 7 of data[1] is not claimed by any known problem.
        let mut data = [0u8; 8];
        data[1] = 0x81;
        assert_eq!(
            decode(CAN_ERR_CRTL, data),
            vec![
                ErrorCause::Controller(ControllerProblems::RX_OVERFLOW),
                ErrorCause::DecodingFailure(CanErrorDecodingFailure::InvalidControllerProblem),
            ]
        );
    }

    #[test]
    fn prot_multi_bit_shares_one_location() {
        // mcp251xfd_handle_ivmif() accumulates STUFF|FORM|TX|BIT1|BIT0 into
        // one folded Protocol cause.
        let mut data = [0u8; 8];
        data[2] = 0x9E;
        data[3] = 0x08;
        assert_eq!(
            decode(CAN_ERR_PROT, data),
            vec![ErrorCause::Protocol {
                types: ViolationTypes::FORM
                    | ViolationTypes::STUFF
                    | ViolationTypes::BIT0
                    | ViolationTypes::BIT1
                    | ViolationTypes::TX,
                location: Location::CrcSequence,
            }]
        );
    }

    #[test]
    fn prot_zero_is_unspecified_not_a_failure() {
        // es58x sets CAN_ERR_PROT whenever data[2] OR data[3] is non-zero,
        // so a location-only violation with data[2] == 0 is reachable.
        let mut data = [0u8; 8];
        data[3] = 0x03;
        assert_eq!(
            decode(CAN_ERR_PROT, data),
            vec![ErrorCause::Protocol {
                types: ViolationTypes::empty(),
                location: Location::StartOfFrame,
            }]
        );
    }

    // ----- data[4]: two nibbles -----

    #[test]
    fn trx_both_lines_es58x() {
        // es58x ORs CANH and CANL codes for a single-wire fault:
        //   cf->data[4] |= CAN_ERR_TRX_CANH_NO_WIRE;
        //   cf->data[4] |= CAN_ERR_TRX_CANL_NO_WIRE;
        let mut data = [0u8; 8];
        data[4] = 0x44;
        assert_eq!(
            decode(CAN_ERR_TRX, data),
            vec![ErrorCause::Transceiver {
                canh: Some(CanHighFault::NoWire),
                canl: Some(CanLowFault::NoWire),
            }]
        );
    }

    #[test]
    fn trx_single_line_each_half() {
        let mut data = [0u8; 8];
        data[4] = 0x05;
        assert_eq!(
            decode(CAN_ERR_TRX, data),
            vec![ErrorCause::Transceiver {
                canh: Some(CanHighFault::ShortToBat),
                canl: None,
            }]
        );

        data[4] = 0x80;
        assert_eq!(
            decode(CAN_ERR_TRX, data),
            vec![ErrorCause::Transceiver {
                canh: None,
                canl: Some(CanLowFault::ShortToCanHigh),
            }]
        );
    }

    #[test]
    fn trx_zero_is_unspecified() {
        assert_eq!(
            decode(CAN_ERR_TRX, [0; 8]),
            vec![ErrorCause::Transceiver {
                canh: None,
                canl: None,
            }]
        );
    }

    #[test]
    fn trx_invalid_half_reports_failure() {
        let mut data = [0u8; 8];
        data[4] = 0x03; // no CANH code 0x03
        assert_eq!(
            decode(CAN_ERR_TRX, data),
            vec![
                ErrorCause::Transceiver {
                    canh: None,
                    canl: None,
                },
                ErrorCause::DecodingFailure(CanErrorDecodingFailure::InvalidTransceiverError),
            ]
        );
    }

    // ----- data[3]: total over the whole byte -----

    #[test]
    fn location_decoding_never_fails() {
        // sja1000 writes the raw 5-bit ECC segment, so all of 0x00..=0x1F
        // is reachable; the rest must not blow up either.
        for v in 0u8..=0xFF {
            let loc = Location::from_raw(v);
            assert_eq!(loc.as_raw(), v, "round-trip failed for {:#04x}", v);
        }
    }

    #[test]
    fn location_named_beyond_error_h() {
        // Present in can-utils and emitted by sja1000, absent from
        // linux/can/error.h.
        assert_eq!(Location::from_raw(0x11), Location::ActiveErrorFlag);
        assert_eq!(Location::from_raw(0x13), Location::TolerateDominantBits);
        assert_eq!(Location::from_raw(0x16), Location::PassiveErrorFlag);
        assert_eq!(Location::from_raw(0x17), Location::ErrorDelimiter);
        assert_eq!(Location::from_raw(0x1C), Location::OverloadFlag);
    }

    #[test]
    fn location_unnamed_in_range_is_reserved() {
        for v in [0x01u8, 0x10, 0x14, 0x15, 0x1D, 0x1E, 0x1F] {
            assert_eq!(Location::from_raw(v), Location::Reserved(v));
        }
    }

    // ----- error kinds -----

    #[test]
    fn kind_prefers_specific_over_other() {
        // A controller warning maps only to Other, so the missing ACK must
        // win. Scanning by class in declaration order gets this wrong.
        let mut data = [0u8; 8];
        data[1] = 0x0C;
        let err = CanError::from(frame(CAN_ERR_CRTL | CAN_ERR_ACK, data));
        assert_eq!(err.kind(), ErrorKind::Acknowledge);
        assert!(err.contains_kind(ErrorKind::Acknowledge));
        assert!(err.contains_kind(ErrorKind::Other));
    }

    #[test]
    fn kind_maps_violation_types() {
        let check = |types: ViolationTypes, expect: ErrorKind| {
            let cause = ErrorCause::Protocol {
                types,
                location: Location::Unspecified,
            };
            assert_eq!(cause.kind(), expect, "for {:?}", types);
        };
        check(ViolationTypes::BIT, ErrorKind::Bit);
        check(ViolationTypes::BIT0, ErrorKind::Bit);
        check(ViolationTypes::BIT1, ErrorKind::Bit);
        check(ViolationTypes::FORM, ErrorKind::Form);
        check(ViolationTypes::STUFF, ErrorKind::Stuff);
        check(ViolationTypes::OVERLOAD, ErrorKind::Other);
    }

    #[test]
    fn kind_overrun_from_buffer_overflow() {
        let mut data = [0u8; 8];
        data[1] = ControllerProblems::TX_OVERFLOW.bits();
        let err = CanError::from(frame(CAN_ERR_CRTL, data));
        assert_eq!(err.kind(), ErrorKind::Overrun);
    }

    #[test]
    fn kind_all_other_falls_back() {
        let err = CanError::from(frame(CAN_ERR_BUSOFF | CAN_ERR_RESTARTED, [0; 8]));
        assert_eq!(err.kind(), ErrorKind::Other);
    }

    #[test]
    fn top_level_error_delegates_kind() {
        let mut data = [0u8; 8];
        data[1] = 0x0C;
        let err = Error::from(frame(CAN_ERR_CRTL | CAN_ERR_ACK, data));
        assert_eq!(err.kind(), ErrorKind::Acknowledge);
    }

    // ----- predicates and accessors -----

    #[test]
    fn predicates_and_accessors() {
        let mut data = [0u8; 8];
        data[1] = 0x0C;
        data[6] = 96;
        data[7] = 0;
        let err = CanError::from(frame(CAN_ERR_CRTL | CAN_ERR_CNT | CAN_ERR_BUSOFF, data));

        assert!(err.is_bus_off());
        assert!(err.has_counters());
        assert!(!err.is_no_ack());
        assert_eq!(err.counters(), Some((96, 0)));
        assert_eq!(
            err.controller(),
            Some(ControllerProblems::RX_WARNING | ControllerProblems::TX_WARNING)
        );
        assert_eq!(err.protocol(), None);
    }

    // ----- Display -----

    #[test]
    fn display_single_is_bare() {
        let err = CanError::new(ErrorCause::BusOff);
        assert_eq!(err.to_string(), "bus off");
    }

    #[test]
    fn display_multi_is_semicolon_joined() {
        let mut data = [0u8; 8];
        data[1] = 0x0C;
        data[6] = 96;
        data[7] = 0;
        let err = CanError::from(frame(CAN_ERR_CRTL | CAN_ERR_CNT, data));
        assert_eq!(
            err.to_string(),
            "controller problem: rx warning, tx warning; error counters: tx=96, rx=0"
        );
    }

    #[test]
    fn display_violations_at_one_location() {
        let mut data = [0u8; 8];
        data[2] = 0x9E;
        data[3] = 0x08;
        let err = CanError::from(frame(CAN_ERR_PROT | CAN_ERR_BUSERROR, data));
        assert_eq!(
            err.to_string(),
            "protocol violation at CRC sequence: frame format error, \
             bit stuffing error, unable to send dominant bit, \
             unable to send recessive bit, error on transmission; bus error"
        );
    }

    #[test]
    fn display_unknown_in_hex() {
        let err = CanError::new(ErrorCause::Unknown(0x400));
        assert_eq!(err.to_string(), "unknown error (0x400)");
    }

    // ----- iteration / conversion plumbing -----

    #[test]
    fn iteration_by_value_and_by_ref() {
        let err = CanError::from_multiple(
            ErrorCause::BusOff,
            [ErrorCause::NoAck, ErrorCause::Restarted],
        );
        assert_eq!(err.len(), 3);
        assert!(!err.is_single());
        assert_eq!(*err.last(), ErrorCause::Restarted);

        let by_ref: Vec<_> = (&err).into_iter().copied().collect();
        let by_val: Vec<_> = err.clone().into_iter().collect();
        assert_eq!(by_ref, by_val);
        assert_eq!(by_ref.len(), 3);

        let via_iter: Vec<_> = err.causes().copied().collect();
        assert_eq!(via_iter, by_val);
    }

    #[test]
    fn single_cause_promotes_to_error() {
        let err: CanError = ErrorCause::BusOff.into();
        assert!(err.is_single());

        // ... and through the top-level Error.
        let err: Error = ErrorCause::BusOff.into();
        match err {
            Error::Can(err) => assert_eq!(*err.first(), ErrorCause::BusOff),
            _ => panic!("expected a CAN error"),
        }
    }

    #[test]
    fn from_iter_checked_rejects_empty() {
        assert!(CanError::from_iter_checked(std::iter::empty()).is_none());
        assert!(CanError::from_iter_checked([ErrorCause::BusOff]).is_some());
    }
}