ironmonitor 7.0.2

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
//! 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,
    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::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 (typically 64).
    /// Data width in bits, where it was read. See [`Self::is_ecc`].
    pub data_width_bits: Option<u32>,
    /// Total width in bits (72 = ECC, 64 = non-ECC).
    /// 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.
    pub total_capacity_bytes: u64,
    /// Maximum supported capacity in bytes (from array info).
    pub max_capacity_bytes: u64,
    /// Number of populated slots.
    pub populated_slots: usize,
    /// Total number of slots.
    pub total_slots: usize,
    /// Whether running in dual-channel mode (inferred from slot population).
    pub dual_channel: bool,
    /// Whether running in quad-channel mode.
    pub quad_channel: bool,
    /// Whether all DIMMs are the same speed.
    pub matched_speeds: bool,
    /// Whether all DIMMs are the same capacity (optimal for interleaving).
    pub matched_capacities: bool,
    /// Whether ECC is active.
    pub ecc_active: 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.
    pub channel_count: u32,
    /// Upgrade recommendations.
    pub recommendations: Vec<String>,
    /// Efficiency score 0-100 (how well the memory is configured).
    pub efficiency_score: 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 {
    /// Create a new memory topology monitor.
    pub fn new() -> Result<Self, IronError> {
        let dimms = Self::enumerate_dimms()?;
        let analysis = Self::analyze(&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::analyze(&self.topology.dimms);
        Ok(())
    }

    /// 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; a module whose size was not is left
        // out rather than counted as zero.
        let total_capacity: u64 = populated.iter().filter_map(|d| d.capacity_bytes).sum();
        let populated_count = populated.len();
        let total_slots = dimms.len();

        // Check matched speeds and capacities
        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.windows(2).all(|w| w[0] == w[1]) || speeds.len() <= 1;
        let matched_capacities =
            capacities.windows(2).all(|w| w[0] == w[1]) || capacities.len() <= 1;

        // ECC detection. `any` over `Option` must ask for `Some(true)`: a DIMM
        // whose widths were not read is not a DIMM known to lack ECC.
        let ecc_active = populated.iter().any(|d| d.is_ecc() == Some(true));

        // Channel inference from locator naming patterns
        let channel_count = Self::infer_channels(&populated);
        let dual_channel = channel_count >= 2;
        let quad_channel = channel_count >= 4;

        // Bandwidth estimation
        // No speed read on any DIMM 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 = speeds
            .iter()
            .copied()
            .max()
            .map(|max_speed| Self::estimate_bandwidth(max_speed, channel_count));

        // Max capacity: assume 2x current or 128GB per slot, whichever is more reasonable
        let max_per_slot: u64 = if populated
            .iter()
            .any(|d| matches!(d.memory_type, MemoryType::DDR5))
        {
            64 * 1024 * 1024 * 1024 // 64 GB per slot for DDR5
        } else {
            32 * 1024 * 1024 * 1024 // 32 GB per slot for DDR4
        };
        let max_capacity_bytes = total_slots as u64 * max_per_slot;

        // Recommendations
        let mut recommendations = Vec::new();
        let efficiency = Self::compute_efficiency(
            &populated,
            total_slots,
            matched_speeds,
            matched_capacities,
            dual_channel,
            &mut recommendations,
        );

        MemoryAnalysis {
            total_capacity_bytes: total_capacity,
            max_capacity_bytes,
            populated_slots: populated_count,
            total_slots,
            dual_channel,
            quad_channel,
            matched_speeds,
            matched_capacities,
            ecc_active,
            estimated_bandwidth_gbs,
            channel_count,
            recommendations,
            efficiency_score: efficiency,
        }
    }

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

        // 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() {
            // Fallback: infer from populated count
            match populated.len() {
                1 => 1,
                2 => 2,
                3 => 2, // likely 2-channel with one extra
                4 => 2, // commonly dual-channel with 2 DIMMs each
                6 => 3, // triple channel
                8 => 4, // quad channel
                _ => 2, // default assumption
            }
        } else {
            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: usize,
        matched_speeds: bool,
        matched_capacities: bool,
        dual_channel: bool,
        recommendations: &mut Vec<String>,
    ) -> u32 {
        let mut score: i32 = 70; // Base score

        if populated.is_empty() {
            return 0;
        }

        // Dual-channel bonus
        if dual_channel {
            score += 10;
        } else if total_slots >= 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
        let empty = total_slots - 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
    }

    #[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))
            }
            _ => {
                // Fallback: /proc/meminfo for total only
                Ok(Vec::new())
            }
        }
    }

    #[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);
                Ok(Self::parse_windows_wmi(&text))
            }
            _ => Ok(Vec::new()),
        }
    }

    #[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);
                Ok(Self::parse_macos_profiler(&text))
            }
            _ => Ok(Vec::new()),
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn enumerate_dimms() -> Result<Vec<DimmInfo>, IronError> {
        Ok(Vec::new())
    }

    #[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 {
            Some(Self::parse_size_to_bytes(&size_str)).filter(|&b| b > 0)
        };

        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 = fields.get("Manufacturer").cloned().unwrap_or_default();
        let part_number = fields.get("Part Number").cloned().unwrap_or_default();
        let serial_number = fields.get("Serial Number").cloned().unwrap_or_default();
        let populated = if slot_empty {
            Some(false)
        } else if capacity_bytes.is_some() || Self::names_a_part(&part_number) {
            Some(true)
        } else {
            None
        };

        let voltage = fields
            .get("Configured Voltage")
            .or(fields.get("Minimum 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,
        })
    }

    /// Whether a SMBIOS part-number field names a part rather than a
    /// placeholder, which is evidence that a module is present.
    fn names_a_part(part: &str) -> bool {
        let p = part.trim();
        !p.is_empty()
            && !["not specified", "unknown", "none", "[empty]", "no dimm"]
                .contains(&p.to_ascii_lowercase().as_str())
    }

    fn parse_size_to_bytes(s: &str) -> u64 {
        let parts: Vec<&str> = s.split_whitespace().collect();
        if parts.len() < 2 {
            return 0;
        }
        let value: u64 = parts[0].parse().unwrap_or(0);
        match parts[1].to_uppercase().as_str() {
            "KB" => value * 1024,
            "MB" => value * 1024 * 1024,
            "GB" => value * 1024 * 1024 * 1024,
            "TB" => value * 1024 * 1024 * 1024 * 1024,
            _ => value,
        }
    }

    /// 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) -> Vec<DimmInfo> {
        // Parse JSON array from PowerShell
        let trimmed = text.trim();
        if trimmed.is_empty() {
            return Vec::new();
        }

        // Try to parse as JSON array or single object
        let items: Vec<serde_json::Value> = if trimmed.starts_with('[') {
            serde_json::from_str(trimmed).unwrap_or_default()
        } else if trimmed.starts_with('{') {
            vec![serde_json::from_str(trimmed).unwrap_or_default()]
        } else {
            Vec::new()
        };

        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);
                let data_width = item["DataWidth"].as_u64().map(|w| w as u32);
                let total_width = item["TotalWidth"].as_u64().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: item["Manufacturer"]
                        .as_str()
                        .unwrap_or("")
                        .trim()
                        .to_string(),
                    part_number: item["PartNumber"].as_str().unwrap_or("").trim().to_string(),
                    serial_number: item["SerialNumber"]
                        .as_str()
                        .unwrap_or("")
                        .trim()
                        .to_string(),
                    // `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()
    }

    #[allow(dead_code)]
    fn parse_macos_profiler(text: &str) -> Vec<DimmInfo> {
        // macOS system_profiler SPMemoryDataType -json
        let root: serde_json::Value = match serde_json::from_str(text) {
            Ok(v) => v,
            Err(_) => return Vec::new(),
        };

        let mut dimms = Vec::new();
        if let Some(items) = root["SPMemoryDataType"].as_array() {
            for item in items {
                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 =
                            Some(Self::parse_size_to_bytes(size_str)).filter(|&b| b > 0);
                        // `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: slot["dimm_manufacturer"]
                                .as_str()
                                .unwrap_or("")
                                .to_string(),
                            part_number: slot["dimm_part_number"]
                                .as_str()
                                .unwrap_or("")
                                .to_string(),
                            serial_number: slot["dimm_serial_number"]
                                .as_str()
                                .unwrap_or("")
                                .to_string(),
                            populated,
                            // `system_profiler` reports no DIMM voltage.
                            voltage: None,
                        });
                    }
                }
            }
        }

        dimms
    }
}

impl Default for MemoryTopologyMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            topology: MemoryTopology {
                dimms: Vec::new(),
                analysis: MemoryAnalysis {
                    total_capacity_bytes: 0,
                    max_capacity_bytes: 0,
                    populated_slots: 0,
                    total_slots: 0,
                    dual_channel: false,
                    quad_channel: false,
                    matched_speeds: true,
                    matched_capacities: true,
                    ecc_active: false,
                    estimated_bandwidth_gbs: None,
                    channel_count: 0,
                    recommendations: Vec::new(),
                    efficiency_score: 0,
                },
            },
        })
    }
}

// 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
}

#[cfg(test)]
mod tests {
    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!(analysis.dual_channel);
        assert!(analysis.matched_speeds);
        assert!(analysis.matched_capacities);
        assert!(
            analysis
                .estimated_bandwidth_gbs
                .expect("both DIMM speeds were read")
                > 40.0
        );
    }

    /// 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);
        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);
    }

    /// 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);
    }

    #[test]
    fn test_monitor_default() {
        let monitor = MemoryTopologyMonitor::default();
        let _topo = monitor.topology();
    }

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