ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
//! Physical memory topology monitoring.
//!
//! Enumerates DIMM slots, memory speeds, timings, ECC status, ranks, and
//! manufacturer information. Provides inference-based bandwidth estimation
//! and upgrade recommendations based on empty slots and configuration.
//!
//! ## Platform Support
//!
//! - **Linux**: DMI/SMBIOS via `/sys/class/dmi/id/` and `dmidecode` output parsing
//! - **Windows**: `Win32_PhysicalMemory` and `Win32_PhysicalMemoryArray` via WMI
//! - **macOS**: `system_profiler SPMemoryDataType`

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::error::IronError;

/// Memory technology type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MemoryType {
    DDR2,
    DDR3,
    DDR4,
    DDR5,
    LPDDR4,
    LPDDR4X,
    LPDDR5,
    LPDDR5X,
    HBM2,
    HBM2E,
    HBM3,
    HBM3E,
    GDDR6,
    GDDR6X,
    ECC,
    Unknown,
}

impl std::fmt::Display for MemoryType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DDR2 => write!(f, "DDR2"),
            Self::DDR3 => write!(f, "DDR3"),
            Self::DDR4 => write!(f, "DDR4"),
            Self::DDR5 => write!(f, "DDR5"),
            Self::LPDDR4 => write!(f, "LPDDR4"),
            Self::LPDDR4X => write!(f, "LPDDR4X"),
            Self::LPDDR5 => write!(f, "LPDDR5"),
            Self::LPDDR5X => write!(f, "LPDDR5X"),
            Self::HBM2 => write!(f, "HBM2"),
            Self::HBM2E => write!(f, "HBM2e"),
            Self::HBM3 => write!(f, "HBM3"),
            Self::HBM3E => write!(f, "HBM3e"),
            Self::GDDR6 => write!(f, "GDDR6"),
            Self::GDDR6X => write!(f, "GDDR6X"),
            Self::ECC => write!(f, "ECC"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Form factor of the memory module.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FormFactor {
    DIMM,
    SODIMM,
    LRDIMM,
    RDIMM,
    UDIMM,
    NVDIMM,
    OnBoard,
    /// In the processor package itself, as Apple silicon's unified memory is.
    /// There is no slot, and the channel count is not reported.
    OnPackage,
    Unknown,
}

impl std::fmt::Display for FormFactor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::DIMM => "DIMM",
            Self::SODIMM => "SO-DIMM",
            Self::LRDIMM => "LR-DIMM",
            Self::RDIMM => "R-DIMM",
            Self::UDIMM => "U-DIMM",
            Self::NVDIMM => "NV-DIMM",
            Self::OnBoard => "On-Board",
            Self::OnPackage => "On-Package",
            Self::Unknown => "Unknown",
        };
        write!(f, "{}", s)
    }
}

/// Information about a single DIMM / memory module.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimmInfo {
    /// Slot/bank locator string (e.g. "DIMM_A1", "ChannelA-DIMM0").
    pub locator: String,
    /// Bank locator.
    pub bank: String,
    /// Capacity in bytes, or `None` where no size was read -- including every
    /// empty slot.
    ///
    /// This was a `u64` documented "0 means empty slot", and the macOS and
    /// Windows readers derived `populated` from it as `capacity > 0`. So a
    /// module whose size string did not parse was reported as an **empty
    /// slot**: an unread value became a claim about the hardware. Size and
    /// presence are now separate facts with separate sources.
    pub capacity_bytes: Option<u64>,
    /// Rated speed in MT/s, or `None` where it was not read.
    ///
    /// `parse_mts` returned `0` for anything it could not parse, and the
    /// Windows reader used `.unwrap_or(0)` on a missing `Speed`.
    pub speed_mts: Option<u32>,
    /// Configured speed in MT/s, or `None` where the platform did not report
    /// one.
    ///
    /// **All three readers substituted the rated speed when this was missing**
    /// -- Linux with `if conf_speed_str.is_empty() { speed_mts }`, Windows with
    /// `ConfiguredClockSpeed.unwrap_or(speed)`, macOS by assigning
    /// `configured_speed_mts: speed_mts` unconditionally, since
    /// `system_profiler` reports no configured speed at all. Rated and
    /// configured are precisely the two figures that differ when XMP or EXPO
    /// is not enabled, so the substitution asserted "this memory runs at its
    /// rated speed" on exactly the machines where that is least certain. The
    /// ontology published it under `memory.dimm.{n}.configured_speed`.
    pub configured_speed_mts: Option<u32>,
    /// Memory type.
    pub memory_type: MemoryType,
    /// Form factor.
    pub form_factor: FormFactor,
    /// Data width in bits, where it was read. See [`Self::is_ecc`].
    pub data_width_bits: Option<u32>,
    /// Total width in bits, where it was read. See [`Self::is_ecc`].
    pub total_width_bits: Option<u32>,
    /// Number of ranks, or `None` where it was not read.
    ///
    /// Windows and macOS set `1` unconditionally -- one beside the comment
    /// "WMI doesn't expose rank count easily" -- and Linux fell back to `1`
    /// when SMBIOS carried no `Rank` field. Single-rank is a specific,
    /// plausible and consequential claim: rank count affects achievable
    /// bandwidth and interleaving, which is what this module estimates.
    pub ranks: Option<u32>,
    /// Manufacturer name.
    pub manufacturer: String,
    /// Part number.
    pub part_number: String,
    /// Serial number.
    pub serial_number: String,
    /// Whether this slot holds a module, or `None` where nothing established
    /// it either way.
    ///
    /// Set only from evidence of presence or absence -- a module row that
    /// exists, a status field, a size that parsed, a part number -- and never
    /// inferred from a size that could not be read.
    pub populated: Option<bool>,
    /// Operating voltage in volts, or `None` where the firmware reported
    /// none.
    ///
    /// This was `f64`, and the Windows reader set it to `0.0` under the comment
    /// "WMI doesn't provide this easily". WMI provides it directly:
    /// `Win32_PhysicalMemory.ConfiguredVoltage`, in millivolts. The query
    /// simply did not select the column. On this crate's development machine it
    /// reads 1100 mV, and the ontology had been publishing
    /// "SMBIOS reported no operating voltage" for it.
    pub voltage: Option<f64>,
}

impl DimmInfo {
    /// Capacity in GiB, where the size was read.
    pub fn capacity_gib(&self) -> Option<f64> {
        self.capacity_bytes
            .map(|b| b as f64 / (1024.0 * 1024.0 * 1024.0))
    }

    /// Whether this DIMM has ECC, or `None` when either width is unknown.
    ///
    /// ECC is inferred from the total width exceeding the data width — 72 bits
    /// carrying 64. Both widths defaulted: Windows and Linux set `data_width`
    /// to 64 and `total_width` to whatever `data_width` came out as, and macOS
    /// hardcoded both to 64. Equal widths mean no ECC, so **a machine with ECC
    /// memory reported that it had none** whenever the widths were not read,
    /// and always on macOS.
    pub fn is_ecc(&self) -> Option<bool> {
        Some(self.total_width_bits? > self.data_width_bits?)
    }
}

/// Inferred memory configuration analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryAnalysis {
    /// Total installed capacity in bytes, summed over the populated modules.
    ///
    /// `None` when any populated module's size was not read. A sum that left
    /// that module out would be short by an amount nothing reported.
    pub total_capacity_bytes: Option<u64>,
    /// The board's declared maximum memory capacity in bytes (SMBIOS type 16,
    /// the Physical Memory Array), summed over the system-memory arrays.
    ///
    /// Not the installed amount, and not a per-slot estimate. `None` where the
    /// record was not read: on Linux that needs root for `dmidecode`, and macOS
    /// publishes no such figure. It used to be a per-slot guess multiplied by
    /// the slot count, and before that a constant `None` that nothing filled.
    pub max_capacity_bytes: Option<u64>,
    /// Number of modules the reader enumerated as populated.
    pub populated_slots: usize,
    /// Total number of slots, or `None` where the source lists installed
    /// modules only.
    ///
    /// SMBIOS type 17 and `system_profiler` list empty slots too. The Windows
    /// reader queries `Win32_PhysicalMemory`, which does not, so it has no
    /// slot count.
    pub total_slots: Option<usize>,
    /// Whether running in dual-channel mode, or `None` where the channel
    /// count was not read.
    pub dual_channel: Option<bool>,
    /// Whether running in quad-channel mode, or `None` where the channel
    /// count was not read.
    pub quad_channel: Option<bool>,
    /// Whether all DIMMs are the same speed, or `None` where fewer than two
    /// speeds were read. One value is nothing to match.
    pub matched_speeds: Option<bool>,
    /// Whether all DIMMs are the same capacity (optimal for interleaving), or
    /// `None` where fewer than two capacities were read.
    pub matched_capacities: Option<bool>,
    /// Whether ECC is active: `Some(true)` if any populated module has it,
    /// `Some(false)` only when every populated module was read and none does,
    /// and `None` otherwise. Unread widths are not evidence of no ECC.
    pub ecc_active: Option<bool>,
    /// Estimated peak bandwidth in GB/s, or `None` where no DIMM speed was
    /// read.
    ///
    /// An estimate, and labelled as one -- it multiplies the fastest DIMM's
    /// rated speed by bus width and inferred channel count, and measures
    /// nothing. It was `0.0` when no speed was read, which is an estimate of no
    /// bandwidth at all.
    pub estimated_bandwidth_gbs: Option<f64>,
    /// Inferred memory channel count, or `None` where no locator named a
    /// channel and the count does not establish one.
    ///
    /// A count of modules does not: two modules may share a channel or not.
    pub channel_count: Option<u32>,
    /// Upgrade recommendations.
    pub recommendations: Vec<String>,
    /// Efficiency score 0-100 (how well the memory is configured), or `None`
    /// where it cannot be scored: fewer than two modules' speeds or
    /// capacities were read, or the channel count was not.
    pub efficiency_score: Option<u32>,
}

/// Full memory topology for the system.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryTopology {
    /// All DIMM slots (populated and empty).
    pub dimms: Vec<DimmInfo>,
    /// Memory analysis with inference.
    pub analysis: MemoryAnalysis,
}

/// Memory topology monitor.
pub struct MemoryTopologyMonitor {
    topology: MemoryTopology,
}

impl MemoryTopologyMonitor {
    /// Whether the platform's source lists empty slots as well as installed
    /// modules. SMBIOS type 17 and `system_profiler` do. `Win32_PhysicalMemory`
    /// lists only installed modules, so a Windows slot count would be a guess.
    const SOURCE_LISTS_EMPTY_SLOTS: bool = !cfg!(target_os = "windows");

    /// Create a new memory topology monitor.
    pub fn new() -> Result<Self, IronError> {
        let dimms = Self::enumerate_dimms()?;
        let analysis = Self::analysis_of(&dimms);
        Ok(Self {
            topology: MemoryTopology { dimms, analysis },
        })
    }

    /// Refresh data.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.topology.dimms = Self::enumerate_dimms()?;
        self.topology.analysis = Self::analysis_of(&self.topology.dimms);
        Ok(())
    }

    /// The analysis of the enumerated modules, plus the board's declared
    /// maximum, which comes from a different record and is read separately.
    fn analysis_of(dimms: &[DimmInfo]) -> MemoryAnalysis {
        let mut analysis = Self::analyze(dimms);
        analysis.max_capacity_bytes = Self::max_capacity_bytes();
        analysis
    }

    /// Get the topology.
    pub fn topology(&self) -> &MemoryTopology {
        &self.topology
    }

    /// Get populated DIMMs only.
    pub fn populated_dimms(&self) -> Vec<&DimmInfo> {
        self.topology
            .dimms
            .iter()
            .filter(|d| d.populated == Some(true))
            .collect()
    }

    /// Get empty slots.
    pub fn empty_slots(&self) -> Vec<&DimmInfo> {
        self.topology
            .dimms
            .iter()
            .filter(|d| d.populated == Some(false))
            .collect()
    }

    /// Analyze memory configuration.
    fn analyze(dimms: &[DimmInfo]) -> MemoryAnalysis {
        let populated: Vec<&DimmInfo> =
            dimms.iter().filter(|d| d.populated == Some(true)).collect();
        // Sums the sizes that were read. One unread size makes the total
        // unknown, rather than a total that quietly leaves that module out.
        // No enumerated module is no total at all, not a total of zero.
        let total_capacity_bytes: Option<u64> = if populated.is_empty() {
            None
        } else {
            populated.iter().map(|d| d.capacity_bytes).sum()
        };
        let populated_count = populated.len();
        // Memory in the processor package has no slots, and its one row says
        // nothing about channels: an M1's LPDDR4X runs on several, and
        // `system_profiler` reports none of them.
        let on_package = dimms.iter().any(|d| d.form_factor == FormFactor::OnPackage);
        // Only a source that lists empty slots can count them, and only when it
        // listed rows: a source with no rows has no slot count, not a count of
        // zero.
        let total_slots = (Self::SOURCE_LISTS_EMPTY_SLOTS && !dimms.is_empty() && !on_package)
            .then_some(dimms.len());

        // Matched speeds and capacities need two values to compare. With fewer,
        // there is no match to report, so the answer is unknown rather than
        // "matched".
        let speeds: Vec<u32> = populated.iter().filter_map(|d| d.speed_mts).collect();
        let capacities: Vec<u64> = populated.iter().filter_map(|d| d.capacity_bytes).collect();
        let matched_speeds = (speeds.len() >= 2).then(|| speeds.windows(2).all(|w| w[0] == w[1]));
        let matched_capacities =
            (capacities.len() >= 2).then(|| capacities.windows(2).all(|w| w[0] == w[1]));

        // ECC detection. A DIMM whose widths were not read is not a DIMM known
        // to lack ECC, so "no ECC" needs every populated module answered.
        let ecc_active = if populated.iter().any(|d| d.is_ecc() == Some(true)) {
            Some(true)
        } else if !populated.is_empty() && populated.iter().all(|d| d.is_ecc() == Some(false)) {
            Some(false)
        } else {
            None
        };

        // Channel inference from locator naming patterns. `None` when no locator
        // names a channel and the module count does not establish one.
        let channel_count = if on_package {
            None
        } else {
            Self::infer_channels(&populated)
        };
        let dual_channel = channel_count.map(|c| c >= 2);
        let quad_channel = channel_count.map(|c| c >= 4);

        // Bandwidth estimation
        // No speed read on any DIMM, or no channel count, means no estimate.
        // `.max().unwrap_or(0)` fed `estimate_bandwidth(0, ..)`, which published
        // 0.00 GB/s -- an estimate of no memory bandwidth for a machine whose
        // DIMMs could not be read.
        let estimated_bandwidth_gbs = match (speeds.iter().copied().max(), channel_count) {
            (Some(max_speed), Some(channels)) => {
                Some(Self::estimate_bandwidth(max_speed, channels))
            }
            _ => None,
        };

        // Recommendations
        let mut recommendations = Vec::new();
        // Scored only when every input it weighs was read. Without the channel
        // count, or with fewer than two modules to compare, a score would
        // reward matches that nothing established.
        let efficiency_score = match (matched_speeds, matched_capacities, dual_channel) {
            (Some(speeds_match), Some(capacities_match), Some(dual)) => {
                Some(Self::compute_efficiency(
                    &populated,
                    total_slots,
                    speeds_match,
                    capacities_match,
                    dual,
                    &mut recommendations,
                ))
            }
            _ => None,
        };

        MemoryAnalysis {
            total_capacity_bytes,
            // Not derived from the modules. `analysis_of` sets it from the
            // memory array record.
            max_capacity_bytes: None,
            populated_slots: populated_count,
            total_slots,
            dual_channel,
            quad_channel,
            matched_speeds,
            matched_capacities,
            ecc_active,
            estimated_bandwidth_gbs,
            channel_count,
            recommendations,
            efficiency_score,
        }
    }

    fn infer_channels(populated: &[&DimmInfo]) -> Option<u32> {
        if populated.is_empty() {
            return None;
        }

        // Try to detect channels from locator strings
        let mut channels: std::collections::HashSet<String> = std::collections::HashSet::new();
        for d in populated {
            let loc = d.locator.to_uppercase();
            // Common patterns: "DIMM_A1", "ChannelA-DIMM0", "BANK 0", "Channel A"
            if loc.contains("CHANNEL") || loc.contains("DIMM_") {
                // Extract channel letter
                for c in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] {
                    if loc.contains(c)
                        && (loc.contains(&format!("CHANNEL{}", c))
                            || loc.contains(&format!("CHANNEL {}", c))
                            || loc.contains(&format!("DIMM_{}", c))
                            || loc.contains(&format!("_{}{}", c, '0'))
                            || loc.contains(&format!("_{}{}", c, '1')))
                    {
                        channels.insert(c.to_string());
                    }
                }
            }
        }

        if channels.is_empty() {
            // A single module occupies one channel. Beyond that, a count of
            // modules does not say how they are wired: two may share a channel
            // or not, so the count is left unread rather than guessed.
            (populated.len() == 1).then_some(1)
        } else {
            Some(channels.len() as u32)
        }
    }

    /// Estimate peak memory bandwidth in GB/s.
    fn estimate_bandwidth(speed_mts: u32, channels: u32) -> f64 {
        // Bandwidth (GB/s) = speed (MT/s) × 8 bytes × channels / 1000
        let bw = speed_mts as f64 * 8.0 * channels as f64 / 1000.0;
        (bw * 100.0).round() / 100.0
    }

    fn compute_efficiency(
        populated: &[&DimmInfo],
        total_slots: Option<usize>,
        matched_speeds: bool,
        matched_capacities: bool,
        dual_channel: bool,
        recommendations: &mut Vec<String>,
    ) -> u32 {
        let mut score: i32 = 70; // Base score

        // Dual-channel bonus. Without a slot count, the populated modules are
        // the only lower bound on the slots.
        if dual_channel {
            score += 10;
        } else if total_slots.unwrap_or(populated.len()) >= 2 {
            score -= 15;
            recommendations.push("Enable dual-channel by populating matching DIMM pairs".into());
        }

        // Matched speeds
        if matched_speeds {
            score += 5;
        } else {
            score -= 10;
            recommendations.push("Mismatched DIMM speeds—all modules run at slowest speed".into());
        }

        // Matched capacities
        if matched_capacities {
            score += 5;
        } else {
            score -= 5;
            recommendations
                .push("Mismatched DIMM capacities reduce interleaving efficiency".into());
        }

        // Empty slots = upgrade potential. Counted only where the source lists
        // empty slots; otherwise no empty slot is known to exist.
        if let Some(total) = total_slots {
            let empty = total.saturating_sub(populated.len());
            if empty > 0 {
                score += 5; // Upgrade headroom is a positive
                recommendations.push(format!(
                    "{} empty DIMM slot(s) available for expansion",
                    empty
                ));
            }
        }

        // ECC bonus for workstations/servers. Only credited where ECC was
        // actually observed.
        if populated.iter().any(|d| d.is_ecc() == Some(true)) {
            score += 5;
        }

        score.clamp(0, 100) as u32
    }

    /// The board's declared maximum capacity, or `None` where it was not read.
    ///
    /// Never an error: a missing maximum must not fail the module listing.
    #[cfg(target_os = "linux")]
    fn max_capacity_bytes() -> Option<u64> {
        // SMBIOS type 16 through dmidecode. Reading it needs root, so an
        // unprivileged run fails here and the answer is unknown.
        let out = std::process::Command::new("dmidecode")
            .args(["-t", "16"])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        Self::parse_dmidecode_max_capacity(&String::from_utf8_lossy(&out.stdout))
    }

    #[cfg(target_os = "windows")]
    fn max_capacity_bytes() -> Option<u64> {
        let out = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-CimInstance Win32_PhysicalMemoryArray | Select-Object MaxCapacityEx,MaxCapacity,Use | ConvertTo-Json",
            ])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        Self::parse_windows_max_capacity(&String::from_utf8_lossy(&out.stdout))
    }

    /// macOS publishes no board maximum, so there is nothing to read.
    #[cfg(not(any(target_os = "linux", target_os = "windows")))]
    fn max_capacity_bytes() -> Option<u64> {
        None
    }

    /// The board maximum from `Win32_PhysicalMemoryArray` JSON, in bytes.
    ///
    /// Sums `MaxCapacityEx` (or `MaxCapacity` where Ex is zero or absent) over
    /// the arrays whose `Use` is 3, system memory. Both are in kilobytes. An
    /// array with no usable capacity leaves the sum short, so the answer is
    /// `None`, as is output with no system-memory array in it.
    #[allow(dead_code)]
    fn parse_windows_max_capacity(text: &str) -> Option<u64> {
        let trimmed = text.trim();
        let items: Vec<serde_json::Value> = match serde_json::from_str(trimmed).ok()? {
            serde_json::Value::Array(items) => items,
            obj @ serde_json::Value::Object(_) => vec![obj],
            _ => return None,
        };

        let mut total: u64 = 0;
        let mut system_arrays = 0usize;
        for item in items.iter().filter(|i| i["Use"].as_u64() == Some(3)) {
            system_arrays += 1;
            let ex = item["MaxCapacityEx"].as_u64().filter(|&kb| kb > 0);
            // 0x80000000 in MaxCapacity is the marker for "see MaxCapacityEx".
            // Without Ex, that value is no capacity to report.
            let plain = item["MaxCapacity"]
                .as_u64()
                .filter(|&kb| kb > 0 && kb != 0x8000_0000);
            let kb = ex.or(plain)?;
            total = total.checked_add(kb.checked_mul(1024)?)?;
        }
        (system_arrays > 0).then_some(total)
    }

    /// The board maximum from `dmidecode -t 16` output, in bytes.
    ///
    /// Each `Physical Memory Array` record names its `Use` and its
    /// `Maximum Capacity`. The system-memory records are summed. A record
    /// whose capacity is missing or unparsed leaves the sum short, so the
    /// answer is `None`.
    #[allow(dead_code)]
    fn parse_dmidecode_max_capacity(text: &str) -> Option<u64> {
        let mut total: u64 = 0;
        let mut system_arrays = 0usize;
        for block in text.split("\nHandle ") {
            if !block.contains("Physical Memory Array") {
                continue;
            }
            let field = |key: &str| {
                block
                    .lines()
                    .map(str::trim)
                    .find_map(|l| l.strip_prefix(key).map(str::trim))
            };
            match field("Use:") {
                Some("System Memory") => {}
                Some(_) => continue,
                None => return None,
            }
            system_arrays += 1;
            let bytes = Self::parse_size_to_bytes(field("Maximum Capacity:")?)?;
            total = total.checked_add(bytes)?;
        }
        (system_arrays > 0).then_some(total)
    }

    #[cfg(target_os = "linux")]
    fn enumerate_dimms() -> Result<Vec<DimmInfo>, IronError> {
        // Try dmidecode parsing
        let output = std::process::Command::new("dmidecode")
            .args(["-t", "memory"])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let text = String::from_utf8_lossy(&out.stdout);
                Ok(Self::parse_dmidecode(&text))
            }
            Ok(out) => Err(IronError::CommandFailed(format!(
                "dmidecode -t memory failed: {}",
                one_line(&out.stderr)
            ))),
            // dmidecode missing from PATH, or not runnable
            Err(e) => Err(e.into()),
        }
    }

    #[cfg(target_os = "windows")]
    fn enumerate_dimms() -> Result<Vec<DimmInfo>, IronError> {
        let output = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-CimInstance Win32_PhysicalMemory | Select-Object BankLabel,DeviceLocator,Capacity,Speed,ConfiguredClockSpeed,ConfiguredVoltage,MemoryType,SMBIOSMemoryType,FormFactor,DataWidth,TotalWidth,Manufacturer,PartNumber,SerialNumber | ConvertTo-Json",
            ])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let text = String::from_utf8_lossy(&out.stdout);
                Self::parse_windows_wmi(&text)
            }
            Ok(out) => Err(IronError::CommandFailed(format!(
                "Get-CimInstance Win32_PhysicalMemory failed: {}",
                one_line(&out.stderr)
            ))),
            // powershell missing from PATH, or not runnable
            Err(e) => Err(e.into()),
        }
    }

    #[cfg(target_os = "macos")]
    fn enumerate_dimms() -> Result<Vec<DimmInfo>, IronError> {
        let output = std::process::Command::new("system_profiler")
            .args(["SPMemoryDataType", "-json"])
            .output();

        match output {
            Ok(out) if out.status.success() => {
                let text = String::from_utf8_lossy(&out.stdout);
                Self::parse_macos_profiler(&text)
            }
            Ok(out) => Err(IronError::CommandFailed(format!(
                "system_profiler SPMemoryDataType failed: {}",
                one_line(&out.stderr)
            ))),
            // system_profiler missing from PATH, or not runnable
            Err(e) => Err(e.into()),
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn enumerate_dimms() -> Result<Vec<DimmInfo>, IronError> {
        Err(IronError::UnsupportedPlatform(
            "memory topology is not read on this platform".into(),
        ))
    }

    #[allow(dead_code)]
    fn parse_dmidecode(text: &str) -> Vec<DimmInfo> {
        let mut dimms = Vec::new();
        let mut in_device = false;
        let mut fields: HashMap<String, String> = HashMap::new();

        for line in text.lines() {
            let trimmed = line.trim();

            if trimmed == "Memory Device" {
                if in_device && !fields.is_empty() {
                    if let Some(dimm) = Self::dimm_from_fields(&fields) {
                        dimms.push(dimm);
                    }
                }
                in_device = true;
                fields.clear();
                continue;
            }

            if in_device {
                if let Some((key, val)) = trimmed.split_once(':') {
                    fields.insert(key.trim().to_string(), val.trim().to_string());
                }
            }
        }

        // Don't forget the last one
        if in_device && !fields.is_empty() {
            if let Some(dimm) = Self::dimm_from_fields(&fields) {
                dimms.push(dimm);
            }
        }

        dimms
    }

    fn dimm_from_fields(fields: &HashMap<String, String>) -> Option<DimmInfo> {
        let locator = fields.get("Locator").cloned().unwrap_or_default();
        let bank = fields.get("Bank Locator").cloned().unwrap_or_default();

        let size_str = fields.get("Size").cloned().unwrap_or_default();
        // "No Module Installed" is SMBIOS saying the slot is empty. Anything
        // else is a size, or a size nobody could read -- and "Unknown" used to
        // count as empty too, which is a claim the firmware did not make.
        let slot_empty = size_str.contains("No Module Installed");
        let capacity_bytes = if slot_empty {
            None
        } else {
            Self::parse_size_to_bytes(&size_str)
        };

        let speed_str = fields.get("Speed").cloned().unwrap_or_default();
        let speed_mts = Self::parse_mts(&speed_str);

        let conf_speed_str = fields
            .get("Configured Memory Speed")
            .or(fields.get("Configured Clock Speed"))
            .cloned()
            .unwrap_or_default();
        // No substitution. An absent "Configured Memory Speed" is not
        // evidence that the DIMM runs at its rated speed.
        let configured_speed_mts = Self::parse_mts(&conf_speed_str);

        let type_str = fields.get("Type").cloned().unwrap_or_default();
        let memory_type = Self::parse_memory_type(&type_str);

        let ff_str = fields.get("Form Factor").cloned().unwrap_or_default();
        let form_factor = Self::parse_form_factor(&ff_str);

        // 64 is the common data width and not this DIMM's, and defaulting the
        // total width to the data width asserts "no ECC" for a field that was
        // not read.
        let data_width = fields
            .get("Data Width")
            .and_then(|s| s.split_whitespace().next())
            .and_then(|s| s.parse::<u32>().ok());

        let total_width = fields
            .get("Total Width")
            .and_then(|s| s.split_whitespace().next())
            .and_then(|s| s.parse::<u32>().ok());

        // SMBIOS reports `Unknown` or omits the field on many boards; that is
        // not a single-rank DIMM.
        let rank = fields.get("Rank").and_then(|s| s.parse::<u32>().ok());

        let manufacturer = Self::read_text(fields.get("Manufacturer").map_or("", String::as_str));
        let part_number = Self::read_text(fields.get("Part Number").map_or("", String::as_str));
        let serial_number = Self::read_text(fields.get("Serial Number").map_or("", String::as_str));
        let populated = if slot_empty {
            Some(false)
        } else if capacity_bytes.is_some() || !part_number.is_empty() {
            Some(true)
        } else {
            None
        };

        // Only the configured voltage is the operating voltage. "Minimum Voltage"
        // is the lowest the module is rated to accept, a specification, and it
        // used to stand in here when the configured figure was absent.
        let voltage = fields
            .get("Configured Voltage")
            .and_then(|s| {
                s.split_whitespace()
                    .next()
                    .and_then(|v| v.parse::<f64>().ok())
            })
            .map(|v| if v > 10.0 { v / 1000.0 } else { v }) // mV to V
            // SMBIOS Type 17 defines zero in these fields as "unknown", so a
            // parsed zero is an absence rather than a reading. `profile/memory`
            // already knew this and filtered on it downstream.
            .filter(|v| *v > 0.0);

        Some(DimmInfo {
            locator,
            bank,
            capacity_bytes,
            speed_mts,
            configured_speed_mts,
            memory_type,
            form_factor,
            data_width_bits: data_width,
            total_width_bits: total_width,
            ranks: rank,
            manufacturer,
            part_number,
            serial_number,
            populated,
            voltage,
        })
    }

    /// A firmware text field as read: trimmed, or `""` where it is empty or
    /// names a placeholder rather than a value. A placeholder is not a part
    /// number, a serial or a manufacturer, and is no evidence of a module.
    fn read_text(s: &str) -> String {
        let t = s.trim();
        let placeholder = [
            "not specified",
            "unknown",
            "none",
            "[empty]",
            "no dimm",
            "to be filled by o.e.m.",
            "undefined",
        ]
        .contains(&t.to_ascii_lowercase().as_str());
        if placeholder {
            String::new()
        } else {
            t.to_string()
        }
    }

    /// Bytes in a size string such as `16 GB`, or `None` where it does not
    /// parse. An unrecognised unit used to be read as bytes, which made
    /// `16 GiB` a 16-byte module.
    fn parse_size_to_bytes(s: &str) -> Option<u64> {
        let parts: Vec<&str> = s.split_whitespace().collect();
        if parts.len() < 2 {
            return None;
        }
        let value: u64 = parts[0].parse().ok()?;
        let multiplier: u64 = match parts[1].to_uppercase().as_str() {
            "KB" | "KIB" => 1 << 10,
            "MB" | "MIB" => 1 << 20,
            "GB" | "GIB" => 1 << 30,
            "TB" | "TIB" => 1 << 40,
            _ => return None,
        };
        value.checked_mul(multiplier).filter(|&b| b > 0)
    }

    /// The leading number of a speed string, or `None` if there is none.
    ///
    /// SMBIOS Type 17 uses `0` for "unknown" in its speed fields, so a parsed
    /// zero is treated as absent too, the same rule `voltage` already follows.
    fn parse_mts(s: &str) -> Option<u32> {
        s.split_whitespace()
            .next()
            .and_then(|v| v.parse::<u32>().ok())
            .filter(|v| *v > 0)
    }

    fn parse_memory_type(s: &str) -> MemoryType {
        let upper = s.to_uppercase();
        if upper.contains("LPDDR5X") {
            MemoryType::LPDDR5X
        } else if upper.contains("LPDDR5") {
            MemoryType::LPDDR5
        } else if upper.contains("LPDDR4X") {
            MemoryType::LPDDR4X
        } else if upper.contains("LPDDR4") {
            MemoryType::LPDDR4
        } else if upper.contains("DDR5") {
            MemoryType::DDR5
        } else if upper.contains("DDR4") {
            MemoryType::DDR4
        } else if upper.contains("DDR3") {
            MemoryType::DDR3
        } else if upper.contains("DDR2") {
            MemoryType::DDR2
        } else if upper.contains("HBM3E") {
            MemoryType::HBM3E
        } else if upper.contains("HBM3") {
            MemoryType::HBM3
        } else if upper.contains("HBM2E") {
            MemoryType::HBM2E
        } else if upper.contains("HBM2") {
            MemoryType::HBM2
        } else {
            MemoryType::Unknown
        }
    }

    fn parse_form_factor(s: &str) -> FormFactor {
        let upper = s.to_uppercase();
        if upper.contains("SODIMM") || upper.contains("SO-DIMM") {
            FormFactor::SODIMM
        } else if upper.contains("LRDIMM") {
            FormFactor::LRDIMM
        } else if upper.contains("RDIMM") {
            FormFactor::RDIMM
        } else if upper.contains("NVDIMM") {
            FormFactor::NVDIMM
        } else if upper.contains("DIMM") {
            FormFactor::DIMM
        } else {
            FormFactor::Unknown
        }
    }

    #[allow(dead_code)]
    fn parse_windows_wmi(text: &str) -> Result<Vec<DimmInfo>, IronError> {
        // Parse JSON array from PowerShell
        let trimmed = text.trim();
        if trimmed.is_empty() {
            return Ok(Vec::new());
        }

        // An array, or one object when a single module is installed. Anything
        // else is an error. An empty list would read as "no memory modules
        // here", and a failed parse used to become a module with no fields.
        let items: Vec<serde_json::Value> = match serde_json::from_str(trimmed) {
            Ok(serde_json::Value::Array(items)) => items,
            Ok(obj @ serde_json::Value::Object(_)) => vec![obj],
            Ok(_) => {
                return Err(IronError::Parse(
                    "Win32_PhysicalMemory output is neither an array nor an object".into(),
                ))
            }
            Err(e) => {
                return Err(IronError::Parse(format!(
                    "Win32_PhysicalMemory output is not JSON: {e}"
                )))
            }
        };

        let dimms: Vec<DimmInfo> = items
            .iter()
            .map(|item| {
                let capacity = item["Capacity"]
                    .as_u64()
                    .or_else(|| item["Capacity"].as_str().and_then(|s| s.parse().ok()))
                    .filter(|&c| c > 0);
                // WMI uses 0 for "unknown" here as SMBIOS does, so a zero is
                // absent too. `ConfiguredClockSpeed` falling back to `Speed`
                // asserted the DIMM runs at its rating.
                let speed = item["Speed"].as_u64().filter(|v| *v > 0).map(|v| v as u32);
                let conf_speed = item["ConfiguredClockSpeed"]
                    .as_u64()
                    .filter(|v| *v > 0)
                    .map(|v| v as u32);
                // A zero width is no width. Kept, it made a module with unread
                // widths answer "no ECC" (equal zeros).
                let data_width = item["DataWidth"]
                    .as_u64()
                    .filter(|w| *w > 0)
                    .map(|w| w as u32);
                let total_width = item["TotalWidth"]
                    .as_u64()
                    .filter(|w| *w > 0)
                    .map(|w| w as u32);

                let smbios_type = item["SMBIOSMemoryType"].as_u64().unwrap_or(0);
                let memory_type = match smbios_type {
                    20 => MemoryType::DDR,
                    21 => MemoryType::DDR2,
                    24 => MemoryType::DDR3,
                    26 => MemoryType::DDR4,
                    34 => MemoryType::DDR5,
                    _ => MemoryType::Unknown,
                };

                let ff_val = item["FormFactor"].as_u64().unwrap_or(0);
                let form_factor = match ff_val {
                    8 => FormFactor::DIMM,
                    12 => FormFactor::SODIMM,
                    _ => FormFactor::Unknown,
                };

                DimmInfo {
                    locator: item["DeviceLocator"].as_str().unwrap_or("").to_string(),
                    bank: item["BankLabel"].as_str().unwrap_or("").to_string(),
                    capacity_bytes: capacity,
                    speed_mts: speed,
                    configured_speed_mts: conf_speed,
                    memory_type,
                    form_factor,
                    data_width_bits: data_width,
                    total_width_bits: total_width,
                    // Win32_PhysicalMemory has no rank field. This was `1`
                    // beside a comment saying so.
                    ranks: None,
                    manufacturer: Self::read_text(item["Manufacturer"].as_str().unwrap_or("")),
                    part_number: Self::read_text(item["PartNumber"].as_str().unwrap_or("")),
                    serial_number: Self::read_text(item["SerialNumber"].as_str().unwrap_or("")),
                    // `Win32_PhysicalMemory` lists installed modules only, so
                    // the row is the evidence. This was `capacity > 0`, which
                    // reported a module with an unreadable `Capacity` as an
                    // empty slot.
                    populated: Some(true),
                    // `ConfiguredVoltage` is in millivolts. A zero there means
                    // the firmware filled the field with nothing, which is not
                    // an operating voltage of zero.
                    voltage: item["ConfiguredVoltage"]
                        .as_u64()
                        .filter(|mv| *mv > 0)
                        .map(|mv| mv as f64 / 1000.0),
                }
            })
            .collect();
        Ok(dimms)
    }

    #[allow(dead_code)]
    fn parse_macos_profiler(text: &str) -> Result<Vec<DimmInfo>, IronError> {
        // macOS system_profiler SPMemoryDataType -json
        let root: serde_json::Value = serde_json::from_str(text)
            .map_err(|e| IronError::Parse(format!("system_profiler output is not JSON: {e}")))?;

        let mut dimms = Vec::new();
        if let Some(items) = root["SPMemoryDataType"].as_array() {
            for item in items {
                // Apple silicon lists no slots. Its one item is the memory in
                // the SoC package, with the size under the data type's own key
                // and the type and maker beside it. Read as no modules, the
                // machine's whole unified memory went unreported.
                if item.get("_items").is_none()
                    && (item.get("dimm_type").is_some() || item.get("SPMemoryDataType").is_some())
                {
                    let size_str = item["SPMemoryDataType"].as_str().unwrap_or("");
                    let capacity_bytes = Self::parse_size_to_bytes(size_str);
                    let type_str = item["dimm_type"].as_str().unwrap_or("Unknown");
                    dimms.push(DimmInfo {
                        locator: "SoC package".to_string(),
                        bank: String::new(),
                        capacity_bytes,
                        // `system_profiler` gives no speed for on-package memory.
                        speed_mts: None,
                        configured_speed_mts: None,
                        memory_type: Self::parse_memory_type(type_str),
                        form_factor: FormFactor::OnPackage,
                        data_width_bits: None,
                        total_width_bits: None,
                        ranks: None,
                        manufacturer: Self::read_text(
                            item["dimm_manufacturer"].as_str().unwrap_or(""),
                        ),
                        part_number: String::new(),
                        serial_number: String::new(),
                        // The item describes installed memory; there is no
                        // empty package to report.
                        populated: Some(true),
                        voltage: None,
                    });
                    continue;
                }
                if let Some(slots) = item["_items"].as_array() {
                    for slot in slots {
                        let size_str = slot["dimm_size"].as_str().unwrap_or("");
                        let capacity_bytes = Self::parse_size_to_bytes(size_str);
                        // `dimm_status` says "empty" or "ok" where it is
                        // present, and "Empty" appears as the size of an empty
                        // slot. A size that parsed is a module. Anything else
                        // establishes nothing.
                        let status = slot["dimm_status"].as_str().unwrap_or("");
                        let populated = if status.eq_ignore_ascii_case("empty")
                            || size_str.eq_ignore_ascii_case("empty")
                        {
                            Some(false)
                        } else if status.eq_ignore_ascii_case("ok") || capacity_bytes.is_some() {
                            Some(true)
                        } else {
                            None
                        };
                        let speed_mts = slot["dimm_speed"].as_str().and_then(Self::parse_mts);
                        let type_str = slot["dimm_type"].as_str().unwrap_or("Unknown");

                        dimms.push(DimmInfo {
                            locator: slot["_name"].as_str().unwrap_or("").to_string(),
                            bank: String::new(),
                            capacity_bytes,
                            speed_mts,
                            // system_profiler reports no configured speed. This
                            // copied the rated one, asserting every Mac's
                            // memory runs at its rating.
                            configured_speed_mts: None,
                            memory_type: Self::parse_memory_type(type_str),
                            form_factor: FormFactor::Unknown,
                            // system_profiler reports neither width, and
                            // 64/64 asserted "no ECC" on every Mac.
                            data_width_bits: None,
                            total_width_bits: None,
                            // system_profiler reports no rank count.
                            ranks: None,
                            manufacturer: Self::read_text(
                                slot["dimm_manufacturer"].as_str().unwrap_or(""),
                            ),
                            part_number: Self::read_text(
                                slot["dimm_part_number"].as_str().unwrap_or(""),
                            ),
                            serial_number: Self::read_text(
                                slot["dimm_serial_number"].as_str().unwrap_or(""),
                            ),
                            populated,
                            // `system_profiler` reports no DIMM voltage.
                            voltage: None,
                        });
                    }
                }
            }
        } else {
            return Err(IronError::Parse(
                "system_profiler output has no SPMemoryDataType array".into(),
            ));
        }

        Ok(dimms)
    }
}

// DDR variant used only for Windows SMBIOS type 20
#[allow(dead_code)]
impl MemoryType {
    const DDR: MemoryType = MemoryType::Unknown; // DDR1 is too old to specifically handle
}

/// A tool's stderr as one line. dmidecode writes one message per line, and
/// the error text ships to readers as a single note.
#[cfg_attr(
    not(any(target_os = "linux", windows, target_os = "macos")),
    allow(dead_code)
)]
fn one_line(stderr: &[u8]) -> String {
    String::from_utf8_lossy(stderr)
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join("; ")
}

#[cfg(test)]
mod tests {
    use super::one_line;

    #[test]
    fn tool_stderr_becomes_one_line() {
        assert_eq!(
            one_line(
                b"smbios_entry_point: Permission denied
Can't read memory from /dev/mem
"
            ),
            "smbios_entry_point: Permission denied; Can't read memory from /dev/mem"
        );
    }

    use super::*;

    #[test]
    fn test_dimm_capacity_gib() {
        let dimm = DimmInfo {
            locator: "DIMM_A1".into(),
            bank: "BANK 0".into(),
            capacity_bytes: Some(16 * 1024 * 1024 * 1024),
            speed_mts: Some(3200),
            configured_speed_mts: Some(3200),
            memory_type: MemoryType::DDR4,
            form_factor: FormFactor::DIMM,
            data_width_bits: Some(64),
            total_width_bits: Some(64),
            ranks: Some(2),
            manufacturer: "Samsung".into(),
            part_number: "M378A2G43AB3-CWE".into(),
            serial_number: "12345678".into(),
            populated: Some(true),
            voltage: Some(1.2),
        };
        assert!((dimm.capacity_gib().unwrap() - 16.0).abs() < 0.01);
        assert_eq!(dimm.is_ecc(), Some(false));
    }

    /// A DIMM whose widths were not read has no ECC answer.
    ///
    /// ECC is inferred from the total width exceeding the data width. The
    /// readers defaulted `data_width` to 64 and `total_width` to whatever
    /// `data_width` became — and macOS hardcoded both to 64 — so equal widths
    /// reported **no ECC** for any DIMM nothing had measured.
    ///
    /// The ontology guarded this with `> 0`, under a comment that named the
    /// danger exactly ("Two zeros are equal, and would otherwise report 'no
    /// ECC'"), and the guard never fired because the sentinel was 64.
    #[test]
    fn unread_widths_give_no_ecc_answer() {
        let mut dimm = DimmInfo {
            locator: "DIMM_A1".into(),
            bank: String::new(),
            capacity_bytes: None,
            speed_mts: Some(0),
            configured_speed_mts: Some(0),
            memory_type: MemoryType::Unknown,
            form_factor: FormFactor::Unknown,
            data_width_bits: None,
            total_width_bits: None,
            ranks: Some(1),
            manufacturer: String::new(),
            part_number: String::new(),
            serial_number: String::new(),
            populated: Some(true),
            voltage: None,
        };
        assert_eq!(dimm.is_ecc(), None, "neither width read");

        dimm.data_width_bits = Some(64);
        assert_eq!(dimm.is_ecc(), None, "only one width read");

        dimm.total_width_bits = Some(72);
        assert_eq!(dimm.is_ecc(), Some(true), "72 carrying 64 is ECC");

        dimm.total_width_bits = Some(64);
        assert_eq!(dimm.is_ecc(), Some(false), "equal widths, both read");
    }

    #[test]
    fn test_ecc_detection() {
        let dimm = DimmInfo {
            locator: "DIMM_A1".into(),
            bank: "".into(),
            capacity_bytes: Some(32 * 1024 * 1024 * 1024),
            speed_mts: Some(3200),
            configured_speed_mts: Some(3200),
            memory_type: MemoryType::DDR4,
            form_factor: FormFactor::RDIMM,
            data_width_bits: Some(64),
            total_width_bits: Some(72),
            ranks: Some(2),
            manufacturer: "SK Hynix".into(),
            part_number: "".into(),
            serial_number: "".into(),
            populated: Some(true),
            voltage: Some(1.2),
        };
        assert_eq!(dimm.is_ecc(), Some(true));
    }

    #[test]
    fn test_bandwidth_estimation() {
        // DDR4-3200 dual-channel: 3200 × 8 × 2 / 1000 = 51.2 GB/s
        let bw = MemoryTopologyMonitor::estimate_bandwidth(3200, 2);
        assert!((bw - 51.2).abs() < 0.1);

        // DDR5-5600 dual-channel: 5600 × 8 × 2 / 1000 = 89.6 GB/s
        let bw5 = MemoryTopologyMonitor::estimate_bandwidth(5600, 2);
        assert!((bw5 - 89.6).abs() < 0.1);
    }

    #[test]
    fn test_memory_type_parsing() {
        assert_eq!(
            MemoryTopologyMonitor::parse_memory_type("DDR4"),
            MemoryType::DDR4
        );
        assert_eq!(
            MemoryTopologyMonitor::parse_memory_type("LPDDR5X"),
            MemoryType::LPDDR5X
        );
        assert_eq!(
            MemoryTopologyMonitor::parse_memory_type("DDR5"),
            MemoryType::DDR5
        );
    }

    #[test]
    fn test_analysis_dual_channel() {
        let dimms = vec![
            DimmInfo {
                locator: "DIMM_A1".into(),
                bank: "BANK 0".into(),
                capacity_bytes: Some(8 * 1024 * 1024 * 1024),
                speed_mts: Some(3200),
                configured_speed_mts: Some(3200),
                memory_type: MemoryType::DDR4,
                form_factor: FormFactor::DIMM,
                data_width_bits: Some(64),
                total_width_bits: Some(64),
                ranks: Some(1),
                manufacturer: "Samsung".into(),
                part_number: "".into(),
                serial_number: "".into(),
                populated: Some(true),
                voltage: Some(1.2),
            },
            DimmInfo {
                locator: "DIMM_B1".into(),
                bank: "BANK 1".into(),
                capacity_bytes: Some(8 * 1024 * 1024 * 1024),
                speed_mts: Some(3200),
                configured_speed_mts: Some(3200),
                memory_type: MemoryType::DDR4,
                form_factor: FormFactor::DIMM,
                data_width_bits: Some(64),
                total_width_bits: Some(64),
                ranks: Some(1),
                manufacturer: "Samsung".into(),
                part_number: "".into(),
                serial_number: "".into(),
                populated: Some(true),
                voltage: Some(1.2),
            },
        ];
        let analysis = MemoryTopologyMonitor::analyze(&dimms);
        assert_eq!(analysis.populated_slots, 2);
        assert_eq!(analysis.dual_channel, Some(true));
        assert_eq!(analysis.matched_speeds, Some(true));
        assert_eq!(analysis.matched_capacities, Some(true));
        assert!(
            analysis.efficiency_score.is_some(),
            "two modules were read in full"
        );
        assert!(
            analysis
                .estimated_bandwidth_gbs
                .expect("both DIMM speeds were read")
                > 40.0
        );
    }

    fn analysed_dimm(locator: &str, capacity: Option<u64>, speed: Option<u32>) -> DimmInfo {
        DimmInfo {
            locator: locator.into(),
            bank: String::new(),
            capacity_bytes: capacity,
            speed_mts: speed,
            configured_speed_mts: None,
            memory_type: MemoryType::DDR4,
            form_factor: FormFactor::DIMM,
            data_width_bits: Some(64),
            total_width_bits: Some(64),
            ranks: Some(1),
            manufacturer: String::new(),
            part_number: String::new(),
            serial_number: String::new(),
            populated: Some(true),
            voltage: None,
        }
    }

    /// One module is nothing to score or match, and a total with an unread
    /// size is not a total.
    #[test]
    fn efficiency_and_totals_need_the_inputs_they_weigh() {
        let one = [analysed_dimm("DIMM_A1", Some(8 << 30), Some(3200))];
        let analysis = MemoryTopologyMonitor::analyze(&one);
        assert_eq!(analysis.populated_slots, 1);
        assert_eq!(analysis.total_capacity_bytes, Some(8 << 30));
        assert_eq!(
            analysis.matched_speeds, None,
            "one speed is nothing to match"
        );
        assert_eq!(
            analysis.matched_capacities, None,
            "one size is nothing to match"
        );
        assert_eq!(analysis.efficiency_score, None);

        let unread = [
            analysed_dimm("DIMM_A1", Some(8 << 30), Some(3200)),
            analysed_dimm("DIMM_B1", None, Some(3200)),
        ];
        let analysis = MemoryTopologyMonitor::analyze(&unread);
        assert_eq!(analysis.total_capacity_bytes, None, "a size was not read");
        assert_eq!(analysis.matched_capacities, None);
        assert_eq!(analysis.efficiency_score, None);
        assert_eq!(analysis.max_capacity_bytes, None);
    }

    /// An unreadable size is not an empty slot.
    ///
    /// macOS derived `populated` from `capacity > 0`, so a module whose
    /// `dimm_size` did not parse was reported as an empty slot. Presence now
    /// comes from the status field or a size that parsed, and neither here
    /// means unknown.
    #[test]
    fn macos_unreadable_size_is_unknown_presence_not_an_empty_slot() {
        let json = r#"{"SPMemoryDataType":[{"_items":[
            {"_name":"DIMM0","dimm_size":"16 GB","dimm_status":"ok"},
            {"_name":"DIMM1","dimm_size":"sixteen gigs"},
            {"_name":"DIMM2","dimm_size":"Empty","dimm_status":"empty"}
        ]}]}"#;
        let dimms =
            MemoryTopologyMonitor::parse_macos_profiler(json).expect("system_profiler JSON parses");
        assert_eq!(dimms.len(), 3);
        assert_eq!(dimms[0].populated, Some(true));
        assert_eq!(dimms[0].capacity_bytes, Some(16 * 1024 * 1024 * 1024));
        assert_eq!(
            dimms[1].populated, None,
            "an unparsed size is not a reading of absence"
        );
        assert_eq!(dimms[1].capacity_bytes, None);
        assert_eq!(dimms[2].populated, Some(false));
        assert_eq!(dimms[2].capacity_bytes, None);
    }

    /// Apple silicon's `system_profiler` lists no slots, only the memory in the
    /// package. That is one on-package module, not none, and it establishes no
    /// slot or channel count.
    #[test]
    fn apple_silicon_unified_memory_is_one_on_package_module() {
        let json = r#"{"SPMemoryDataType":[{
            "SPMemoryDataType":"16 GB","dimm_manufacturer":"Hynix","dimm_type":"LPDDR5"
        }]}"#;
        let dimms =
            MemoryTopologyMonitor::parse_macos_profiler(json).expect("system_profiler JSON parses");
        assert_eq!(dimms.len(), 1);
        let unified = &dimms[0];
        assert_eq!(unified.form_factor, FormFactor::OnPackage);
        assert_eq!(unified.capacity_bytes, Some(16 * 1024 * 1024 * 1024));
        assert_eq!(unified.memory_type, MemoryType::LPDDR5);
        assert_eq!(unified.manufacturer, "Hynix");
        assert_eq!(unified.populated, Some(true));
        assert_eq!(unified.speed_mts, None);

        let analysis = MemoryTopologyMonitor::analyze(&dimms);
        assert_eq!(analysis.total_capacity_bytes, Some(16 * 1024 * 1024 * 1024));
        assert_eq!(analysis.total_slots, None, "a package is not a slot");
        assert_eq!(
            analysis.channel_count, None,
            "one row says nothing of channels"
        );
        assert_eq!(analysis.dual_channel, None);
        assert_eq!(analysis.efficiency_score, None);
    }

    /// SMBIOS "Unknown" is not "No Module Installed", and a real part number is
    /// evidence of a module even when the size did not read.
    #[test]
    fn linux_presence_comes_from_evidence_not_from_the_size() {
        let fields = |size: &str, part: &str| -> HashMap<String, String> {
            [
                ("Locator".to_string(), "DIMM_A1".to_string()),
                ("Size".to_string(), size.to_string()),
                ("Part Number".to_string(), part.to_string()),
            ]
            .into_iter()
            .collect()
        };
        let d = |size, part| MemoryTopologyMonitor::dimm_from_fields(&fields(size, part)).unwrap();

        let empty = d("No Module Installed", "Not Specified");
        assert_eq!((empty.populated, empty.capacity_bytes), (Some(false), None));

        let sized = d("32 GB", "Not Specified");
        assert_eq!(sized.populated, Some(true));
        assert_eq!(sized.capacity_bytes, Some(32 * 1024 * 1024 * 1024));

        let unknown_size_real_part = d("Unknown", "F5-6000J3038F16G");
        assert_eq!(unknown_size_real_part.populated, Some(true));
        assert_eq!(unknown_size_real_part.capacity_bytes, None);

        // "Unknown" used to count as an empty slot.
        let nothing_known = d("Unknown", "Not Specified");
        assert_eq!(nothing_known.populated, None);
    }

    /// No enumerated module is unknown, not zero, and "no ECC" needs every
    /// populated module's widths to have been read.
    #[test]
    fn no_enumerated_modules_is_unknown_not_zero() {
        let none = MemoryTopologyMonitor::analyze(&[]);
        assert_eq!(none.total_capacity_bytes, None);
        assert_eq!(none.total_slots, None);
        assert_eq!(none.ecc_active, None);

        let known = [analysed_dimm("DIMM_A1", Some(8 << 30), Some(3200))];
        assert_eq!(
            MemoryTopologyMonitor::analyze(&known).ecc_active,
            Some(false)
        );

        let mut unread = analysed_dimm("DIMM_A1", Some(8 << 30), Some(3200));
        unread.data_width_bits = None;
        unread.total_width_bits = None;
        assert_eq!(MemoryTopologyMonitor::analyze(&[unread]).ecc_active, None);
    }

    /// Output that does not parse is an error, not an empty list. The Windows
    /// reader turned a `{` it could not parse into a module with every field
    /// unset and `populated: Some(true)`.
    #[test]
    fn unparseable_profiler_output_is_an_error_not_an_empty_list() {
        assert!(MemoryTopologyMonitor::parse_windows_wmi("not json").is_err());
        assert!(MemoryTopologyMonitor::parse_windows_wmi("{ truncated").is_err());
        assert!(MemoryTopologyMonitor::parse_windows_wmi("42").is_err());
        assert!(MemoryTopologyMonitor::parse_windows_wmi("")
            .unwrap()
            .is_empty());
        assert!(MemoryTopologyMonitor::parse_macos_profiler("not json").is_err());
        assert!(
            MemoryTopologyMonitor::parse_macos_profiler(r#"{"SPHardwareDataType":[]}"#).is_err()
        );
    }

    #[test]
    fn size_with_an_unrecognised_unit_is_unread() {
        assert_eq!(
            MemoryTopologyMonitor::parse_size_to_bytes("16 GB"),
            Some(16 << 30)
        );
        assert_eq!(
            MemoryTopologyMonitor::parse_size_to_bytes("16 GiB"),
            Some(16 << 30)
        );
        assert_eq!(
            MemoryTopologyMonitor::parse_size_to_bytes("16 furlongs"),
            None
        );
    }

    /// Two system-memory arrays add up. Ex is preferred where set, MaxCapacity
    /// covers an array with Ex at zero, and a non-system array is not counted.
    #[test]
    fn windows_board_maximum_sums_the_system_arrays_in_kilobytes() {
        let json = r#"[
            {"MaxCapacityEx": 0, "MaxCapacity": 33554432, "Use": 3},
            {"MaxCapacityEx": 33554432, "MaxCapacity": 2147483648, "Use": 3},
            {"MaxCapacityEx": 1024, "MaxCapacity": 1024, "Use": 4}
        ]"#;
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity(json),
            Some(64 << 30)
        );
    }

    /// `ConvertTo-Json` writes one object, not an array, for a single array.
    #[test]
    fn windows_board_maximum_accepts_a_single_object() {
        let json = r#"{"MaxCapacityEx": null, "MaxCapacity": 16777216, "Use": 3}"#;
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity(json),
            Some(16 << 30)
        );
    }

    /// 0x80000000 in MaxCapacity means "see MaxCapacityEx". Without Ex it is
    /// no capacity, and a system array with no usable capacity leaves the sum
    /// short, so both are unknown rather than a figure.
    #[test]
    fn windows_board_maximum_unknown_when_no_capacity_is_usable() {
        let sentinel = r#"[{"MaxCapacity": 2147483648, "Use": 3}]"#;
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity(sentinel),
            None
        );
        let missing = r#"[{"Use": 3}, {"MaxCapacityEx": 1048576, "Use": 3}]"#;
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity(missing),
            None
        );
        let no_system = r#"[{"MaxCapacity": 1024, "Use": 4}]"#;
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity(no_system),
            None
        );
        assert_eq!(MemoryTopologyMonitor::parse_windows_max_capacity(""), None);
        assert_eq!(
            MemoryTopologyMonitor::parse_windows_max_capacity("not json"),
            None
        );
    }

    /// Realistic `dmidecode -t 16` output. The video array is not system
    /// memory, so it is not counted.
    #[test]
    fn dmidecode_board_maximum_sums_the_system_arrays() {
        let text = "# dmidecode 3.5\n\
Getting SMBIOS data from sysfs.\n\
SMBIOS 3.4.0 present.\n\
\n\
Handle 0x1000, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tLocation: System Board Or Motherboard\n\
\tUse: System Memory\n\
\tError Correction Type: Multi-bit ECC\n\
\tMaximum Capacity: 128 GB\n\
\tError Information Handle: Not Provided\n\
\tNumber Of Devices: 4\n\
\n\
Handle 0x1005, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tLocation: Other\n\
\tUse: Video Memory\n\
\tMaximum Capacity: 1 GB\n\
\tNumber Of Devices: 1\n";
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(text),
            Some(128 << 30)
        );
    }

    /// Two system arrays are summed. An unparsed capacity, a missing Use line
    /// or no system array at all is unknown.
    #[test]
    fn dmidecode_board_maximum_unknown_when_a_record_is_unreadable() {
        let two = "Handle 0x1000, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tUse: System Memory\n\
\tMaximum Capacity: 64 GB\n\
\n\
Handle 0x1001, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tUse: System Memory\n\
\tMaximum Capacity: 64 GB\n";
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(two),
            Some(128 << 30)
        );
        let not_specified = "Handle 0x1000, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tUse: System Memory\n\
\tMaximum Capacity: Not Specified\n";
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(not_specified),
            None
        );
        let no_use = "Handle 0x1000, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tMaximum Capacity: 64 GB\n";
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(no_use),
            None
        );
        let video_only = "Handle 0x1000, DMI type 16, 23 bytes\n\
Physical Memory Array\n\
\tUse: Video Memory\n\
\tMaximum Capacity: 1 GB\n";
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(video_only),
            None
        );
        assert_eq!(
            MemoryTopologyMonitor::parse_dmidecode_max_capacity(""),
            None
        );
    }

    /// The configured voltage is the operating voltage. The rated minimum is a
    /// specification and is not published in its place.
    #[test]
    fn voltage_is_the_configured_voltage_and_never_the_minimum() {
        let fields = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
            pairs
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect()
        };
        let only_minimum = fields(&[
            ("Locator", "DIMM_A1"),
            ("Size", "16 GB"),
            ("Minimum Voltage", "1.2 V"),
        ]);
        let dimm = MemoryTopologyMonitor::dimm_from_fields(&only_minimum).unwrap();
        assert_eq!(dimm.voltage, None, "a minimum is not an operating voltage");

        let configured = fields(&[
            ("Locator", "DIMM_A1"),
            ("Size", "16 GB"),
            ("Minimum Voltage", "1.2 V"),
            ("Configured Voltage", "1.35 V"),
        ]);
        let dimm = MemoryTopologyMonitor::dimm_from_fields(&configured).unwrap();
        assert_eq!(dimm.voltage, Some(1.35));
    }

    /// WMI's zero width is no width, so no ECC answer is given for it.
    #[test]
    fn zero_widths_from_wmi_are_unread_not_equal_widths() {
        let unread = MemoryTopologyMonitor::parse_windows_wmi(
            r#"{"Capacity": 17179869184, "DataWidth": 0, "TotalWidth": 0}"#,
        )
        .unwrap();
        assert_eq!(unread[0].data_width_bits, None);
        assert_eq!(unread[0].is_ecc(), None);

        let ecc = MemoryTopologyMonitor::parse_windows_wmi(
            r#"[{"Capacity": 17179869184, "DataWidth": 64, "TotalWidth": 72}]"#,
        )
        .unwrap();
        assert_eq!(ecc[0].is_ecc(), Some(true));
    }

    #[test]
    fn test_serialization() {
        let analysis = MemoryAnalysis {
            total_capacity_bytes: Some(32 * 1024 * 1024 * 1024),
            max_capacity_bytes: None,
            populated_slots: 2,
            total_slots: Some(4),
            dual_channel: Some(true),
            quad_channel: Some(false),
            matched_speeds: Some(true),
            matched_capacities: Some(true),
            ecc_active: Some(false),
            estimated_bandwidth_gbs: Some(51.2),
            channel_count: Some(2),
            recommendations: vec!["2 empty DIMM slot(s) available for expansion".into()],
            efficiency_score: Some(85),
        };
        let json = serde_json::to_string(&analysis).unwrap();
        assert!(json.contains("dual_channel"));
        let _: MemoryAnalysis = serde_json::from_str(&json).unwrap();
    }
}