cyme 3.0.1

List system USB buses and devices. A modern cross-platform lsusb
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
//! Provides the main utilities to display USB types within this crate - primarily used by `cyme` binary.
//!
//! TODO: There is some repeat code that could probably be made into functions/generics
use clap::ValueEnum;
use colored::*;
use fastrand;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::cmp;
use std::collections::HashMap;
use std::hash::Hash;
use std::io::{self, Write};
use strum::{IntoEnumIterator, VariantArray};
use strum_macros::{Display, EnumIter, VariantArray};
use unicode_width::UnicodeWidthStr;

use crate::colour;
use crate::error::Result;
use crate::icon;
use crate::profiler::{Bus, Device, DeviceFilter, SystemProfile};
use crate::types::NumericalUnit;
use crate::usb::{
    path::ConfigurationPath, path::DevicePath, path::EndpointPath, path::PortPath, BaseClass,
    ConfigAttributes, Configuration, DeviceExtra, Direction, Endpoint, Interface,
};

const ICON_HEADING: &str = "I";
const DEFAULT_AUTO_WIDTH: u16 = 80; // default terminal width to scale if None returned for size
const MIN_VARIABLE_STRING_LEN: usize = 5; // minimum variable string length to scale to
const LIST_INSET_SPACES: u8 = 2; // number of spaces for non-tree inset

/// Colouring control for the output
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum, Default)]
#[serde(rename_all = "kebab-case")]
pub enum ColorWhen {
    /// Show colours if the output goes to an interactive console
    #[default]
    Auto,
    /// Always apply colouring to the output
    Always,
    /// Never apply colouring to the output
    Never,
}

impl std::fmt::Display for ColorWhen {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Icon control for the output
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum, Default)]
#[serde(rename_all = "kebab-case")]
pub enum IconWhen {
    /// Show icon blocks if the [`Encoding`] supports icons matched in the [`icon::IconTheme`]
    #[default]
    Auto,
    /// Always print icon blocks if included in configured blocks
    Always,
    /// Never print icon blocks
    Never,
}

impl std::fmt::Display for IconWhen {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl IconWhen {
    fn retain_ref<B: BlockEnum, T>(
        &self,
        devices: &[&T],
        blocks: &mut Vec<impl Block<B, T>>,
        settings: &PrintSettings,
    ) {
        match self {
            IconWhen::Never => {
                blocks.retain(|b| !b.is_icon());
            }
            IconWhen::Auto => {
                let valid_icons = devices
                    .iter()
                    // all must be valid to avoid tofu chars
                    .all(|d| has_valid_icons(*d, blocks, settings));
                if settings.icons.is_none() || !valid_icons {
                    log::debug!("{:?} removing icon blocks", settings.icon_when);
                    blocks.retain(|b| !b.is_icon());
                }
            }
            IconWhen::Always => {
                if settings.icons.is_none() {
                    log::warn!(
                        "{:?} blocks requested but no icons provided",
                        settings.icon_when
                    );
                }
            }
        }
    }

    fn retain<B: BlockEnum, T>(
        &self,
        devices: &[T],
        blocks: &mut Vec<impl Block<B, T>>,
        settings: &PrintSettings,
    ) {
        match self {
            IconWhen::Never => {
                blocks.retain(|b| !b.is_icon());
            }
            IconWhen::Auto => {
                let valid_icons = devices
                    .iter()
                    // all must be valid to avoid tofu chars
                    .all(|d| has_valid_icons(d, blocks, settings));
                if settings.icons.is_none() || !valid_icons {
                    log::debug!("{:?} removing icon blocks", settings.icon_when);
                    blocks.retain(|b| !b.is_icon());
                }
            }
            IconWhen::Always => {
                if settings.icons.is_none() {
                    log::warn!(
                        "{:?} blocks requested but no icons provided",
                        settings.icon_when
                    );
                }
            }
        }
    }
}

/// Character encoding control for the output
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum, Default)]
#[serde(rename_all = "kebab-case")]
pub enum Encoding {
    /// Use UTF-8 private use area characters such as those used by NerdFont to show glyph icons
    #[default]
    Glyphs,
    /// Use only standard UTF-8 characters for the output; no private use area glyph icons
    Utf8,
    /// Use only ASCII characters for the output; 0x00 - 0x7F (127 chars)
    Ascii,
}

impl std::fmt::Display for Encoding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl Encoding {
    /// Returns if a char is valid for the encoding for not
    ///
    /// ```
    /// use cyme::display::Encoding;
    ///
    /// let enc = Encoding::Ascii;
    /// assert!(enc.char_is_valid('I'));
    /// assert!(!enc.char_is_valid('\u{2000}'));
    /// assert!(!enc.char_is_valid('●'));
    ///
    /// let enc = Encoding::Utf8;
    /// assert!(enc.char_is_valid('I'));
    /// assert!(enc.char_is_valid('\u{2000}'));
    /// assert!(enc.char_is_valid('●'));
    /// assert!(!enc.char_is_valid('\u{e001}'));
    /// assert!(!enc.char_is_valid(''));
    ///
    /// let enc = Encoding::Glyphs;
    /// assert!(enc.char_is_valid('I'));
    /// assert!(enc.char_is_valid('\u{2000}'));
    /// assert!(enc.char_is_valid('\u{f287}'));
    /// assert!(enc.char_is_valid('\u{e001}'));
    /// assert!(enc.char_is_valid(''));
    /// ```
    pub fn char_is_valid(&self, c: char) -> bool {
        match self {
            Encoding::Ascii if !c.is_ascii() => false,
            // not inside private use area
            Encoding::Utf8 => !matches!(c,
                '\u{E000}'..='\u{F8FF}' |
                '\u{F0000}'..='\u{FFFFD}' |
                '\u{100000}'..='\u{10FFFD}'),
            _ => true,
        }
    }

    /// Returns if a str is valid for the encoding for not
    ///
    /// ```
    /// use cyme::display::Encoding;
    ///
    /// let enc = Encoding::Ascii;
    /// assert!(enc.str_is_valid("hello world"));
    /// assert!(!enc.str_is_valid("├──")); // utf-8 tree
    /// assert!(!enc.str_is_valid("chip "));
    ///
    /// let enc = Encoding::Utf8;
    /// assert!(enc.str_is_valid("hello world"));
    /// assert!(enc.str_is_valid("├──")); // utf-8 tree
    /// assert!(!enc.str_is_valid("chip "));
    ///
    /// let enc = Encoding::Glyphs;
    /// assert!(enc.str_is_valid("hello world"));
    /// assert!(enc.str_is_valid("├──")); // utf-8 tree
    /// assert!(enc.str_is_valid("chip "));
    /// ```
    pub fn str_is_valid(&self, s: &str) -> bool {
        s.chars().all(|c| self.char_is_valid(c))
    }
}

/// Info that can be printed about a [`Device`]
#[non_exhaustive]
#[derive(
    Debug,
    EnumIter,
    VariantArray,
    ValueEnum,
    Display,
    Copy,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Clone,
    Hash,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum DeviceBlocks {
    /// Number of bus device is attached
    BusNumber,
    /// Bus issued device number
    DeviceNumber,
    /// Position of device in parent branch
    BranchPosition,
    /// Linux style port path
    PortPath,
    /// Linux udev reported syspath
    SysPath,
    /// Linux udev reported driver loaded for device
    Driver,
    /// Icon based on VID/PID
    Icon,
    /// Unique vendor identifier - purchased from USB IF
    VendorId,
    /// Vendor unique product identifier
    ProductId,
    /// Unique vendor identifier and product identifier as a string formatted 'vid:pid' like lsusb
    VidPid,
    /// The device name as reported in descriptor or using usb_ids if None
    Name,
    /// The device manufacturer as provided in descriptor or using usb_ids if None
    Manufacturer,
    /// The device product name as reported by usb_ids vidpid lookup
    ProductName,
    /// The device vendor name as reported by usb_ids vid lookup
    VendorName,
    /// Device serial string as reported by descriptor
    Serial,
    /// Advertised device capable speed
    Speed,
    /// Negotiated device speed as connected
    NegotiatedSpeed,
    /// Advertised device speed as the USB-IF label string
    SpeedLabel,
    /// Negotiated device speed as the USB-IF label string
    NegotiatedSpeedLabel,
    /// Position along all branches back to trunk device
    TreePositions,
    /// macOS system_profiler only - actually bus current in mA not power!
    BusPower,
    /// macOS system_profiler only - actually bus current used in mA not power!
    BusPowerUsed,
    /// macOS system_profiler only - actually bus current used in mA not power!
    ExtraCurrentUsed,
    /// The device version
    BcdDevice,
    /// The supported USB version
    BcdUsb,
    /// Base class enum of interface provided by USB IF - only available when using libusb
    #[serde(alias = "class-code")] // was called ClassCode in previous versions
    BaseClass,
    /// Sub-class value of interface provided by USB IF - only available when using libusb
    SubClass,
    /// Prototol value for interface provided by USB IF - only available when using libusb
    Protocol,
    /// Class name from USB IDs repository
    UidClass,
    /// Sub-class name from USB IDs repository
    UidSubClass,
    /// Protocol name from USB IDs repository
    UidProtocol,
    /// Fully defined USB Class Code enum based on BaseClass/SubClass/Protocol triplet
    Class,
    /// Base class as number value rather than enum
    #[serde(alias = "class-value")] // was called ClassCode in previous versions
    BaseValue,
    /// Last time device was seen
    LastEvent,
    /// Event icon
    EventIcon,
    /// Advertised device speed as USB-IF Gen NxM operation mode string (e.g. 'USB 3.2 Gen 2x1')
    OperationMode,
    /// Negotiated device speed as USB-IF Gen NxM operation mode string
    NegotiatedOperationMode,
    /// Advertised device speed as USB-IF recommended marketing label (e.g. 'USB 5 Gbps')
    SpeedMarketingLabel,
    /// Negotiated device speed as USB-IF recommended marketing label
    NegotiatedSpeedMarketingLabel,
}

/// Info that can be printed about a [`Bus`]
#[non_exhaustive]
#[derive(
    Debug,
    Copy,
    EnumIter,
    VariantArray,
    ValueEnum,
    Display,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Hash,
    Clone,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum BusBlocks {
    /// System bus number identifier
    BusNumber,
    /// Icon based on VID/PID
    Icon,
    /// System internal bus name based on Root Hub device name
    Name,
    /// System internal bus provider name
    HostController,
    /// Vendor name of PCI Host Controller from pci.ids
    HostControllerVendor,
    /// Device name of PCI Host Controller from pci.ids
    HostControllerDevice,
    /// PCI vendor ID (VID)
    PciVendor,
    /// PCI device ID (PID)
    PciDevice,
    /// PCI Revsision ID
    PciRevision,
    /// syspath style port path to bus, applicable to Linux only
    PortPath,
}

/// Info that can be printed about a [`Configuration`]
#[non_exhaustive]
#[derive(
    Debug,
    Copy,
    EnumIter,
    VariantArray,
    ValueEnum,
    Display,
    Eq,
    PartialEq,
    Hash,
    Clone,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum ConfigurationBlocks {
    /// Name from string descriptor
    Name,
    /// Number of config, bConfigurationValue; value to set to enable to configuration
    Number,
    /// Interfaces available for this configuruation
    NumInterfaces,
    /// Attributes of configuration, bmAttributes
    Attributes,
    /// Icon representation of bmAttributes
    IconAttributes,
    /// Maximum current consumption in mA
    MaxPower,
}

/// Info that can be printed about a [`Interface`]
#[non_exhaustive]
#[derive(
    Debug,
    Copy,
    EnumIter,
    VariantArray,
    ValueEnum,
    Display,
    Eq,
    PartialEq,
    Hash,
    Clone,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum InterfaceBlocks {
    /// Name from string descriptor
    Name,
    /// Interface number
    Number,
    /// Interface port path (only applicable on Linux)
    PortPath,
    /// Base class enum of interface provided by USB IF
    #[serde(alias = "class-code")] // was called ClassCode in previous versions
    BaseClass,
    /// Sub-class value of interface provided by USB IF
    SubClass,
    /// Prototol value for interface provided by USB IF
    Protocol,
    /// Interfaces can have the same number but an alternate settings defined here
    AltSetting,
    /// Driver obtained from udev (Linux only)
    Driver,
    /// syspath obtained from udev (Linux only)
    SysPath,
    /// The /dev/ device paths for the interface if any exist (Linux only)
    ///
    /// For example a CDC ACM device may have `/dev/ttyACM0`, MSD devices may have `/dev/sdX` paths per LUN
    DevPath,
    /// Mount paths for MSD interfaces in CSV partition_no:mount_path format (Linux only)
    MountPaths,
    /// An interface can have many endpoints
    NumEndpoints,
    /// Icon based on BaseClass/SubCode/Protocol
    Icon,
    /// Class name from USB IDs repository
    UidClass,
    /// Sub-class name from USB IDs repository
    UidSubClass,
    /// Protocol name from USB IDs repository
    UidProtocol,
    /// Fully defined USB Class Code based on BaseClass/SubClass/Protocol triplet
    Class,
    /// Base class as number value rather than enum
    #[serde(alias = "class-value")]
    BaseValue,
}

/// Info that can be printed about a [`Endpoint`]
#[non_exhaustive]
#[derive(
    Debug,
    Copy,
    EnumIter,
    VariantArray,
    ValueEnum,
    Display,
    Eq,
    PartialEq,
    Hash,
    Clone,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum EndpointBlocks {
    /// Endpoint number on interface
    Number,
    /// Direction of data into endpoint
    Direction,
    /// Type of data transfer endpoint accepts
    TransferType,
    /// Synchronisation type (Iso mode)
    SyncType,
    /// Usage type (Iso mode)
    UsageType,
    /// Maximum packet size in bytes endpoint can send/receive
    MaxPacketSize,
    /// Interval for polling endpoint data transfers. Value in frame counts. Ignored for Bulk & Control Endpoints. Isochronous must equal 1 and field may range from 1 to 255 for interrupt endpoints.
    Interval,
}

/// Length of field printed by block
#[derive(Debug, Eq, PartialEq)]
pub enum BlockLength {
    /// Fixed length like numbers with padding
    Fixed(usize),
    /// Variable length such as string descriptors - contained value is the heading (min) length
    Variable(usize),
}

impl BlockLength {
    /// Get the length contained in Enum
    pub fn len(self) -> usize {
        match self {
            BlockLength::Fixed(s) => s,
            BlockLength::Variable(s) => s,
        }
    }

    /// Is the length zero
    pub fn is_empty(self) -> bool {
        match self {
            BlockLength::Fixed(s) => s == 0,
            BlockLength::Variable(s) => s == 0,
        }
    }

    /// Get the fixed length if `[BlockLength::Fixed]` else None
    pub fn fixed_len(self) -> Option<usize> {
        match self {
            BlockLength::Fixed(s) => Some(s),
            _ => None,
        }
    }

    /// Get the variable length if `[BlockLength::Variable]` else None
    pub fn variable_len(self) -> Option<usize> {
        match self {
            BlockLength::Variable(s) => Some(s),
            _ => None,
        }
    }
}

/// Helper trait to allow for generic block handling
pub trait BlockEnum: Eq + Hash + VariantArray + ValueEnum {}
impl BlockEnum for DeviceBlocks {}
impl BlockEnum for BusBlocks {}
impl BlockEnum for ConfigurationBlocks {}
impl BlockEnum for InterfaceBlocks {}
impl BlockEnum for EndpointBlocks {}

/// Intended to be `impl` by a xxxBlocks `enum`
pub trait Block<B: BlockEnum, T> {
    /// The inset when printing non-tree as a list
    const INSET: u8 = 0;

    /// List of default blocks to use for printing T with optional `verbose` for maximum verbosity
    fn default_blocks(verbose: bool) -> Vec<Self>
    where
        Self: Sized;

    /// Example blocks for generated files
    fn example_blocks() -> Vec<Self>
    where
        Self: Sized,
    {
        Self::default_blocks(false)
    }

    /// Returns the length of block value given device data - like block_length but actual device field length rather than fixed/heading
    fn len(&self, d: &[&T]) -> usize;

    /// Returns length type and usize contained, [`BlockLength::Variable`] will be heading usize without actual device data
    fn block_length(&self) -> BlockLength;

    /// Creates a HashMap of B keys to usize of longest value for that key in the `d` Vec or heading if > this; values can then be padded to match this
    fn generate_padding(d: &[&T]) -> HashMap<B, usize>;

    /// Colour the block String
    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString;

    /// Creates the heading for the block value, for use with the heading flag
    fn heading(&self) -> &str;

    /// Pads the heading with provided padding block HashMap
    fn heading_padded(&self, pad: &HashMap<B, usize>) -> String;

    /// Returns whether the value intended for the block is a variable length type (string descriptor)
    fn value_is_variable_length(&self) -> bool {
        match self.block_length() {
            BlockLength::Fixed(_) => false,
            BlockLength::Variable(_) => true,
        }
    }

    /// Formats the value associated with the block into a display String
    fn format_value(
        &self,
        d: &T,
        pad: &HashMap<B, usize>,
        settings: &PrintSettings,
    ) -> Option<String>;

    /// Formats u16 values like VID as base16 or base10 depending on decimal setting
    fn format_base_u16(v: u16, settings: &PrintSettings) -> String {
        if settings.decimal {
            // pad 6 not 5 to maintain 0x padding
            format!("{v:6}")
        } else {
            format!("0x{v:04x}")
        }
    }

    /// Formats u8 values like codes as base16 or base10 depending on decimal setting
    fn format_base_u8(v: u8, settings: &PrintSettings) -> String {
        if settings.decimal {
            format!("{v:4}")
        } else {
            format!("0x{v:02x}")
        }
    }

    /// Formats VID and PID values into a string like "vid:pid" with padding
    fn format_vidpid(v: Option<u16>, p: Option<u16>, settings: &PrintSettings) -> String {
        match (v, p) {
            (Some(v), Some(p)) => {
                if settings.decimal {
                    format!("{v:>5}:{p:<5}")
                } else {
                    format!(" {v:04x}:{p:04x} ")
                }
            }
            _ => format!("{:>5}:{:<5}", "-", "-"),
        }
    }

    /// If the block is used for icons
    fn is_icon(&self) -> bool {
        false
    }

    /// Get static array of all blocks for this type
    fn all_blocks() -> &'static [B]
    where
        Self: Sized,
    {
        B::VARIANTS
    }
}

impl DeviceBlocks {
    /// Default `DeviceBlocks` for watch mode printing
    pub fn default_watch_blocks(verbose: bool, tree: bool) -> Vec<Self> {
        let mut blocks = if tree {
            Self::default_device_tree_blocks()
        } else {
            Self::default_blocks(verbose)
        };
        blocks.push(DeviceBlocks::EventIcon);
        blocks.push(DeviceBlocks::LastEvent);
        blocks
    }

    /// Default `DeviceBlocks` for tree printing are different to list, get them here
    pub fn default_device_tree_blocks() -> Vec<Self> {
        #[cfg(target_os = "linux")]
        {
            vec![
                DeviceBlocks::Icon,
                DeviceBlocks::BranchPosition,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::Name,
                DeviceBlocks::Serial,
                DeviceBlocks::Driver,
            ]
        }

        #[cfg(not(target_os = "linux"))]
        {
            vec![
                DeviceBlocks::Icon,
                DeviceBlocks::BranchPosition,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::Name,
                DeviceBlocks::Serial,
            ]
        }
    }
}

impl Block<DeviceBlocks, Device> for DeviceBlocks {
    #[cfg(target_os = "linux")]
    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                DeviceBlocks::BusNumber,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::TreePositions,
                DeviceBlocks::PortPath,
                DeviceBlocks::Icon,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::BcdDevice,
                DeviceBlocks::BcdUsb,
                DeviceBlocks::BaseValue,
                DeviceBlocks::BaseClass,
                DeviceBlocks::SubClass,
                DeviceBlocks::UidSubClass,
                DeviceBlocks::Protocol,
                DeviceBlocks::UidProtocol,
                DeviceBlocks::Name,
                DeviceBlocks::Manufacturer,
                DeviceBlocks::Serial,
                DeviceBlocks::Driver,
                DeviceBlocks::SysPath,
                DeviceBlocks::Speed,
            ]
        } else {
            vec![
                DeviceBlocks::BusNumber,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::Icon,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::Name,
                DeviceBlocks::Serial,
                DeviceBlocks::Driver,
                DeviceBlocks::Speed,
            ]
        }
    }

    #[cfg(not(target_os = "linux"))]
    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                DeviceBlocks::BusNumber,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::TreePositions,
                DeviceBlocks::PortPath,
                DeviceBlocks::Icon,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::BcdDevice,
                DeviceBlocks::BcdUsb,
                DeviceBlocks::BaseValue,
                DeviceBlocks::BaseClass,
                DeviceBlocks::SubClass,
                DeviceBlocks::UidSubClass,
                DeviceBlocks::Protocol,
                DeviceBlocks::UidProtocol,
                DeviceBlocks::Name,
                DeviceBlocks::Manufacturer,
                DeviceBlocks::Serial,
                DeviceBlocks::Speed,
            ]
        } else {
            vec![
                DeviceBlocks::BusNumber,
                DeviceBlocks::DeviceNumber,
                DeviceBlocks::Icon,
                DeviceBlocks::VendorId,
                DeviceBlocks::ProductId,
                DeviceBlocks::Name,
                DeviceBlocks::Serial,
                DeviceBlocks::Speed,
            ]
        }
    }

    fn example_blocks() -> Vec<Self> {
        vec![
            DeviceBlocks::BusNumber,
            DeviceBlocks::DeviceNumber,
            DeviceBlocks::Icon,
            DeviceBlocks::VendorId,
            DeviceBlocks::ProductId,
            DeviceBlocks::Name,
            DeviceBlocks::Serial,
            DeviceBlocks::Driver,
            DeviceBlocks::Speed,
        ]
    }

    fn len(&self, d: &[&Device]) -> usize {
        match self {
            DeviceBlocks::Name => d.iter().map(|d| d.name.width()).max().unwrap_or(0),
            DeviceBlocks::Serial => d
                .iter()
                .flat_map(|d| d.serial_num.as_ref().map(|s| s.width()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::Manufacturer => d
                .iter()
                .flat_map(|d| d.manufacturer.as_ref().map(|s| s.width()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::TreePositions => d
                .iter()
                .map(|d| d.location_id.tree_positions.len() * 2)
                .max()
                .unwrap_or(0),
            DeviceBlocks::PortPath => d
                .iter()
                // byte len ok as I know it's all ascii
                .map(|d| d.port_path().to_string().len())
                .max()
                .unwrap_or(0),
            DeviceBlocks::SysPath => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.syspath.as_ref().map(|s| s.len()))
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::Driver => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.driver.as_ref().map(|s| s.len()))
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::ProductName => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.product_name.as_ref().map(|s| s.width()))
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::VendorName => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.vendor.as_ref().map(|s| s.width()))
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::BaseClass => d
                .iter()
                .flat_map(|d| d.class.as_ref().map(|c| c.to_string().len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::UidClass => d
                .iter()
                .flat_map(|d| d.class_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::UidSubClass => d
                .iter()
                .flat_map(|d| d.sub_class_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::UidProtocol => d
                .iter()
                .flat_map(|d| d.protocol_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::Class => d
                .iter()
                .map(|d| d.fully_defined_class().map_or(0, |c| c.to_string().len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::LastEvent => d
                .iter()
                .flat_map(|d| d.last_event().map(|s| s.to_string().len()))
                .max()
                .unwrap_or(0),
            DeviceBlocks::SpeedLabel => d
                .iter()
                .flat_map(|d| {
                    d.device_speed
                        .as_ref()
                        .and_then(|s| s.original_label())
                        .map(|l| l.len())
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::NegotiatedSpeedLabel => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.negotiated_speed.as_ref())
                        .map(|s| s.original_label().len())
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::SpeedMarketingLabel => d
                .iter()
                .flat_map(|d| {
                    d.device_speed
                        .as_ref()
                        .and_then(|s| s.marketing_label())
                        .map(|l| l.len())
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::NegotiatedSpeedMarketingLabel => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.negotiated_speed.as_ref())
                        .map(|s| s.marketing_label().len())
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::OperationMode => d
                .iter()
                .flat_map(|d| {
                    d.device_speed
                        .as_ref()
                        .and_then(|s| s.operation_mode())
                        .map(|m| m.to_string().len())
                })
                .max()
                .unwrap_or(0),
            DeviceBlocks::NegotiatedOperationMode => d
                .iter()
                .flat_map(|d| {
                    d.extra
                        .as_ref()
                        .and_then(|e| e.negotiated_speed.as_ref())
                        .and_then(|s| s.operation_mode())
                        .map(|m| m.to_string().len())
                })
                .max()
                .unwrap_or(0),
            _ => self.block_length().len(),
        }
    }

    fn generate_padding(d: &[&Device]) -> HashMap<Self, usize> {
        DeviceBlocks::iter()
            .map(|b| (b, cmp::max(b.heading().len(), b.len(d))))
            .collect()
    }

    fn format_value(
        &self,
        d: &Device,
        pad: &HashMap<Self, usize>,
        settings: &PrintSettings,
    ) -> Option<String> {
        match self {
            DeviceBlocks::BusNumber => Some(format!("{:3}", d.location_id.bus)),
            DeviceBlocks::DeviceNumber => Some(format!("{:3}", d.location_id.number)),
            DeviceBlocks::BranchPosition => Some(format!("{:3}", d.get_branch_position())),
            DeviceBlocks::PortPath => Some(format!(
                "{:pad$}",
                d.port_path().to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            DeviceBlocks::SysPath => Some(match d.extra.as_ref() {
                Some(e) => format!(
                    "{:pad$}",
                    e.syspath.as_ref().unwrap_or(&format!(
                        "{:pad$}",
                        "-",
                        pad = pad.get(self).unwrap_or(&0)
                    )),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::Driver => Some(match d.extra.as_ref() {
                Some(e) => format!(
                    "{:pad$}",
                    e.driver.as_ref().unwrap_or(&format!(
                        "{:pad$}",
                        "-",
                        pad = pad.get(self).unwrap_or(&0)
                    )),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::ProductName => Some(match d.extra.as_ref() {
                Some(e) => format!(
                    "{:pad$}",
                    e.product_name.as_ref().unwrap_or(&format!(
                        "{:pad$}",
                        "-",
                        pad = pad.get(self).unwrap_or(&0)
                    )),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::VendorName => Some(match d.extra.as_ref() {
                Some(e) => format!(
                    "{:pad$}",
                    e.vendor.as_ref().unwrap_or(&format!(
                        "{:pad$}",
                        "-",
                        pad = pad.get(self).unwrap_or(&0)
                    )),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::Icon => settings.icons.as_ref().map(|i| i.get_device_icon(d)),
            DeviceBlocks::VendorId => Some(match d.vendor_id {
                Some(v) => Self::format_base_u16(v, settings),
                None => format!("{:>6}", "-"),
            }),
            DeviceBlocks::ProductId => Some(match d.product_id {
                Some(v) => Self::format_base_u16(v, settings),
                None => format!("{:>6}", "-"),
            }),
            DeviceBlocks::VidPid => Some(Self::format_vidpid(d.vendor_id, d.product_id, settings)),
            DeviceBlocks::Name => Some(format!(
                "{:pad$}",
                d.name,
                pad = pad.get(self).unwrap_or(&0)
            )),
            DeviceBlocks::Manufacturer => Some(match d.manufacturer.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::Serial => Some(match d.serial_num.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::Speed => Some(match d.device_speed.as_ref() {
                Some(v) => format!("{:>10}", v.to_string()),
                None => format!("{:>10}", "-"),
            }),
            DeviceBlocks::NegotiatedSpeed => Some(
                match d.extra.as_ref().and_then(|e| e.negotiated_speed.as_ref()) {
                    Some(v) => {
                        let nu = NumericalUnit::<f32>::from(v);
                        format!("{:>10}", nu.to_string())
                    }
                    None => format!("{:>10}", "-"),
                },
            ),
            DeviceBlocks::SpeedLabel => Some(match d.device_speed.as_ref() {
                Some(v) => format!(
                    "{:pad$}",
                    v.original_label().unwrap_or_else(|| "-".into()),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::NegotiatedSpeedLabel => Some(
                match d.extra.as_ref().and_then(|e| e.negotiated_speed.as_ref()) {
                    Some(v) => format!(
                        "{:pad$}",
                        v.original_label(),
                        pad = pad.get(self).unwrap_or(&0)
                    ),
                    None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
                },
            ),
            DeviceBlocks::SpeedMarketingLabel => Some(match d.device_speed.as_ref() {
                Some(v) => format!(
                    "{:pad$}",
                    v.marketing_label().unwrap_or_else(|| "-".into()),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::NegotiatedSpeedMarketingLabel => Some(
                match d.extra.as_ref().and_then(|e| e.negotiated_speed.as_ref()) {
                    Some(v) => format!(
                        "{:pad$}",
                        v.marketing_label(),
                        pad = pad.get(self).unwrap_or(&0)
                    ),
                    None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
                },
            ),
            DeviceBlocks::OperationMode => Some(
                match d.device_speed.as_ref().and_then(|s| s.operation_mode()) {
                    Some(v) => format!("{:pad$}", v.to_string(), pad = pad.get(self).unwrap_or(&0)),
                    None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
                },
            ),
            DeviceBlocks::NegotiatedOperationMode => Some(
                match d
                    .extra
                    .as_ref()
                    .and_then(|e| e.negotiated_speed.as_ref())
                    .and_then(|s| s.operation_mode())
                {
                    Some(v) => format!("{:pad$}", v.to_string(), pad = pad.get(self).unwrap_or(&0)),
                    None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
                },
            ),
            DeviceBlocks::TreePositions => Some(format!(
                "{:pad$}",
                format!("{:}", d.location_id.tree_positions.iter().format("-")),
                pad = pad.get(self).unwrap_or(&0)
            )),
            DeviceBlocks::BusPower => Some(match d.bus_power {
                Some(v) => format!("{v:3} mA"),
                None => format!("{:>6}", "-"),
            }),
            DeviceBlocks::BusPowerUsed => Some(match d.bus_power_used {
                Some(v) => format!("{v:3} mA"),
                None => format!("{:>6}", "-"),
            }),
            DeviceBlocks::ExtraCurrentUsed => Some(match d.extra_current_used {
                Some(v) => format!("{v:3} mA"),
                None => format!("{:>6}", "-"),
            }),
            DeviceBlocks::BcdDevice => Some(match d.bcd_device {
                Some(v) => format!("{:5}", v.to_string()),
                None => format!("{:>5}", "-"),
            }),
            DeviceBlocks::BcdUsb => Some(match d.bcd_usb {
                Some(v) => format!("{:5}", v.to_string()),
                None => format!("{:>5}", "-"),
            }),
            DeviceBlocks::BaseClass => Some(match d.class.as_ref() {
                Some(v) => format!("{:pad$}", v.to_string(), pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::SubClass => Some(match d.sub_class.as_ref() {
                Some(v) => Self::format_base_u8(*v, settings),
                None => format!("{:>4}", "-"),
            }),
            DeviceBlocks::Protocol => Some(match d.protocol.as_ref() {
                Some(v) => Self::format_base_u8(*v, settings),
                None => format!("{:>4}", "-"),
            }),
            DeviceBlocks::UidClass => Some(match d.class_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::UidSubClass => Some(match d.sub_class_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::UidProtocol => Some(match d.protocol_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::Class => Some(match d.fully_defined_class() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::BaseValue => Some(match d.class.as_ref() {
                Some(v) => Self::format_base_u8((*v).into(), settings),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::LastEvent => Some(match d.last_event() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            DeviceBlocks::EventIcon => match d.last_event() {
                Some(e) => settings.icons.as_ref().map(|i| i.get_event_icon(&e)),
                None => None,
            },
        }
    }

    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString {
        match self {
            DeviceBlocks::BcdUsb
            | DeviceBlocks::BcdDevice
            | DeviceBlocks::DeviceNumber
            | DeviceBlocks::LastEvent => ct.number.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::BusNumber
            | DeviceBlocks::BranchPosition
            | DeviceBlocks::TreePositions => ct.location.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::Icon | DeviceBlocks::EventIcon => {
                ct.icon.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::PortPath | DeviceBlocks::SysPath => {
                ct.path.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::VendorId | DeviceBlocks::VidPid => {
                ct.vid.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::ProductId => ct.pid.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::Name | DeviceBlocks::ProductName => {
                ct.name.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::Serial => ct.serial.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::Manufacturer | DeviceBlocks::VendorName => {
                ct.manufacturer.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::Driver => ct.driver.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::Speed
            | DeviceBlocks::NegotiatedSpeed
            | DeviceBlocks::SpeedLabel
            | DeviceBlocks::NegotiatedSpeedLabel
            | DeviceBlocks::SpeedMarketingLabel
            | DeviceBlocks::NegotiatedSpeedMarketingLabel
            | DeviceBlocks::OperationMode
            | DeviceBlocks::NegotiatedOperationMode => ct.speed.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::BusPower
            | DeviceBlocks::BusPowerUsed
            | DeviceBlocks::ExtraCurrentUsed => ct.power.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::BaseClass
            | DeviceBlocks::UidClass
            | DeviceBlocks::Class
            | DeviceBlocks::BaseValue => ct.class_code.map_or(s.normal(), |c| s.color(c)),
            DeviceBlocks::SubClass | DeviceBlocks::UidSubClass => {
                ct.sub_code.map_or(s.normal(), |c| s.color(c))
            }
            DeviceBlocks::Protocol | DeviceBlocks::UidProtocol => {
                ct.protocol.map_or(s.normal(), |c| s.color(c))
            }
        }
    }

    fn heading(&self) -> &str {
        match self {
            DeviceBlocks::BusNumber => "Bus",
            DeviceBlocks::DeviceNumber => "#",
            DeviceBlocks::BranchPosition => "Prt",
            DeviceBlocks::PortPath => "PPath",
            DeviceBlocks::SysPath => "SPath",
            DeviceBlocks::Driver => "Driver",
            DeviceBlocks::VendorId => "VID",
            DeviceBlocks::ProductId => "PID",
            DeviceBlocks::VidPid => "VID:PID",
            DeviceBlocks::Name => "Name",
            DeviceBlocks::Manufacturer => "Manfacturer",
            DeviceBlocks::ProductName => "PName",
            DeviceBlocks::VendorName => "VName",
            DeviceBlocks::Serial => "Serial",
            DeviceBlocks::Speed => "Speed",
            DeviceBlocks::NegotiatedSpeed => "NgSpd",
            DeviceBlocks::SpeedLabel => "SgSpd",
            DeviceBlocks::NegotiatedSpeedLabel => "NSSpd",
            DeviceBlocks::SpeedMarketingLabel => "MktSpd",
            DeviceBlocks::NegotiatedSpeedMarketingLabel => "NgMktSpd",
            DeviceBlocks::OperationMode => "OpMode",
            DeviceBlocks::NegotiatedOperationMode => "NgOpMode",
            DeviceBlocks::TreePositions => "TPos",
            // will be 000 mA = 6
            DeviceBlocks::BusPower => "PBus",
            DeviceBlocks::BusPowerUsed => "PUsd",
            DeviceBlocks::ExtraCurrentUsed => "PExr",
            // 00.00 = 5
            DeviceBlocks::BcdDevice => "Dev V",
            DeviceBlocks::BcdUsb => "USB V",
            DeviceBlocks::BaseClass => "BaseC",
            DeviceBlocks::SubClass => "SubC",
            DeviceBlocks::Protocol => "Pcol",
            DeviceBlocks::UidClass => "UidCl",
            DeviceBlocks::UidSubClass => "UidSc",
            DeviceBlocks::UidProtocol => "UidPc",
            DeviceBlocks::Class => "Class",
            DeviceBlocks::BaseValue => "CVal",
            DeviceBlocks::Icon => ICON_HEADING,
            DeviceBlocks::EventIcon => "E",
            DeviceBlocks::LastEvent => "Event",
        }
    }

    fn heading_padded(&self, pad: &HashMap<Self, usize>) -> String {
        format!(
            "{:^pad$}",
            self.heading(),
            pad = pad.get(self).unwrap_or(&0)
        )
    }

    fn block_length(&self) -> BlockLength {
        match self {
            DeviceBlocks::Icon | DeviceBlocks::EventIcon => BlockLength::Fixed(1),
            DeviceBlocks::BusNumber | DeviceBlocks::DeviceNumber | DeviceBlocks::BranchPosition => {
                BlockLength::Fixed(3)
            }
            DeviceBlocks::VendorId | DeviceBlocks::ProductId => BlockLength::Fixed(6),
            DeviceBlocks::VidPid => BlockLength::Fixed(11),
            DeviceBlocks::Speed => BlockLength::Fixed(10),
            DeviceBlocks::NegotiatedSpeed => BlockLength::Fixed(10),
            DeviceBlocks::BusPower
            | DeviceBlocks::BusPowerUsed
            | DeviceBlocks::ExtraCurrentUsed => BlockLength::Fixed(6),
            DeviceBlocks::BcdDevice | DeviceBlocks::BcdUsb => BlockLength::Fixed(5),
            DeviceBlocks::SubClass | DeviceBlocks::Protocol | DeviceBlocks::BaseValue => {
                BlockLength::Fixed(4)
            }
            _ => BlockLength::Variable(self.heading().len()),
        }
    }

    fn is_icon(&self) -> bool {
        self == &DeviceBlocks::Icon
    }
}

impl Block<BusBlocks, Bus> for BusBlocks {
    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                BusBlocks::Icon,
                BusBlocks::PortPath,
                BusBlocks::Name,
                BusBlocks::HostController,
                BusBlocks::HostControllerDevice,
                BusBlocks::HostControllerVendor,
                BusBlocks::PciVendor,
                BusBlocks::PciDevice,
                BusBlocks::PciRevision,
            ]
        } else {
            vec![
                BusBlocks::PortPath,
                BusBlocks::Name,
                BusBlocks::HostController,
                BusBlocks::HostControllerDevice,
            ]
        }
    }

    fn len(&self, d: &[&Bus]) -> usize {
        match self {
            BusBlocks::Name => d.iter().map(|d| d.name.width()).max().unwrap_or(0),
            BusBlocks::HostController => d
                .iter()
                .map(|d| d.host_controller.width())
                .max()
                .unwrap_or(0),
            BusBlocks::HostControllerVendor => d
                .iter()
                .flat_map(|d| d.host_controller_vendor.as_ref().map(|v| v.width()))
                .max()
                .unwrap_or(0),
            BusBlocks::HostControllerDevice => d
                .iter()
                .flat_map(|d| d.host_controller_device.as_ref().map(|v| v.width()))
                .max()
                .unwrap_or(0),
            BusBlocks::PortPath => d
                .iter()
                .map(|d| d.path().unwrap_or_default().as_os_str().len())
                .max()
                .unwrap_or(0),
            _ => self.block_length().len(),
        }
    }

    fn generate_padding(d: &[&Bus]) -> HashMap<Self, usize> {
        BusBlocks::iter()
            .map(|b| (b, cmp::max(b.heading().len(), b.len(d))))
            .collect()
    }

    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString {
        match self {
            BusBlocks::BusNumber => ct.location.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::PciVendor => ct.vid.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::PciDevice => ct.pid.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::Name => ct.name.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::HostController => ct.class_code.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::HostControllerVendor => ct.manufacturer.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::HostControllerDevice => ct.name.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::PciRevision => ct.number.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::Icon => ct.icon.map_or(s.normal(), |c| s.color(c)),
            BusBlocks::PortPath => ct.path.map_or(s.normal(), |c| s.color(c)),
        }
    }

    fn format_value(
        &self,
        bus: &Bus,
        pad: &HashMap<Self, usize>,
        settings: &PrintSettings,
    ) -> Option<String> {
        match self {
            BusBlocks::BusNumber => bus
                .get_bus_number()
                .map(|v| format!("{v:3}"))
                .or(Some("---".to_string())),
            BusBlocks::Icon => settings
                .icons
                .as_ref()
                .map(|i| i.get_bus_icon(bus))
                .or(Some(" ".to_string())),
            BusBlocks::PciVendor => Some(match bus.pci_vendor {
                Some(v) => Self::format_base_u16(v, settings),
                None => format!("{:>6}", "-"),
            }),
            BusBlocks::PciDevice => Some(match bus.pci_device {
                Some(v) => Self::format_base_u16(v, settings),
                None => format!("{:>6}", "-"),
            }),
            BusBlocks::PciRevision => Some(match bus.pci_revision {
                Some(v) => Self::format_base_u16(v, settings),
                None => format!("{:>6}", "-"),
            }),
            BusBlocks::Name => Some(format!(
                "{:pad$}",
                bus.name,
                pad = pad.get(self).unwrap_or(&0)
            )),
            BusBlocks::HostController => Some(format!(
                "{:pad$}",
                bus.host_controller,
                pad = pad.get(self).unwrap_or(&0)
            )),
            BusBlocks::HostControllerVendor => Some(match bus.host_controller_vendor.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            BusBlocks::HostControllerDevice => Some(match bus.host_controller_device.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            BusBlocks::PortPath => Some(match bus.path() {
                Some(v) => format!("{:pad$}", v.display(), pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
        }
    }

    fn heading(&self) -> &str {
        match self {
            BusBlocks::BusNumber => "Bus",
            BusBlocks::PortPath => "PPath",
            BusBlocks::PciDevice => "VID",
            BusBlocks::PciVendor => "PID",
            BusBlocks::PciRevision => "Revisn",
            BusBlocks::Name => "Name",
            BusBlocks::HostController => "HostController",
            BusBlocks::HostControllerVendor => "HostVendor",
            BusBlocks::HostControllerDevice => "HostDevice",
            BusBlocks::Icon => ICON_HEADING,
        }
    }

    fn heading_padded(&self, pad: &HashMap<Self, usize>) -> String {
        format!(
            "{:^pad$}",
            self.heading(),
            pad = pad.get(self).unwrap_or(&0)
        )
    }

    fn block_length(&self) -> BlockLength {
        match self {
            BusBlocks::Icon => BlockLength::Fixed(1),
            BusBlocks::BusNumber => BlockLength::Fixed(3),
            BusBlocks::PciDevice | BusBlocks::PciVendor | BusBlocks::PciRevision => {
                BlockLength::Fixed(6)
            }
            _ => BlockLength::Variable(self.heading().len()),
        }
    }

    fn is_icon(&self) -> bool {
        self == &BusBlocks::Icon
    }
}

impl Block<ConfigurationBlocks, Configuration> for ConfigurationBlocks {
    const INSET: u8 = 1;

    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                ConfigurationBlocks::Number,
                ConfigurationBlocks::IconAttributes,
                ConfigurationBlocks::Attributes,
                ConfigurationBlocks::NumInterfaces,
                ConfigurationBlocks::MaxPower,
                ConfigurationBlocks::Name,
            ]
        } else {
            vec![
                ConfigurationBlocks::Number,
                ConfigurationBlocks::IconAttributes,
                ConfigurationBlocks::MaxPower,
                ConfigurationBlocks::Name,
            ]
        }
    }

    fn len(&self, d: &[&Configuration]) -> usize {
        match self {
            ConfigurationBlocks::Name => d.iter().map(|d| d.name.len()).max().unwrap_or(0),
            ConfigurationBlocks::Attributes => d
                .iter()
                .map(|d| d.attributes_string().len())
                .max()
                .unwrap_or(0),
            _ => self.block_length().len(),
        }
    }

    fn generate_padding(d: &[&Configuration]) -> HashMap<Self, usize> {
        ConfigurationBlocks::iter()
            .map(|b| (b, cmp::max(b.heading().len(), b.len(d))))
            .collect()
    }

    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString {
        match self {
            ConfigurationBlocks::Number => ct.location.map_or(s.normal(), |c| s.color(c)),
            ConfigurationBlocks::NumInterfaces => ct.number.map_or(s.normal(), |c| s.color(c)),
            ConfigurationBlocks::MaxPower => ct.power.map_or(s.normal(), |c| s.color(c)),
            ConfigurationBlocks::Name => ct.name.map_or(s.normal(), |c| s.color(c)),
            ConfigurationBlocks::Attributes => ct.attributes.map_or(s.normal(), |c| s.color(c)),
            ConfigurationBlocks::IconAttributes => ct.icon.map_or(s.normal(), |c| s.color(c)),
        }
    }

    fn format_value(
        &self,
        config: &Configuration,
        pad: &HashMap<Self, usize>,
        settings: &PrintSettings,
    ) -> Option<String> {
        match self {
            ConfigurationBlocks::Number => Some(format!("{:2}", config.number)),
            ConfigurationBlocks::NumInterfaces => Some(format!("{:2}", config.interfaces.len())),
            ConfigurationBlocks::Name => Some(format!(
                "{:pad$}",
                config.name,
                pad = pad.get(self).unwrap_or(&0)
            )),
            ConfigurationBlocks::MaxPower => Some(format!("{:6}", config.max_power)),
            ConfigurationBlocks::Attributes => Some(format!(
                "{:pad$}",
                config.attributes_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            ConfigurationBlocks::IconAttributes => Some(format!(
                "{:pad$}",
                attributes_to_icons(&config.attributes, settings),
                pad = pad.get(self).unwrap_or(&0)
            )),
        }
    }

    fn heading(&self) -> &str {
        match self {
            ConfigurationBlocks::Number => "#",
            ConfigurationBlocks::NumInterfaces => "I#",
            ConfigurationBlocks::MaxPower => "PMax",
            ConfigurationBlocks::Name => "Name",
            ConfigurationBlocks::Attributes => "Attributes",
            ConfigurationBlocks::IconAttributes => ICON_HEADING,
        }
    }

    fn heading_padded(&self, pad: &HashMap<Self, usize>) -> String {
        format!(
            "{:^pad$}",
            self.heading(),
            pad = pad.get(self).unwrap_or(&0)
        )
    }

    fn block_length(&self) -> BlockLength {
        match self {
            ConfigurationBlocks::Number => BlockLength::Fixed(2),
            ConfigurationBlocks::NumInterfaces => BlockLength::Fixed(2),
            ConfigurationBlocks::MaxPower => BlockLength::Fixed(6),
            // two possible icons and a space between
            ConfigurationBlocks::IconAttributes => BlockLength::Fixed(3),
            _ => BlockLength::Variable(self.heading().len()),
        }
    }

    fn is_icon(&self) -> bool {
        self == &ConfigurationBlocks::IconAttributes
    }
}

impl Block<InterfaceBlocks, Interface> for InterfaceBlocks {
    const INSET: u8 = 2;

    #[cfg(target_os = "linux")]
    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                InterfaceBlocks::PortPath,
                InterfaceBlocks::Icon,
                InterfaceBlocks::AltSetting,
                InterfaceBlocks::BaseValue,
                InterfaceBlocks::BaseClass,
                InterfaceBlocks::SubClass,
                InterfaceBlocks::UidSubClass,
                InterfaceBlocks::Protocol,
                InterfaceBlocks::UidProtocol,
                InterfaceBlocks::Name,
                InterfaceBlocks::NumEndpoints,
                InterfaceBlocks::Driver,
                InterfaceBlocks::DevPath,
                InterfaceBlocks::SysPath,
            ]
        } else {
            vec![
                InterfaceBlocks::PortPath,
                InterfaceBlocks::Icon,
                InterfaceBlocks::AltSetting,
                InterfaceBlocks::BaseClass,
                InterfaceBlocks::SubClass,
                InterfaceBlocks::Protocol,
                InterfaceBlocks::Name,
                InterfaceBlocks::Driver,
            ]
        }
    }

    #[cfg(not(target_os = "linux"))]
    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                InterfaceBlocks::PortPath,
                InterfaceBlocks::Icon,
                InterfaceBlocks::AltSetting,
                InterfaceBlocks::BaseValue,
                InterfaceBlocks::BaseClass,
                InterfaceBlocks::SubClass,
                InterfaceBlocks::UidSubClass,
                InterfaceBlocks::Protocol,
                InterfaceBlocks::UidProtocol,
                InterfaceBlocks::Name,
                InterfaceBlocks::NumEndpoints,
            ]
        } else {
            vec![
                InterfaceBlocks::PortPath,
                InterfaceBlocks::Icon,
                InterfaceBlocks::AltSetting,
                InterfaceBlocks::BaseClass,
                InterfaceBlocks::SubClass,
                InterfaceBlocks::Protocol,
                InterfaceBlocks::Name,
            ]
        }
    }

    fn example_blocks() -> Vec<Self> {
        vec![
            InterfaceBlocks::PortPath,
            InterfaceBlocks::Icon,
            InterfaceBlocks::AltSetting,
            InterfaceBlocks::BaseClass,
            InterfaceBlocks::SubClass,
            InterfaceBlocks::Protocol,
            InterfaceBlocks::Name,
            InterfaceBlocks::Driver,
        ]
    }

    fn len(&self, d: &[&Interface]) -> usize {
        match self {
            InterfaceBlocks::Name => d
                .iter()
                .flat_map(|d| d.name.as_ref().map(|s| s.width()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::BaseClass => d
                .iter()
                .map(|d| d.class.to_string().len())
                .max()
                .unwrap_or(0),
            InterfaceBlocks::PortPath => d.iter().map(|d| d.path.len()).max().unwrap_or(0),
            InterfaceBlocks::SysPath => d
                .iter()
                .flat_map(|d| d.syspath.as_ref().map(|v| v.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::Driver => d
                .iter()
                .flat_map(|d| d.driver.as_ref().map(|v| v.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::DevPath => d
                .iter()
                .flat_map(|d| {
                    d.dev_paths()
                        .map(|paths| paths.iter().map(|p| p.to_string_lossy()).join(",").len())
                })
                .max()
                .unwrap_or(0),
            InterfaceBlocks::MountPaths => d
                .iter()
                .flat_map(|d| render_mount_paths(d).map(|v| v.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::UidClass => d
                .iter()
                .flat_map(|d| d.class_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::UidSubClass => d
                .iter()
                .flat_map(|d| d.sub_class_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::UidProtocol => d
                .iter()
                .flat_map(|d| d.protocol_name().map(|s| s.len()))
                .max()
                .unwrap_or(0),
            InterfaceBlocks::Class => d
                .iter()
                .map(|d| d.fully_defined_class().to_string().len())
                .max()
                .unwrap_or(0),
            _ => self.block_length().len(),
        }
    }

    fn generate_padding(d: &[&Interface]) -> HashMap<Self, usize> {
        InterfaceBlocks::iter()
            .map(|b| (b, cmp::max(b.heading().len(), b.len(d))))
            .collect()
    }

    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString {
        match self {
            InterfaceBlocks::Number => ct.number.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::Name => ct.name.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::PortPath
            | InterfaceBlocks::SysPath
            | InterfaceBlocks::DevPath
            | InterfaceBlocks::MountPaths => ct.path.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::Icon => ct.icon.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::BaseClass
            | InterfaceBlocks::UidClass
            | InterfaceBlocks::Class
            | InterfaceBlocks::BaseValue => ct.class_code.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::SubClass | InterfaceBlocks::UidSubClass => {
                ct.sub_code.map_or(s.normal(), |c| s.color(c))
            }
            InterfaceBlocks::Protocol | InterfaceBlocks::UidProtocol => {
                ct.protocol.map_or(s.normal(), |c| s.color(c))
            }
            InterfaceBlocks::Driver => ct.driver.map_or(s.normal(), |c| s.color(c)),
            InterfaceBlocks::AltSetting | InterfaceBlocks::NumEndpoints => {
                ct.number.map_or(s.normal(), |c| s.color(c))
            }
        }
    }

    fn format_value(
        &self,
        interface: &Interface,
        pad: &HashMap<Self, usize>,
        settings: &PrintSettings,
    ) -> Option<String> {
        match self {
            InterfaceBlocks::Number => Some(format!("{:2}", interface.number)),
            InterfaceBlocks::Name => Some(match interface.name.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::NumEndpoints => Some(format!("{:2}", interface.endpoints.len())),
            InterfaceBlocks::PortPath => Some(format!(
                "{:pad$}",
                interface.path,
                pad = pad.get(self).unwrap_or(&0)
            )),
            InterfaceBlocks::SysPath => Some(match interface.syspath.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::Driver => Some(match interface.driver.as_ref() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::DevPath => Some(match interface.dev_paths() {
                Some(v) => format!(
                    "{:pad$}",
                    v.iter().map(|p| p.to_string_lossy()).join(","),
                    pad = pad.get(self).unwrap_or(&0)
                ),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::MountPaths => Some(match render_mount_paths(interface) {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::BaseClass => Some(format!(
                "{:pad$}",
                interface.class.to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            InterfaceBlocks::SubClass => Some(Self::format_base_u8(interface.sub_class, settings)),
            InterfaceBlocks::Protocol => Some(Self::format_base_u8(interface.protocol, settings)),
            InterfaceBlocks::AltSetting => {
                Some(Self::format_base_u8(interface.alt_setting, settings))
            }
            InterfaceBlocks::Icon => settings.icons.as_ref().map(|i| {
                i.get_classifier_icon(&interface.class, interface.sub_class, interface.protocol)
            }),
            InterfaceBlocks::UidClass => Some(match interface.class_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::UidSubClass => Some(match interface.sub_class_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::UidProtocol => Some(match interface.protocol_name() {
                Some(v) => format!("{:pad$}", v, pad = pad.get(self).unwrap_or(&0)),
                None => format!("{:pad$}", "-", pad = pad.get(self).unwrap_or(&0)),
            }),
            InterfaceBlocks::Class => Some(format!(
                "{:pad$}",
                interface.fully_defined_class(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            InterfaceBlocks::BaseValue => {
                Some(Self::format_base_u8(interface.class.into(), settings))
            }
        }
    }

    fn heading(&self) -> &str {
        match self {
            InterfaceBlocks::Number => "#",
            InterfaceBlocks::Name => "Name",
            InterfaceBlocks::NumEndpoints => "E#",
            InterfaceBlocks::PortPath => "PPath",
            InterfaceBlocks::SysPath => "SPath",
            InterfaceBlocks::Driver => "Driver",
            InterfaceBlocks::DevPath => "DPath",
            InterfaceBlocks::MountPaths => "MPaths",
            InterfaceBlocks::BaseClass => "BaseC",
            InterfaceBlocks::SubClass => "SubC",
            InterfaceBlocks::Protocol => "Pcol",
            InterfaceBlocks::AltSetting => "Alt#",
            InterfaceBlocks::UidClass => "UidCl",
            InterfaceBlocks::UidSubClass => "UidSc",
            InterfaceBlocks::UidProtocol => "UidPc",
            InterfaceBlocks::Class => "Class",
            InterfaceBlocks::BaseValue => "CVal",
            InterfaceBlocks::Icon => ICON_HEADING,
        }
    }

    fn heading_padded(&self, pad: &HashMap<Self, usize>) -> String {
        format!(
            "{:^pad$}",
            self.heading(),
            pad = pad.get(self).unwrap_or(&0)
        )
    }

    fn block_length(&self) -> BlockLength {
        match self {
            InterfaceBlocks::Icon => BlockLength::Fixed(1),
            InterfaceBlocks::Number => BlockLength::Fixed(2),
            InterfaceBlocks::NumEndpoints => BlockLength::Fixed(2),
            InterfaceBlocks::SubClass
            | InterfaceBlocks::Protocol
            | InterfaceBlocks::AltSetting
            | InterfaceBlocks::BaseValue => BlockLength::Fixed(4),
            _ => BlockLength::Variable(self.heading().len()),
        }
    }

    fn is_icon(&self) -> bool {
        self == &InterfaceBlocks::Icon
    }
}

impl Block<EndpointBlocks, Endpoint> for EndpointBlocks {
    const INSET: u8 = 3;

    fn default_blocks(verbose: bool) -> Vec<Self> {
        if verbose {
            vec![
                EndpointBlocks::Number,
                EndpointBlocks::Direction,
                EndpointBlocks::TransferType,
                EndpointBlocks::SyncType,
                EndpointBlocks::UsageType,
                EndpointBlocks::Interval,
                EndpointBlocks::MaxPacketSize,
            ]
        } else {
            vec![
                EndpointBlocks::Number,
                EndpointBlocks::Direction,
                EndpointBlocks::TransferType,
                EndpointBlocks::SyncType,
                EndpointBlocks::UsageType,
                EndpointBlocks::MaxPacketSize,
            ]
        }
    }

    fn len(&self, d: &[&Endpoint]) -> usize {
        match self {
            EndpointBlocks::TransferType => d
                .iter()
                .map(|d| d.transfer_type.to_string().len())
                .max()
                .unwrap_or(0),
            EndpointBlocks::SyncType => d
                .iter()
                .map(|d| d.sync_type.to_string().len())
                .max()
                .unwrap_or(0),
            EndpointBlocks::UsageType => d
                .iter()
                .map(|d| d.usage_type.to_string().len())
                .max()
                .unwrap_or(0),
            EndpointBlocks::Direction => d
                .iter()
                .map(|d| d.address.direction.to_string().len())
                .max()
                .unwrap_or(0),
            EndpointBlocks::MaxPacketSize => d
                .iter()
                .map(|d| d.max_packet_string().len())
                .max()
                .unwrap_or(0),
            _ => self.block_length().len(),
        }
    }

    fn generate_padding(d: &[&Endpoint]) -> HashMap<Self, usize> {
        EndpointBlocks::iter()
            .map(|b| (b, cmp::max(b.heading().len(), b.len(d))))
            .collect()
    }

    fn colour(&self, s: &str, ct: &colour::ColourTheme) -> ColoredString {
        match self {
            EndpointBlocks::Number | EndpointBlocks::Interval | EndpointBlocks::MaxPacketSize => {
                ct.number.map_or(s.normal(), |c| s.color(c))
            }
            EndpointBlocks::Direction
            | EndpointBlocks::UsageType
            | EndpointBlocks::TransferType
            | EndpointBlocks::SyncType => ct.attributes.map_or(s.normal(), |c| s.color(c)),
        }
    }

    fn format_value(
        &self,
        end: &Endpoint,
        pad: &HashMap<Self, usize>,
        _settings: &PrintSettings,
    ) -> Option<String> {
        match self {
            EndpointBlocks::Number => Some(format!("{:2}", end.address.number)),
            EndpointBlocks::Interval => Some(format!("{:2}", end.interval)),
            EndpointBlocks::MaxPacketSize => Some(format!(
                "{:pad$}",
                end.max_packet_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            EndpointBlocks::Direction => Some(format!(
                "{:pad$}",
                end.address.direction.to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            EndpointBlocks::TransferType => Some(format!(
                "{:pad$}",
                end.transfer_type.to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            EndpointBlocks::SyncType => Some(format!(
                "{:pad$}",
                end.sync_type.to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
            EndpointBlocks::UsageType => Some(format!(
                "{:pad$}",
                end.usage_type.to_string(),
                pad = pad.get(self).unwrap_or(&0)
            )),
        }
    }

    fn heading(&self) -> &str {
        match self {
            EndpointBlocks::Number => "#",
            EndpointBlocks::Interval => "Iv",
            EndpointBlocks::MaxPacketSize => "MaxPkb",
            EndpointBlocks::Direction => "Dir",
            EndpointBlocks::TransferType => "TranT",
            EndpointBlocks::SyncType => "SyncT",
            EndpointBlocks::UsageType => "UsgeT",
        }
    }

    fn heading_padded(&self, pad: &HashMap<Self, usize>) -> String {
        format!(
            "{:^pad$}",
            self.heading(),
            pad = pad.get(self).unwrap_or(&0)
        )
    }

    fn block_length(&self) -> BlockLength {
        match self {
            EndpointBlocks::Number => BlockLength::Fixed(2),
            EndpointBlocks::Interval => BlockLength::Fixed(2),
            _ => BlockLength::Variable(self.heading().len()),
        }
    }
}

/// Value to sort [`Device`]
#[derive(Default, PartialEq, Eq, Debug, ValueEnum, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Sort {
    #[default]
    /// Sort by bus device number
    DeviceNumber,
    /// Sort by position in parent branch
    BranchPosition,
    /// No sorting; whatever order it was parsed
    NoSort,
}

impl Sort {
    /// Sort the [`Device`]s in place
    pub fn sort_devices(&self, devices: &mut [Device]) {
        // add bus number to maintain bus order when sorting
        match self {
            Sort::BranchPosition => {
                devices.sort_by_key(|d| d.get_branch_position() + d.location_id.bus)
            }
            Sort::DeviceNumber => devices.sort_by_key(|d| d.location_id.number + d.location_id.bus),
            _ => (),
        }
    }

    /// Sort the references to [`Device`]s in place
    pub fn sort_devices_ref(&self, devices: &mut [&Device]) {
        match self {
            Sort::BranchPosition => {
                devices.sort_by_key(|d| d.get_branch_position() + d.location_id.bus)
            }
            Sort::DeviceNumber => devices.sort_by_key(|d| d.location_id.number + d.location_id.bus),
            _ => (),
        }
    }

    /// Sort the devices at each branch by calling this recursively after sorting the devices at this level
    pub fn sort_devices_recursive(&self, devices: &mut Vec<Device>) {
        // sort the devices at this level
        self.sort_devices(devices);
        // then sort the devices at each branch
        for device in devices {
            if let Some(branch_devices) = &mut device.devices {
                self.sort_devices_recursive(branch_devices);
            }
        }
    }

    /// Walk the bus tree and sort the devices at each branch
    pub fn sort_bus(&self, bus: &mut Bus) {
        if matches!(self, Sort::NoSort) {
            return;
        }

        if let Some(devices) = &mut bus.devices {
            self.sort_devices_recursive(devices);
        }
    }

    /// Sort buses in place, sorting devices on each bus and then by bus number
    pub fn sort_buses(&self, buses: &mut Vec<Bus>) {
        buses.sort_by_key(|b| b.get_bus_number());
        for bus in buses {
            self.sort_bus(bus);
        }
    }
}

/// Value to group [`Device`]
#[derive(Default, Debug, ValueEnum, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Group {
    #[default]
    /// No grouping
    NoGroup,
    /// Group into buses with bus info as heading - like a flat tree
    Bus,
}

/// Options for [`PrintSettings`] mask_serials
#[derive(Default, Debug, ValueEnum, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MaskSerial {
    /// No masking
    NoMask,
    /// Hide with '*' char
    #[default]
    Hide,
    /// Mask by randomising existing chars
    Scramble,
    /// Mask by replacing length with random chars
    Replace,
}

/// Mode being used for printing
#[derive(Default, Debug, ValueEnum, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PrintMode {
    /// Normal printing to static output
    #[default]
    Normal,
    /// Dynamic printing such as watch mode
    Dynamic,
}

/// Passed to printing functions allows default args
#[derive(Debug, Default)]
pub struct PrintSettings {
    /// Don't pad in order to align blocks
    pub no_padding: bool,
    /// Print in decimal not base16
    pub decimal: bool,
    /// No tree printing
    pub tree: bool,
    /// Sort devices
    pub sort_devices: Sort,
    /// Sort buses by bus number
    pub sort_buses: bool,
    /// Group devices
    pub group_devices: Group,
    /// Print headings for blocks
    pub headings: bool,
    /// Level of verbosity
    pub verbosity: u8,
    /// Print more blocks by default
    pub more: bool,
    /// Print as json
    pub json: bool,
    /// Character encoding to use
    pub encoding: Encoding,
    /// Scramble serial numbers, useful if sharing sensitive device dumps
    pub mask_serials: Option<MaskSerial>,
    /// [`DeviceBlocks`] to use for printing
    pub device_blocks: Option<Vec<DeviceBlocks>>,
    /// [`BusBlocks`] to use for printing
    pub bus_blocks: Option<Vec<BusBlocks>>,
    /// [`ConfigurationBlocks`] to use for printing
    pub config_blocks: Option<Vec<ConfigurationBlocks>>,
    /// [`InterfaceBlocks`] to use for printing
    pub interface_blocks: Option<Vec<InterfaceBlocks>>,
    /// [`EndpointBlocks`] to use for printing
    pub endpoint_blocks: Option<Vec<EndpointBlocks>>,
    /// [`crate::icon::IconTheme`] to apply - None to not print any icons
    pub icons: Option<icon::IconTheme>,
    /// [`crate::colour::ColourTheme`] to apply - None to not colour
    pub colours: Option<colour::ColourTheme>,
    /// Max variable string length to display before truncating - descriptors and classes for example
    pub max_variable_string_len: Option<usize>,
    /// Enable auto generation of max_variable_string_len based on terminal width
    pub auto_width: bool,
    /// Terminal width and height data
    pub terminal_size: Option<(u16, u16)>,
    /// When to print icon blocks
    pub icon_when: IconWhen,
    /// When to print colour
    pub color_when: ColorWhen,
    /// Printing in watch mode
    pub print_mode: PrintMode,
    /// Apply muted colour to hub device lines instead of per-block colours
    pub mute_hubs: bool,
}

/// Converts a HashSet of [`ConfigAttributes`] a String of nerd icons
fn attributes_to_icons(attributes: &Vec<ConfigAttributes>, settings: &PrintSettings) -> String {
    let mut icon_strs = Vec::new();
    if settings.icons.is_some() {
        for a in attributes {
            match a {
                ConfigAttributes::SelfPowered => icon_strs.push("\u{f06a5}"), // 󰚥
                ConfigAttributes::RemoteWakeup => icon_strs.push("\u{f0155}"), // 󰅕
                ConfigAttributes::BatteryPowered => icon_strs.push("\u{f244}"), //                ConfigAttributes::BusPowered => icon_strs.push("\u{f11f0}"),  // 󱇰
            }
        }
    }
    icon_strs.join(" ")
}

/// Truncates and appends '...' to show string has been truncated
///
/// `len` is length of resulting String, with '...' so original `s` content will be len - 3
///
/// If `len` is less than 3, `s` truncated to this length
///
/// ```
/// use cyme::display::truncate_string;
/// let mut string = String::from("Hello world");
/// truncate_string(&mut string, 8);
/// assert_eq!(string, "Hello...");
/// // emoji are 2 bytes so will be truncated correctly on char boundary
/// let mut string = String::from("Hell😅 world");
/// truncate_string(&mut string, 8);
/// assert_eq!(string, "Hell😅...");
/// let mut string = String::from("bl");
/// truncate_string(&mut string, 2);
/// assert_eq!(string, "bl");
/// // don't shorten if already length
/// let mut string = String::from("blah");
/// truncate_string(&mut string, 4);
/// assert_eq!(string, "blah");
/// // just over length
/// let mut string = String::from("blahx");
/// truncate_string(&mut string, 4);
/// assert_eq!(string, "b...");
/// ```
pub fn truncate_string(s: &mut String, len: usize) {
    // if already less than or equal to len, or len is less than 3, return
    if s.width() <= len || len <= 3 {
        return;
    }
    // use char_indices to find last char boundary before len - 3
    // not s.len() as this is the byte length and utf-8 chars can be multiple bytes
    if let Some((i, _)) = s.char_indices().nth(len - 3) {
        s.truncate(i);
        s.push_str("...");
    }
}

/// Finds the maximum string size to truncate variable fields
///
/// Calculates based on the [`PrintSettings`] terminal_size width, the total length of the [`BlockLength::Fixed`] fields and thus the remaining space to divide between [`BlockLength::Variable`] fields as the maximum string size
///
/// Total length is based the prior calculated `variable_lens` - the values represent the maximum length of variable fields to print
pub fn auto_max_string_len<B: BlockEnum, T>(
    blocks: &[impl Block<B, T>],
    offset: usize,
    #[allow(clippy::ptr_arg)] variable_lens: &Vec<usize>,
    settings: &PrintSettings,
) -> Option<usize> {
    if variable_lens.is_empty() {
        return None;
    }

    // total fixed includes length of blocks to account for spaces between fields, plus tree offset
    let total_fixed: usize = blocks
        .iter()
        .filter_map(|b| b.block_length().fixed_len())
        .sum::<usize>()
        + blocks.len()
        + offset;
    let total_variable: usize = variable_lens.iter().sum();
    let total_len: usize = total_fixed + total_variable + (blocks.len() * 2);
    let (width, height) = settings.terminal_size.unwrap_or((DEFAULT_AUTO_WIDTH, 0));
    log::trace!(
        "Auto scaling running for max length {total_len:?} of which fixed {total_fixed:?}, to terminal size {width:?} {height:?}"
    );
    let w = width as usize;

    if total_len > w {
        // fixed already taking all space, return min
        if w < total_fixed {
            log::trace!("Cannot scale, fixed already taking all space!");
            return Some(MIN_VARIABLE_STRING_LEN);
        }
        // remaining len for variable strings
        let variable_len_remain: usize = w - total_fixed;
        // auto max is the space not taken by fixed divided by number of variable length
        // *variable_lens checked not zero at entry so should not be div 0
        let mut auto_max_string = variable_len_remain / (variable_lens.len());
        // remaining chars are those not used by variable strings; ones not over the found auto max and can be used by other variable strings - bumping the global max up since they won't use it
        let mut remaining_chars: usize = variable_lens
            .iter()
            .filter(|v| **v <= auto_max_string)
            .map(|v| auto_max_string - v)
            .sum();
        log::trace!(
            "Auto max string calculated {auto_max_string:?}, remaining {remaining_chars:?}"
        );

        // equally divide remaining chars between variable > auto_max_string - not perfect as could be shared per how much longer each is but this would require unique max for each block
        let variable_longer = variable_lens
            .iter()
            .filter(|v| **v > auto_max_string)
            .count();
        remaining_chars = remaining_chars
            .checked_div(variable_longer)
            .unwrap_or(remaining_chars);
        auto_max_string += remaining_chars;

        if auto_max_string < MIN_VARIABLE_STRING_LEN {
            log::trace!(
                "Ignoring auto max string {auto_max_string:?}! Clamped to MIN_VARIABLE_STRING_LEN {MIN_VARIABLE_STRING_LEN:?}"
            );
            Some(MIN_VARIABLE_STRING_LEN)
        } else {
            log::trace!("Final auto max string {auto_max_string:?}");
            Some(auto_max_string)
        }
    } else {
        None
    }
}

/// Returns true if the [`Block`] has a valid icon for the [`PrintSettings`] [`Encoding`]
pub fn has_valid_icons<B: BlockEnum, T>(
    d: &T,
    blocks: &[impl Block<B, T>],
    settings: &PrintSettings,
) -> bool {
    blocks.iter().filter(|b| b.is_icon()).all(|b| {
        if log::log_enabled!(log::Level::Trace) {
            let val = b.format_value(d, &HashMap::new(), settings);
            let ret = match &val {
                Some(v) => settings.encoding.str_is_valid(v),
                None => false,
            };
            log::trace!(
                "icon {:?} valid for {:?}: {:?}",
                val,
                settings.encoding,
                ret
            );
            ret
        } else {
            match b.format_value(d, &HashMap::new(), settings) {
                Some(v) => settings.encoding.str_is_valid(&v),
                None => false,
            }
        }
    })
}

/// Controls per-line colour overrides applied by [`render_value`]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum LineStyle {
    /// Normal per-block colouring
    #[default]
    Normal,
    /// Dimmed white — used for disconnected devices
    Dimmed,
    /// Uniform muted colour — used to de-emphasise a line
    Muted,
}

/// Formats each [`Block`] value shown from a device `d`
pub fn render_value<B: BlockEnum, T>(
    d: &T,
    blocks: &[impl Block<B, T>],
    pad: &HashMap<B, usize>,
    settings: &PrintSettings,
    max_string_length: Option<usize>,
    line_style: LineStyle,
) -> Vec<String> {
    let mut ret = Vec::new();
    for b in blocks {
        if let Some(mut string) = b.format_value(d, pad, settings) {
            // truncate if max_string_length present and before colour applied as this will _add_ chars
            if b.value_is_variable_length() {
                if let Some(ml) = max_string_length {
                    truncate_string(&mut string, ml)
                }
            }
            match &settings.colours {
                Some(c) => match line_style {
                    LineStyle::Dimmed => ret.push(format!("{}", string.dimmed().white())),
                    LineStyle::Muted => ret.push(format!(
                        "{}",
                        c.muted.map_or(string.normal(), |hc| string.color(hc))
                    )),
                    LineStyle::Normal => ret.push(format!("{}", b.colour(&string, c))),
                },
                None => ret.push(string.to_string()),
            };
        }
    }

    ret
}

/// Renders the headings for each [`Block`] being shown
pub fn render_heading<B: BlockEnum, T>(
    blocks: &[impl Block<B, T>],
    pad: &HashMap<B, usize>,
    max_string_length: Option<usize>,
) -> Vec<String> {
    let mut ret = Vec::new();

    for b in blocks {
        let mut string = b.heading_padded(pad);
        if b.value_is_variable_length() {
            if let Some(ml) = max_string_length {
                truncate_string(&mut string, ml)
            }
        }
        ret.push(string)
    }

    ret
}

/// Renders mount mounts with partition "partition:mount_path,..." format
pub fn render_mount_paths(interface: &Interface) -> Option<String> {
    interface.block_mount_paths().map(|paths| {
        paths
            .iter()
            .map(|(num, path)| {
                if let Ok(part) = num.strip_prefix("/dev/") {
                    format!("{}:{}", part.display(), path.display())
                } else {
                    format!(":{}", path.display())
                }
            })
            .collect::<Vec<String>>()
            .join(", ")
    })
}

/// Generates tree formatting and values given `current_tree`, current `branch_length` and item `index` in branch
fn generate_tree_data(
    current_tree: &TreeData,
    branch_length: usize,
    index: usize,
    settings: &PrintSettings,
) -> TreeData {
    let mut pass_tree = current_tree.clone();

    // get prefix from icons if tree - maybe should cache these before build rather than lookup each time...
    if settings.tree {
        pass_tree.prefix = if pass_tree.depth > 0 {
            let edge_icon = if index + 1 != pass_tree.branch_length {
                icon::Icon::TreeLine
            } else {
                icon::Icon::TreeBlank
            };

            format!(
                "{}{}",
                pass_tree.prefix,
                settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(&edge_icon, &settings.encoding),
                    |i| i.get_tree_icon(&edge_icon, &settings.encoding)
                )
            )
        } else {
            pass_tree.prefix.to_string()
        };
    }

    pass_tree.depth += 1;
    pass_tree.branch_length = branch_length;
    pass_tree.trunk_index = index as u8;

    pass_tree
}

/// Generates the [`DeviceExtra`] blocks based on the [`PrintSettings`] or defaults. Will also retain based on `is_icon` and [`IconWhen`] setting
///
/// If [`IconWhen::Auto`] will render icon block values to check if supported by [`Encoding`] and remove if not
fn generate_extra_blocks(
    extra: &DeviceExtra,
    settings: &PrintSettings,
) -> (
    Vec<ConfigurationBlocks>,
    Vec<InterfaceBlocks>,
    Vec<EndpointBlocks>,
) {
    let mut blocks = (
        settings.config_blocks.to_owned().unwrap_or(
            Block::<ConfigurationBlocks, Configuration>::default_blocks(settings.more),
        ),
        settings.interface_blocks.to_owned().unwrap_or(
            Block::<InterfaceBlocks, Interface>::default_blocks(settings.more),
        ),
        settings.endpoint_blocks.to_owned().unwrap_or(
            Block::<EndpointBlocks, Endpoint>::default_blocks(settings.more),
        ),
    );

    // auto drop icon blocks depending on IconWhen and Encoding
    // will drop if any in search is not valid for encoding rather than per device
    // I think acceptable as similar to device block behaviour
    match settings.icon_when {
        // if never or auto and no icons, drop
        IconWhen::Never | IconWhen::Auto if settings.icons.is_none() => {
            blocks.0.retain(|b| !b.is_icon());
            blocks.1.retain(|b| !b.is_icon());
            blocks.2.retain(|b| !b.is_icon());
        }
        // skip further processing if including private use area utf8
        IconWhen::Auto if settings.encoding == Encoding::Glyphs => (),
        // always only warn if no icons provided
        IconWhen::Always => {
            if settings.icons.is_none() {
                log::warn!(
                    "{:?} blocks requested but no icons provided",
                    settings.icon_when
                );
            }
        }
        // drill through values checking
        _ => {
            settings
                .icon_when
                .retain(&extra.configurations, &mut blocks.0, settings);
            extra.configurations.iter().for_each(|c| {
                settings
                    .icon_when
                    .retain(&c.interfaces, &mut blocks.1, settings);
                c.interfaces.iter().for_each(|i| {
                    settings
                        .icon_when
                        .retain(&i.endpoints, &mut blocks.2, settings);
                });
            });
        }
    }
    blocks
}

/// Passed to print functions to support tree building
#[derive(Debug, Default, Clone)]
pub struct TreeData {
    /// Length of the branch sitting on
    branch_length: usize,
    /// Index within parent list of devices
    trunk_index: u8,
    /// Depth of tree being built - normally len() tree_positions but might not be if printing inner
    depth: usize,
    /// Prefix to apply, builds up as depth increases
    prefix: String,
}

/// The operation to perform on the blocks when specified by the user
#[derive(Default, PartialEq, Eq, Debug, ValueEnum, Clone, Copy, Serialize, Deserialize)]
pub enum BlockOperation {
    /// Add new blocks to the existing blocks, ignoring duplicates
    #[default]
    Add,
    /// Append new blocks to the end of the existing blocks
    Append,
    /// Replace all blocks with new ones
    New,
    /// Prepend new blocks to the start of the existing blocks
    Prepend,
    /// Remove matching blocks from the existing blocks
    Remove,
}

impl BlockOperation {
    /// Create a new or run the operation on the blocks, returning the new blocks
    pub fn new_or_op<B: BlockEnum + Block<B, T>, T>(
        &self,
        blocks: Option<Vec<B>>,
        new: &[B],
        verbose: bool,
    ) -> Result<Vec<B>> {
        if matches!(self, BlockOperation::New) {
            return Ok(new.to_vec());
        }

        let mut current = blocks.unwrap_or_else(|| B::default_blocks(verbose));
        self.run(&mut current, new)?;
        Ok(current)
    }

    /// Run the operation on the blocks, modifying them in place
    pub fn run<T: BlockEnum>(&self, blocks: &mut Vec<T>, new: &[T]) -> Result<()> {
        match self {
            BlockOperation::New => {
                *blocks = new.to_vec();
            }
            BlockOperation::Append => {
                blocks.extend(new.iter().cloned());
            }
            BlockOperation::Prepend => {
                let mut new = new.to_vec();
                new.append(blocks);
                *blocks = new;
            }
            BlockOperation::Add => {
                for b in new {
                    if !blocks.contains(b) {
                        blocks.push(b.clone());
                    }
                }
            }
            BlockOperation::Remove => {
                for b in new {
                    blocks.retain(|x| x != b);
                }
            }
        }
        Ok(())
    }
}

/// Used to describe the item being printed
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LineItem {
    /// Bus number
    Bus(usize),
    /// Device port path
    Device(PortPath),
    /// Configuration number
    Config(ConfigurationPath),
    /// Interface name
    Interface(DevicePath),
    /// Endpoint Address
    Endpoint(EndpointPath),
    /// New lines or other non-item
    None,
}

/// DisplayWriter allows control of output to terminal or other Writer
///
/// Mainly for watch mode to allow control of output
pub struct DisplayWriter<W: Write> {
    raw_mode: bool,
    line_context: Vec<LineItem>,
    inner: W,
}

impl<W: Write> Write for DisplayWriter<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl Default for DisplayWriter<io::Stdout> {
    fn default() -> Self {
        Self::new(io::stdout())
    }
}

impl<W: Write> DisplayWriter<W> {
    /// Create a new DisplayWriter with the inner writer
    pub fn new(inner: W) -> Self {
        Self {
            raw_mode: false,
            line_context: Vec::new(),
            inner,
        }
    }

    /// Set the raw mode for the writer
    ///
    /// Raw mode will print `\r\n` instead of `\n` for newlines
    pub fn set_raw_mode(&mut self, raw_mode: bool) {
        self.raw_mode = raw_mode;
    }

    /// Print text to the writer
    pub fn print<S: AsRef<str>>(&mut self, text: S) -> io::Result<()> {
        write!(self.inner, "{}", text.as_ref())?;
        self.inner.flush()?;
        Ok(())
    }

    /// Print text to the writer with a newline
    pub fn println<S: AsRef<str>>(&mut self, text: S, item: LineItem) -> io::Result<()> {
        if self.raw_mode {
            write!(self.inner, "{}\r\n", text.as_ref())?;
        } else {
            writeln!(self.inner, "{}", text.as_ref())?;
        }
        self.line_context.push(item);
        self.inner.flush()?;
        Ok(())
    }

    /// Get the inner writer
    pub fn into_inner(self) -> W {
        self.inner
    }

    /// Get the line context for the writer
    pub fn line_context(&self) -> &Vec<LineItem> {
        &self.line_context
    }

    /// All device [`Endpoint`]
    pub fn print_endpoints(
        &mut self,
        interface: &Interface,
        blocks: &[EndpointBlocks],
        settings: &PrintSettings,
        tree: &TreeData,
        line_style: LineStyle,
    ) {
        let endpoints = &interface.endpoints;
        let device_path = interface.device_path();
        let mut pad = if !settings.no_padding {
            let endpoints: Vec<&Endpoint> = endpoints.iter().collect();
            EndpointBlocks::generate_padding(&endpoints)
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| blocks.contains(k));

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let offset = if settings.tree {
                tree.depth * 3 + 1
            } else {
                (EndpointBlocks::INSET * LIST_INSET_SPACES) as usize
            };
            let variable_lens: Vec<usize> = pad
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(blocks, offset, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        log::trace!("Print endpoints padding {pad:?}, tree {tree:?}");

        // if there is a max variable length, adjust padding to this if current > it and is variable
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        for (i, endpoint) in endpoints.iter().enumerate() {
            let line_item = if let Some(dp) = device_path.as_ref() {
                LineItem::Endpoint(EndpointPath::new_with_device_path(
                    dp.to_owned(),
                    endpoint.address.address,
                ))
            } else {
                LineItem::None
            };
            // get current prefix based on if last in tree and whether we are within the tree
            if settings.tree {
                let mut prefix = if tree.depth > 0 {
                    let edge_icon = if i + 1 != tree.branch_length {
                        icon::Icon::TreeEdge
                    } else {
                        icon::Icon::TreeCorner
                    };
                    let edge = settings.icons.as_ref().map_or(
                        icon::get_default_tree_icon(&edge_icon, &settings.encoding),
                        |i| i.get_tree_icon(&edge_icon, &settings.encoding),
                    );
                    format!("{}{}", tree.prefix, edge)
                // zero depth
                } else {
                    tree.prefix.to_string()
                };

                let mut terminator = settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(
                        &icon::Icon::Endpoint(endpoint.address.direction),
                        &settings.encoding,
                    ),
                    |i| {
                        i.get_tree_icon(
                            &icon::Icon::Endpoint(endpoint.address.direction),
                            &settings.encoding,
                        )
                    },
                );

                // colour tree
                if let Some(ct) = settings.colours.as_ref() {
                    prefix = ct
                        .tree
                        .map_or(prefix.normal(), |c| prefix.color(c))
                        .to_string();
                    terminator = if endpoint.address.direction == Direction::In {
                        ct.tree_endpoint_in
                            .map_or(terminator.normal(), |c| terminator.color(c))
                            .to_string()
                    } else {
                        ct.tree_endpoint_out
                            .map_or(terminator.normal(), |c| terminator.color(c))
                            .to_string()
                    };
                }

                // maybe should just do once at start of bus
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{}  {}", prefix, heading.bold().underline()),
                        LineItem::None,
                    )
                    .unwrap();
                }

                // render and print tree if doing it
                self.print(format!("{prefix}{terminator} ")).unwrap();
                self.println(
                    render_value(
                        endpoint,
                        blocks,
                        &pad,
                        settings,
                        max_variable_string_len,
                        line_style,
                    )
                    .join(" "),
                    line_item,
                )
                .unwrap();
            } else {
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{:spaces$}{}", "", heading.bold().underline(), spaces = 6),
                        LineItem::None,
                    )
                    .unwrap();
                }

                self.println(
                    format!(
                        "{:spaces$}{}",
                        "",
                        render_value(
                            endpoint,
                            blocks,
                            &pad,
                            settings,
                            max_variable_string_len,
                            line_style,
                        )
                        .join(" "),
                        spaces = (EndpointBlocks::INSET * LIST_INSET_SPACES) as usize
                    ),
                    line_item,
                )
                .unwrap();
            }
        }
    }

    /// All device [`Interface`]
    pub fn print_interfaces(
        &mut self,
        interfaces: &[Interface],
        blocks: (&Vec<InterfaceBlocks>, &Vec<EndpointBlocks>),
        settings: &PrintSettings,
        tree: &TreeData,
        line_style: LineStyle,
    ) {
        let mut pad = if !settings.no_padding {
            let interfaces: Vec<&Interface> = interfaces.iter().collect();
            InterfaceBlocks::generate_padding(&interfaces)
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| blocks.0.contains(k));

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let offset = if settings.tree {
                tree.depth * 3 + 1
            } else {
                (InterfaceBlocks::INSET * LIST_INSET_SPACES) as usize
            };
            let variable_lens: Vec<usize> = pad
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(blocks.0, offset, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        log::trace!("Print interfaces padding {pad:?}, tree {tree:?}");

        for (i, interface) in interfaces.iter().enumerate() {
            let line_item = if let Some(dp) = interface.device_path() {
                LineItem::Interface(dp)
            } else {
                LineItem::None
            };
            // get current prefix based on if last in tree and whether we are within the tree
            if settings.tree {
                let mut prefix = if tree.depth > 0 {
                    let edge_icon = if i + 1 != tree.branch_length {
                        icon::Icon::TreeEdge
                    } else {
                        icon::Icon::TreeCorner
                    };
                    let edge = settings.icons.as_ref().map_or(
                        icon::get_default_tree_icon(&edge_icon, &settings.encoding),
                        |i| i.get_tree_icon(&edge_icon, &settings.encoding),
                    );
                    format!("{}{}", tree.prefix, edge)
                // zero depth
                } else {
                    tree.prefix.to_string()
                };

                let mut terminator = settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(
                        &icon::Icon::TreeInterfaceTerminator,
                        &settings.encoding,
                    ),
                    |i| i.get_tree_icon(&icon::Icon::TreeInterfaceTerminator, &settings.encoding),
                );

                // colour tree
                if let Some(ct) = settings.colours.as_ref() {
                    prefix = ct
                        .tree
                        .map_or(prefix.normal(), |c| prefix.color(c))
                        .to_string();
                    terminator = ct
                        .tree_interface_terminator
                        .map_or(terminator.normal(), |c| terminator.color(c))
                        .to_string();
                }

                // maybe should just do once at start of bus
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks.0, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{}  {}", prefix, heading.bold().underline()),
                        LineItem::None,
                    )
                    .unwrap();
                }

                // render and print tree if doing it
                self.print(format!("{prefix}{terminator} ")).unwrap();

                self.println(
                    render_value(
                        interface,
                        blocks.0,
                        &pad,
                        settings,
                        max_variable_string_len,
                        line_style,
                    )
                    .join(" "),
                    line_item,
                )
                .unwrap();
            } else {
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks.0, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{:spaces$}{}", "", heading.bold().underline(), spaces = 4),
                        LineItem::None,
                    )
                    .unwrap();
                }

                self.println(
                    format!(
                        "{:spaces$}{}",
                        "",
                        render_value(
                            interface,
                            blocks.0,
                            &pad,
                            settings,
                            max_variable_string_len,
                            line_style,
                        )
                        .join(" "),
                        spaces = (InterfaceBlocks::INSET * LIST_INSET_SPACES) as usize
                    ),
                    line_item,
                )
                .unwrap();
            }

            // print the endpoints
            if settings.verbosity >= 3 || interface.is_expanded() {
                self.print_endpoints(
                    interface,
                    blocks.1,
                    settings,
                    &generate_tree_data(tree, interface.endpoints.len(), i, settings),
                    line_style,
                );
            }
        }
    }

    /// All device [`Configuration`]
    pub fn print_configurations(
        &mut self,
        device: &Device,
        configs: &[Configuration],
        blocks: (
            &Vec<ConfigurationBlocks>,
            &Vec<InterfaceBlocks>,
            &Vec<EndpointBlocks>,
        ),
        settings: &PrintSettings,
        tree: &TreeData,
    ) {
        let mut pad = if !settings.no_padding {
            let configs: Vec<&Configuration> = configs.iter().collect();
            ConfigurationBlocks::generate_padding(&configs)
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| blocks.0.contains(k));

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let offset = if settings.tree {
                tree.depth * 3 + 1
            } else {
                (ConfigurationBlocks::INSET * LIST_INSET_SPACES) as usize
            };
            let variable_lens: Vec<usize> = pad
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(blocks.0, offset, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        log::trace!("Print configs padding {pad:?}, tree {tree:?}");

        for (i, config) in configs.iter().enumerate() {
            let line_item = LineItem::Config((device.port_path(), config.number));
            // get current prefix based on if last in tree and whether we are within the tree
            if settings.tree {
                let mut prefix = if tree.depth > 0 {
                    let edge_icon = if i + 1 != tree.branch_length {
                        icon::Icon::TreeEdge
                    } else {
                        icon::Icon::TreeCorner
                    };
                    let edge = settings.icons.as_ref().map_or(
                        icon::get_default_tree_icon(&edge_icon, &settings.encoding),
                        |i| i.get_tree_icon(&edge_icon, &settings.encoding),
                    );
                    format!("{}{}", tree.prefix, edge)
                // zero depth
                } else {
                    tree.prefix.to_string()
                };

                let mut terminator = settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(
                        &icon::Icon::TreeConfigurationTerminator,
                        &settings.encoding,
                    ),
                    |i| {
                        i.get_tree_icon(
                            &icon::Icon::TreeConfigurationTerminator,
                            &settings.encoding,
                        )
                    },
                );

                // colour tree
                if let Some(ct) = settings.colours.as_ref() {
                    prefix = ct
                        .tree
                        .map_or(prefix.normal(), |c| prefix.color(c))
                        .to_string();
                    terminator = ct
                        .tree_configuration_terminator
                        .map_or(terminator.normal(), |c| terminator.color(c))
                        .to_string();
                }

                // maybe should just do once at start of bus
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks.0, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{}  {}", prefix, heading.bold().underline()),
                        LineItem::None,
                    )
                    .unwrap();
                }

                // render and print tree if doing it
                self.print(format!("{prefix}{terminator} ")).unwrap();

                let ls = if device.is_disconnected() {
                    LineStyle::Dimmed
                } else {
                    LineStyle::Normal
                };
                self.println(
                    render_value(
                        config,
                        blocks.0,
                        &pad,
                        settings,
                        max_variable_string_len,
                        ls,
                    )
                    .join(" "),
                    line_item,
                )
                .unwrap();
            } else {
                if settings.headings && i == 0 {
                    let heading = render_heading(blocks.0, &pad, max_variable_string_len).join(" ");
                    self.println(
                        format!("{:spaces$}{}", "", heading.bold().underline(), spaces = 2),
                        LineItem::None,
                    )
                    .unwrap();
                }

                let ls = if device.is_disconnected() {
                    LineStyle::Dimmed
                } else {
                    LineStyle::Normal
                };
                self.println(
                    format!(
                        "{:spaces$}{}",
                        "",
                        render_value(
                            config,
                            blocks.0,
                            &pad,
                            settings,
                            max_variable_string_len,
                            ls,
                        )
                        .join(" "),
                        spaces = (ConfigurationBlocks::INSET * LIST_INSET_SPACES) as usize
                    ),
                    line_item,
                )
                .unwrap();
            }

            // print the interfaces
            if settings.verbosity >= 2 || config.is_expanded() {
                let ls = if device.is_disconnected() {
                    LineStyle::Dimmed
                } else {
                    LineStyle::Normal
                };
                self.print_interfaces(
                    &config.interfaces,
                    ((blocks.1), (blocks.2)),
                    settings,
                    &generate_tree_data(tree, config.interfaces.len(), i, settings),
                    ls,
                );
            }
        }
    }

    /// Recursively print `devices`; will call for each `Device` devices if `Some`
    ///
    /// Will draw tree if `settings.tree`, otherwise it will be flat
    pub fn print_devices(
        &mut self,
        devices: &[Device],
        db: &Vec<DeviceBlocks>,
        settings: &PrintSettings,
        tree: &TreeData,
        padding: &HashMap<DeviceBlocks, usize>,
    ) {
        let mut padding = padding.clone();
        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let offset = if settings.tree { tree.depth * 3 + 1 } else { 0 };
            let variable_lens: Vec<usize> = padding
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(db, offset, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in padding.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        log::trace!("Print devices padding {padding:?}, tree {tree:?}");

        for (i, device) in devices.iter().filter(|d| !d.is_hidden()).enumerate() {
            // get current prefix based on if last in tree and whether we are within the tree
            if settings.tree {
                let mut prefix = if tree.depth > 0 {
                    let edge_icon = if i + 1 != tree.branch_length {
                        icon::Icon::TreeEdge
                    } else {
                        icon::Icon::TreeCorner
                    };
                    let edge = settings.icons.as_ref().map_or(
                        icon::get_default_tree_icon(&edge_icon, &settings.encoding),
                        |i| i.get_tree_icon(&edge_icon, &settings.encoding),
                    );
                    format!("{}{}", tree.prefix, edge)
                // zero depth
                } else {
                    tree.prefix.to_string()
                };

                let icon_terminator = if device.is_disconnected() {
                    icon::Icon::TreeDisconnectedTerminator
                } else if device.class == Some(BaseClass::Hub) {
                    icon::Icon::TreeHubTerminator
                } else {
                    icon::Icon::TreeDeviceTerminator
                };
                let mut terminator = settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(&icon_terminator, &settings.encoding),
                    |i| i.get_tree_icon(&icon_terminator, &settings.encoding),
                );

                // colour tree
                if let Some(ct) = settings.colours.as_ref() {
                    prefix = ct
                        .tree
                        .map_or(prefix.normal(), |c| prefix.color(c))
                        .to_string();
                    terminator = ct
                        .tree_bus_terminator
                        .map_or(terminator.normal(), |c| terminator.color(c))
                        .to_string();
                }

                // maybe should just do once at start of bus
                if settings.headings && i == 0 {
                    let heading = render_heading(db, &padding, max_variable_string_len).join(" ");
                    self.println(
                        format!("{}  {}", prefix, heading.bold().underline()),
                        LineItem::None,
                    )
                    .unwrap();
                }

                // render and print tree if doing it
                self.print(format!("{prefix}{terminator} ")).unwrap();
            } else if settings.headings && i == 0 {
                let heading = render_heading(db, &padding, max_variable_string_len).join(" ");
                self.println(format!("{}", heading.bold().underline()), LineItem::None)
                    .unwrap();
            }

            // print the device
            let line_style = if device.is_disconnected() {
                LineStyle::Dimmed
            } else if settings.mute_hubs && device.class == Some(BaseClass::Hub) {
                LineStyle::Muted
            } else {
                LineStyle::Normal
            };
            let device_string = render_value(
                device,
                db,
                &padding,
                settings,
                max_variable_string_len,
                line_style,
            )
            .join(" ");
            self.println(&device_string, LineItem::Device(device.port_path()))
                .unwrap();

            // print the configurations
            if let Some(extra) = device.extra.as_ref() {
                if settings.verbosity >= 1 || device.is_expanded() {
                    // generate extra blocks if not passed and drop icons if not supported by encoding
                    let blocks = generate_extra_blocks(extra, settings);
                    let num = device
                        .devices
                        .as_ref()
                        .map_or(0, |d| d.iter().filter(|d| !d.is_hidden()).count());

                    // pass branch length as number of configurations for this device plus devices still to print
                    self.print_configurations(
                        device,
                        &extra.configurations,
                        (&blocks.0, &blocks.1, &blocks.2),
                        settings,
                        &generate_tree_data(tree, extra.configurations.len() + num, i, settings),
                    );
                }
            } else if settings.verbosity >= 1 {
                log::warn!(
                    "Unable to print verbose information for {device} because libusb extra data is missing"
                )
            }

            if let Some(d) = device.devices.as_ref() {
                // and then walk down devices printing them too
                self.print_devices(
                    d,
                    db,
                    settings,
                    &generate_tree_data(
                        tree,
                        d.iter().filter(|dd| !dd.is_hidden()).count(),
                        i,
                        settings,
                    ),
                    &padding,
                );
            }
        }
    }

    /// Print [`SystemProfile`] [`Bus`] and [`Device`] information
    pub fn print_sp_usb(&mut self, sp_usb: &SystemProfile, settings: &PrintSettings) {
        let mut bb = settings
            .bus_blocks
            .to_owned()
            .unwrap_or(Block::<BusBlocks, Bus>::default_blocks(settings.more));
        let mut db = settings
            .device_blocks
            .to_owned()
            .unwrap_or(if settings.more {
                DeviceBlocks::default_blocks(true)
            } else if settings.tree {
                DeviceBlocks::default_device_tree_blocks()
            } else {
                DeviceBlocks::default_blocks(false)
            });

        // remove icon blocks if not supported by encoding
        match settings.icon_when {
            IconWhen::Never | IconWhen::Auto if settings.icons.is_none() => {
                bb.retain(|b| !b.is_icon());
                db.retain(|b| !b.is_icon());
            }
            IconWhen::Auto if settings.encoding == Encoding::Glyphs => (),
            IconWhen::Always => {
                if settings.icons.is_none() {
                    log::warn!(
                        "{:?} blocks requested but no icons provided",
                        settings.icon_when
                    );
                }
            }
            _ => {
                settings.icon_when.retain(&sp_usb.buses, &mut bb, settings);
                sp_usb.buses.iter().for_each(|bo| {
                    bo.devices
                        .iter()
                        .for_each(|b| settings.icon_when.retain(b, &mut db, settings));
                });
            }
        }

        let base_tree = TreeData {
            ..Default::default()
        };

        let mut pad: HashMap<BusBlocks, usize> = if !settings.no_padding {
            BusBlocks::generate_padding(&sp_usb.buses.iter().collect::<Vec<&Bus>>())
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| bb.contains(k));

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let variable_lens: Vec<usize> = pad
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(&bb, base_tree.depth * 3, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        log::trace!(
            "print system profile with settings: {settings:?}; padding: {pad:?}; tree {base_tree:?}"
        );

        let len = sp_usb.buses.iter().filter(|b| !b.is_hidden()).count();
        for (i, bus) in sp_usb.buses.iter().filter(|b| !b.is_hidden()).enumerate() {
            if settings.tree {
                let mut prefix = base_tree.prefix.to_owned();
                let mut start = settings.icons.as_ref().map_or(
                    icon::get_default_tree_icon(&icon::Icon::TreeBusStart, &settings.encoding),
                    |i| i.get_tree_icon(&icon::Icon::TreeBusStart, &settings.encoding),
                );

                // colour tree
                if let Some(ct) = settings.colours.as_ref() {
                    prefix = ct
                        .tree
                        .map_or(prefix.normal(), |c| prefix.color(c))
                        .to_string();
                    start = ct
                        .tree_bus_start
                        .map_or(start.normal(), |c| start.color(c))
                        .to_string();
                }

                if settings.headings {
                    let heading = render_heading(&bb, &pad, max_variable_string_len).join(" ");
                    // 2 spaces for bus start icon and space to info
                    self.println(
                        format!("{:>spaces$}{}", "", heading.bold().underline(), spaces = 2),
                        LineItem::Bus(i),
                    )
                    .unwrap();
                }

                self.print(format!("{prefix}{start} ")).unwrap()
            } else if settings.headings {
                let heading = render_heading(&bb, &pad, max_variable_string_len).join(" ");
                // 2 spaces for bus start icon and space to info
                self.println(format!("{}", heading.bold().underline()), LineItem::Bus(i))
                    .unwrap();
            }
            self.println(
                render_value(
                    bus,
                    &bb,
                    &pad,
                    settings,
                    max_variable_string_len,
                    LineStyle::Normal,
                )
                .join(" "),
                LineItem::Bus(i),
            )
            .unwrap();

            if let Some(d) = bus.devices.as_ref() {
                let num = d.iter().filter(|d| !d.is_hidden()).count();
                let tree = generate_tree_data(&base_tree, num, i, settings);
                let mut padding = if !settings.no_padding {
                    // if tree, generate padding for only local devices
                    // otherwise we need it for all device as flattened
                    if settings.tree {
                        let devices = d
                            .iter()
                            .filter(|d| !d.is_hidden())
                            .collect::<Vec<&Device>>();
                        DeviceBlocks::generate_padding(&devices)
                    } else {
                        let devices = bus
                            .flattened_devices()
                            .into_iter()
                            .filter(|d| !d.is_hidden())
                            .collect::<Vec<&Device>>();
                        DeviceBlocks::generate_padding(&devices)
                    }
                } else {
                    HashMap::new()
                };
                padding.retain(|k, _| db.contains(k));

                // and then walk down devices printing them too
                self.print_devices(d, &db, settings, &tree, &padding);
            }

            // separate bus groups with line
            if i + 1 != len {
                self.println("", LineItem::None).unwrap();
            }
        }
    }

    /// Print `devices` [`Device`] references without looking down each device's devices!
    pub fn print_flattened_devices(&mut self, devices: &[&Device], settings: &PrintSettings) {
        let mut db = settings
            .device_blocks
            .to_owned()
            .unwrap_or(DeviceBlocks::default_blocks(settings.more));

        // remove icon blocks if not supported
        match settings.icon_when {
            IconWhen::Never | IconWhen::Auto if settings.icons.is_none() => {
                db.retain(|b| !b.is_icon());
            }
            IconWhen::Auto if settings.encoding == Encoding::Glyphs => (),
            IconWhen::Always => {
                if settings.icons.is_none() {
                    log::warn!(
                        "{:?} blocks requested but no icons provided",
                        settings.icon_when
                    );
                }
            }
            _ => settings.icon_when.retain_ref(devices, &mut db, settings),
        }

        let mut pad = if !settings.no_padding {
            DeviceBlocks::generate_padding(devices)
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| db.contains(k));
        log::trace!("Flattened devices padding {pad:?}");

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let variable_lens: Vec<usize> = pad
                .iter()
                .filter(|(k, _)| k.value_is_variable_length())
                .map(|(_, v)| *v)
                .collect();
            auto_max_string_len(&db, 0, &variable_lens, settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        if settings.headings {
            let heading = render_heading(&db, &pad, max_variable_string_len).join(" ");
            println!("{}", heading.bold().underline());
        }

        for (i, device) in devices.iter().enumerate() {
            let line_style = if device.is_disconnected() {
                LineStyle::Dimmed
            } else if settings.mute_hubs && device.class == Some(BaseClass::Hub) {
                LineStyle::Muted
            } else {
                LineStyle::Normal
            };
            println!(
                "{}",
                render_value(
                    *device,
                    &db,
                    &pad,
                    settings,
                    max_variable_string_len,
                    line_style,
                )
                .join(" ")
            );
            // print the configurations
            if let Some(extra) = device.extra.as_ref() {
                if settings.verbosity >= 1 || device.is_expanded() {
                    let blocks = generate_extra_blocks(extra, settings);

                    // pass branch length as number of configurations for this device plus devices still to print
                    self.print_configurations(
                        device,
                        &extra.configurations,
                        (&blocks.0, &blocks.1, &blocks.2),
                        settings,
                        &generate_tree_data(
                            &Default::default(),
                            extra.configurations.len()
                                + device
                                    .devices
                                    .as_ref()
                                    .map_or(0, |d| d.iter().filter(|d| !d.is_hidden()).count()),
                            i,
                            settings,
                        ),
                    );
                }
            } else if settings.verbosity >= 1 {
                log::warn!(
                    "Unable to print verbose information for {device} because libusb extra data is missing"
                )
            }
        }
    }

    /// A way of printing a reference flattened [`SystemProfile`] rather than hard flatten
    ///
    /// Prints each `&Bus` and tuple pair `Vec<&Device>`
    pub fn print_bus_grouped(
        &mut self,
        bus_devices: Vec<(&Bus, Vec<&Device>)>,
        settings: &PrintSettings,
    ) {
        let bb = settings
            .bus_blocks
            .to_owned()
            .unwrap_or(Block::<BusBlocks, Bus>::default_blocks(settings.more));
        let mut pad: HashMap<BusBlocks, usize> = if !settings.no_padding {
            let buses: Vec<&Bus> = bus_devices.iter().map(|bd| bd.0).collect();
            BusBlocks::generate_padding(&buses)
        } else {
            HashMap::new()
        };
        pad.retain(|k, _| bb.contains(k));

        let max_variable_string_len: Option<usize> = if settings.auto_width {
            let mut variable_lens = pad.clone();
            variable_lens.retain(|k, _| k.value_is_variable_length());
            auto_max_string_len(&bb, 0, &variable_lens.into_values().collect(), settings)
                .or(settings.max_variable_string_len)
        } else {
            settings.max_variable_string_len
        };

        // if there is a max variable length, adjust padding to this if current > it
        if let Some(ml) = max_variable_string_len.as_ref() {
            for (k, v) in pad.iter_mut() {
                if k.value_is_variable_length() {
                    *v = cmp::min(*v, *ml);
                }
            }
        }

        let len = bus_devices.len();
        for (i, (bus, devices)) in bus_devices.into_iter().enumerate() {
            if settings.headings {
                let heading = render_heading(&bb, &pad, max_variable_string_len).join(" ");
                self.println(format!("{}", heading.bold().underline()), LineItem::Bus(i))
                    .unwrap();
            }
            self.println(
                render_value(
                    bus,
                    &bb,
                    &pad,
                    settings,
                    max_variable_string_len,
                    LineStyle::Normal,
                )
                .join(" "),
                LineItem::Bus(i),
            )
            .unwrap();
            self.print_flattened_devices(&devices, settings);
            // new line for each group
            if i + 1 != len {
                self.println("", LineItem::None).unwrap();
            }
        }
    }
}

/// Mask the `device` serial if it has one using the [`MaskSerial`] method and recursively if `recursive`
pub fn mask_serial(device: &mut Device, hide: &MaskSerial, recursive: bool) {
    if let Some(serial) = device.serial_num.as_mut() {
        *serial = match hide {
            MaskSerial::Hide => serial.chars().map(|_| '*').collect::<String>(),
            MaskSerial::Scramble => serial
                .chars()
                .map(|_| {
                    serial
                        .chars()
                        .nth(fastrand::usize(0..serial.len()))
                        .unwrap_or('*')
                })
                .collect::<String>(),
            MaskSerial::Replace => serial
                .chars()
                .map(|_| fastrand::alphanumeric())
                .collect::<String>()
                .to_uppercase(),
            _ => serial.to_string(),
        };
    }

    if recursive {
        device
            .devices
            .iter_mut()
            .for_each(|dd| dd.iter_mut().for_each(|d| mask_serial(d, hide, recursive)));
    }
}

/// Main cyme bin prepare for printing function - changes mutable `sp_usb` with requested `filter` and sort in `settings`
pub fn prepare(
    sp_usb: &mut SystemProfile,
    filter: Option<&DeviceFilter>,
    settings: &PrintSettings,
) {
    // if not printing tree, hard flatten now before filtering as filter will retain non-matching parents with matching devices in tree
    // flattening now will also mean hubs will be removed when listing if `hide_hubs` because they will appear empty and sorting will be in bus -> device order rather than tree position
    log::debug!("Running prepare pre-printing");
    if !settings.tree && !matches!(settings.print_mode, PrintMode::Dynamic) {
        log::debug!("Flattening SPUSBDataType");
        sp_usb.into_flattened();
    }

    // do the filter if present; will keep parents of matched devices even if they do not match
    log::debug!("Filtering with {filter:?}");
    if let Some(filter) = filter {
        if matches!(settings.print_mode, PrintMode::Dynamic) {
            filter.hide_buses(&mut sp_usb.buses);
        } else {
            filter.retain_buses(&mut sp_usb.buses);
        }
    }

    // sort device tree based on sort option
    log::debug!("Sorting with {:?}", settings.sort_devices);
    settings.sort_devices.sort_buses(&mut sp_usb.buses);

    // sort the buses if asked and not already sorted
    if settings.sort_buses && matches!(settings.sort_devices, Sort::NoSort) {
        log::debug!("Sorting buses by bus number");
        sp_usb.buses.sort_by_key(|d| d.get_bus_number());
    }

    // hide serials Recursively
    if let Some(hide) = settings.mask_serials.as_ref() {
        log::debug!("Masking serials with {hide:?}");
        for bus in &mut sp_usb.buses {
            bus.devices.iter_mut().for_each(|devices| {
                for device in devices {
                    mask_serial(device, hide, true);
                }
            });
        }
    }

    log::trace!("sp_usb data post filter and bus sort\n\r{sp_usb:#}");
}

/// Main cyme bin print function
pub fn print(sp_usb: &SystemProfile, settings: &PrintSettings) {
    log::trace!("Printing with {settings:?}");
    let mut dw = DisplayWriter::default();

    match settings.color_when {
        ColorWhen::Always => colored::control::set_override(true),
        ColorWhen::Never => colored::control::set_override(false),
        ColorWhen::Auto => colored::control::unset_override(),
    }

    if settings.tree || settings.group_devices == Group::Bus {
        if settings.json {
            println!("{}", serde_json::to_string_pretty(&sp_usb).unwrap());
        } else {
            dw.print_sp_usb(sp_usb, settings);
        }
    } else {
        // get a list of all devices
        let devs = sp_usb.flattened_devices();

        if settings.json {
            println!("{}", serde_json::to_string_pretty(&devs).unwrap());
        } else {
            dw.print_flattened_devices(&devs, settings);
        }
    }
}