retch-sysinfo 0.1.27

System information gathering library for retch
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
// SPDX-FileCopyrightText: 2026 Ken Tobias
// SPDX-License-Identifier: GPL-3.0-or-later

//! Physical memory (RAM) slot detection — type, speed, and capacity.

pub fn detect_physical_memory() -> Option<String> {
    #[cfg(target_os = "linux")]
    return detect_linux();

    #[cfg(target_os = "macos")]
    return detect_macos();

    #[cfg(target_os = "windows")]
    return detect_windows();

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    return None;
}

/// Represents one DIMM slot as parsed from DMI type-17 output.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
#[derive(Debug, PartialEq)]
pub struct DimmSlot {
    pub size_mb: u64,
    pub mem_type: String,
    pub speed_mt: Option<u64>,
}

/// Parses `dmidecode --type 17` text output into a list of populated DIMM slots.
#[cfg(target_os = "linux")]
pub fn parse_dmidecode_type17(output: &str) -> Vec<DimmSlot> {
    let mut slots = Vec::new();
    let mut size_mb: Option<u64> = None;
    let mut mem_type = String::new();
    let mut speed_mt: Option<u64> = None;

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

        if trimmed == "Memory Device" {
            // Flush previous slot
            if let Some(mb) = size_mb.take() {
                if mb > 0 {
                    slots.push(DimmSlot {
                        size_mb: mb,
                        mem_type: mem_type.clone(),
                        speed_mt,
                    });
                }
            }
            mem_type.clear();
            speed_mt = None;
        } else if let Some(rest) = trimmed.strip_prefix("Size:") {
            let rest = rest.trim();
            if rest.contains("No Module") || rest == "Unknown" {
                size_mb = Some(0);
            } else if let Some(n) = rest
                .strip_suffix(" GiB")
                .or_else(|| rest.strip_suffix(" GB"))
            {
                size_mb = n.trim().parse::<u64>().ok().map(|g| g * 1024);
            } else if let Some(n) = rest
                .strip_suffix(" MiB")
                .or_else(|| rest.strip_suffix(" MB"))
            {
                size_mb = n.trim().parse::<u64>().ok();
            }
        } else if let Some(rest) = trimmed.strip_prefix("Type:") {
            let t = rest.trim();
            if t != "Unknown" && !t.is_empty() {
                mem_type = t.to_string();
            }
        } else if let Some(rest) = trimmed.strip_prefix("Speed:") {
            // e.g. "4800 MT/s" or "Unknown"
            let rest = rest.trim();
            if let Some(mt_str) = rest.strip_suffix(" MT/s") {
                speed_mt = mt_str.trim().parse::<u64>().ok();
            }
        }
    }

    // Flush last slot
    if let Some(mb) = size_mb {
        if mb > 0 {
            slots.push(DimmSlot {
                size_mb: mb,
                mem_type,
                speed_mt,
            });
        }
    }

    slots
}

/// Formats a list of DIMM slots into a human-readable summary string.
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
pub fn format_dimm_slots(slots: &[DimmSlot]) -> Option<String> {
    if slots.is_empty() {
        return None;
    }

    // Group identical slots (same size + type + speed)
    #[derive(PartialEq, Eq, Hash)]
    struct Key {
        size_mb: u64,
        mem_type: String,
        speed_mt: Option<u64>,
    }

    let mut groups: Vec<(Key, usize)> = Vec::new();
    for slot in slots {
        let key = Key {
            size_mb: slot.size_mb,
            mem_type: slot.mem_type.clone(),
            speed_mt: slot.speed_mt,
        };
        if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
            entry.1 += 1;
        } else {
            groups.push((key, 1));
        }
    }

    let parts: Vec<String> = groups
        .iter()
        .map(|(key, count)| {
            let size_str = if key.size_mb >= 1024 {
                format!("{} GB", key.size_mb / 1024)
            } else {
                format!("{} MB", key.size_mb)
            };

            let mut s = if *count > 1 {
                format!("{}× {}", count, size_str)
            } else {
                size_str
            };

            if !key.mem_type.is_empty() {
                s.push(' ');
                s.push_str(&key.mem_type);
            }

            if let Some(mt) = key.speed_mt {
                s.push_str(&format!(" {} MT/s", mt));
            }

            s
        })
        .collect();

    Some(parts.join(", "))
}

#[cfg(target_os = "linux")]
fn detect_linux() -> Option<String> {
    // Try name-only first (works when /usr/bin is in PATH), then known absolute paths.
    let candidates = ["dmidecode", "/usr/bin/dmidecode", "/usr/sbin/dmidecode"];
    for cmd in candidates {
        let Ok(output) = std::process::Command::new(cmd)
            .args(["--type", "17"])
            .output()
        else {
            continue;
        };
        if !output.status.success() {
            continue;
        }
        let text = String::from_utf8_lossy(&output.stdout);
        let slots = parse_dmidecode_type17(&text);
        return format_dimm_slots(&slots);
    }
    None
}

#[cfg(target_os = "macos")]
fn detect_macos() -> Option<String> {
    let output = std::process::Command::new("system_profiler")
        .args(["SPMemoryDataType", "-detailLevel", "basic"])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let text = String::from_utf8_lossy(&output.stdout);
    parse_system_profiler_memory(&text)
}

/// Parses `system_profiler SPMemoryDataType` text output into a summary string.
#[cfg(target_os = "macos")]
pub fn parse_system_profiler_memory(text: &str) -> Option<String> {
    // Example output:
    //   Memory:
    //     Type: LPDDR5
    //     Speed: 6400 MT/s
    //     Manufacturers: SK Hynix
    //     Size: 16 GB
    // Or for multi-slot Macs:
    //   BANK 0/DIMM0:
    //     Size: 16 GB
    //     Type: DDR5
    //     Speed: 4800 MT/s

    let mut slots: Vec<DimmSlot> = Vec::new();
    let mut current_size_mb: Option<u64> = None;
    let mut current_type = String::new();
    let mut current_speed: Option<u64> = None;
    let mut in_slot = false;

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

        // Slot/bank header (indented section headers ending with ':')
        if (trimmed.contains("DIMM") || trimmed.contains("BANK") || trimmed.contains("Slot"))
            && trimmed.ends_with(':')
        {
            if in_slot {
                if let Some(mb) = current_size_mb.take() {
                    if mb > 0 {
                        slots.push(DimmSlot {
                            size_mb: mb,
                            mem_type: current_type.clone(),
                            speed_mt: current_speed,
                        });
                    }
                }
                current_type.clear();
                current_speed = None;
            }
            in_slot = true;
            continue;
        }

        // "Size:" is used on physical Macs; VMs report the total as "Memory:" instead
        let size_rest = trimmed.strip_prefix("Size:").or_else(|| {
            trimmed
                .strip_prefix("Memory:")
                .filter(|s| !s.trim().is_empty())
        });
        if let Some(rest) = size_rest {
            let rest = rest.trim();
            if rest.contains("Empty") || rest == "Unknown" {
                current_size_mb = Some(0);
            } else if let Some(gb_str) = rest.strip_suffix(" GB") {
                current_size_mb = gb_str.trim().parse::<u64>().ok().map(|g| g * 1024);
            } else if let Some(mb_str) = rest.strip_suffix(" MB") {
                current_size_mb = mb_str.trim().parse::<u64>().ok();
            }
        } else if let Some(rest) = trimmed.strip_prefix("Type:") {
            let t = rest.trim();
            if t != "Unknown" && !t.is_empty() {
                current_type = t.to_string();
            }
        } else if let Some(rest) = trimmed.strip_prefix("Speed:") {
            let rest = rest.trim();
            if let Some(mt_str) = rest.strip_suffix(" MT/s") {
                current_speed = mt_str.trim().parse::<u64>().ok();
            } else if let Some(mhz_str) = rest.strip_suffix(" MHz") {
                // Older Macs report MHz
                current_speed = mhz_str.trim().parse::<u64>().ok().map(|mhz| mhz * 2);
            }
        }
    }

    // Flush last slot
    if let Some(mb) = current_size_mb {
        if mb > 0 {
            slots.push(DimmSlot {
                size_mb: mb,
                mem_type: current_type,
                speed_mt: current_speed,
            });
        }
    }

    // Apple Silicon unified memory: system_profiler often reports a single "Size" at the top level
    // without slot headers — we'll have one slot from the flush above.

    format_dimm_slots(&slots)
}

#[cfg(target_os = "windows")]
fn detect_windows() -> Option<String> {
    let cmd = "Get-CimInstance Win32_PhysicalMemory | \
               Select-Object Capacity,SMBIOSMemoryType,Speed | \
               ConvertTo-Csv -NoTypeInformation";
    if let Ok(output) = std::process::Command::new("powershell")
        .args(["-NoProfile", "-NonInteractive", "-Command", cmd])
        .output()
    {
        if output.status.success() {
            let text = String::from_utf8_lossy(&output.stdout);
            if let Some(result) = parse_win32_physical_memory(&text) {
                return Some(result);
            }
        }
    }

    // Hyper-V and other VMs don't expose DIMM rows in Win32_PhysicalMemory.
    // Fall back to the total from Win32_ComputerSystem so the field still appears.
    let fb_cmd = "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory";
    let Ok(fb) = std::process::Command::new("powershell")
        .args(["-NoProfile", "-NonInteractive", "-Command", fb_cmd])
        .output()
    else {
        return None;
    };
    if !fb.status.success() {
        return None;
    }
    let total_bytes: u64 = String::from_utf8_lossy(&fb.stdout).trim().parse().ok()?;
    if total_bytes == 0 {
        return None;
    }
    let gb = total_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
    Some(format!("{:.0} GB (VM — DIMM info unavailable)", gb))
}

/// Parses `Get-CimInstance Win32_PhysicalMemory | ConvertTo-Csv` output.
///
/// Expected CSV header: `"Capacity","SMBIOSMemoryType","Speed"`
/// Speed is in MT/s (Win32 already uses the transfer-rate value, e.g. 3200 for DDR4-3200).
#[cfg(target_os = "windows")]
pub fn parse_win32_physical_memory(csv: &str) -> Option<String> {
    let mut lines = csv.lines();
    lines.next(); // skip header
    let mut slots = Vec::new();
    for line in lines {
        let fields = unquoted_csv_fields(line);
        if fields.len() < 3 {
            continue;
        }
        let capacity_bytes: u64 = fields[0].trim().parse().unwrap_or(0);
        if capacity_bytes == 0 {
            continue;
        }
        let size_mb = capacity_bytes / (1024 * 1024);
        let type_code: u16 = fields[1].trim().parse().unwrap_or(0);
        let speed_mt: u64 = fields[2].trim().parse().unwrap_or(0);
        slots.push(DimmSlot {
            size_mb,
            mem_type: smbios_memory_type(type_code),
            speed_mt: if speed_mt > 0 { Some(speed_mt) } else { None },
        });
    }
    format_dimm_slots(&slots)
}

/// Maps SMBIOS memory type codes (from `Win32_PhysicalMemory.SMBIOSMemoryType`) to strings.
#[cfg(target_os = "windows")]
fn smbios_memory_type(code: u16) -> String {
    match code {
        20 => "DDR".to_string(),
        21 => "DDR2".to_string(),
        24 => "DDR3".to_string(),
        26 => "DDR4".to_string(),
        27 => "LPDDR".to_string(),
        28 => "LPDDR2".to_string(),
        29 => "LPDDR3".to_string(),
        30 => "LPDDR4".to_string(),
        34 => "DDR5".to_string(),
        35 => "LPDDR5".to_string(),
        _ => String::new(),
    }
}

/// Splits one PowerShell `ConvertTo-Csv` line into unquoted fields.
///
/// `ConvertTo-Csv` wraps every value in double quotes: `"val1","val2",...`
#[cfg(target_os = "windows")]
fn unquoted_csv_fields(line: &str) -> Vec<String> {
    let line = line.trim().trim_matches('"');
    line.split("\",\"").map(|s| s.to_string()).collect()
}

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

    #[cfg(target_os = "linux")]
    #[test]
    fn test_parse_dmidecode_two_slots() {
        let input = r#"
Memory Device
        Size: 8 GB
        Type: DDR5
        Speed: 4800 MT/s

Memory Device
        Size: 8 GB
        Type: DDR5
        Speed: 4800 MT/s
"#;
        let slots = parse_dmidecode_type17(input);
        assert_eq!(slots.len(), 2);
        assert_eq!(slots[0].size_mb, 8192);
        assert_eq!(slots[0].mem_type, "DDR5");
        assert_eq!(slots[0].speed_mt, Some(4800));

        let summary = format_dimm_slots(&slots).unwrap();
        assert_eq!(summary, "2× 8 GB DDR5 4800 MT/s");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_parse_dmidecode_gib_units() {
        // dmidecode reports GiB on some systems (e.g. LPDDR5 laptops)
        let input = r#"
Memory Device
    Size: 2 GiB
    Type: LPDDR5
    Speed: 6400 MT/s

Memory Device
    Size: 2 GiB
    Type: LPDDR5
    Speed: 6400 MT/s
"#;
        let slots = parse_dmidecode_type17(input);
        assert_eq!(slots.len(), 2);
        assert_eq!(slots[0].size_mb, 2048);
        assert_eq!(slots[0].mem_type, "LPDDR5");
        assert_eq!(slots[0].speed_mt, Some(6400));

        let summary = format_dimm_slots(&slots).unwrap();
        assert_eq!(summary, "2× 2 GB LPDDR5 6400 MT/s");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_parse_dmidecode_empty_slot() {
        let input = r#"
Memory Device
        Size: No Module Installed
        Type: Unknown

Memory Device
        Size: 16 GB
        Type: DDR4
        Speed: 3200 MT/s
"#;
        let slots = parse_dmidecode_type17(input);
        assert_eq!(slots.len(), 1);
        assert_eq!(slots[0].size_mb, 16384);
        let summary = format_dimm_slots(&slots).unwrap();
        assert_eq!(summary, "16 GB DDR4 3200 MT/s");
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_parse_dmidecode_mixed_sizes() {
        let input = r#"
Memory Device
        Size: 16 GB
        Type: DDR5
        Speed: 5600 MT/s

Memory Device
        Size: 32 GB
        Type: DDR5
        Speed: 5600 MT/s
"#;
        let slots = parse_dmidecode_type17(input);
        assert_eq!(slots.len(), 2);
        let summary = format_dimm_slots(&slots).unwrap();
        // Two different sizes → two groups
        assert!(summary.contains("16 GB DDR5 5600 MT/s"));
        assert!(summary.contains("32 GB DDR5 5600 MT/s"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_parse_system_profiler_apple_silicon() {
        let input = r#"
Memory:

      Type: LPDDR5
      Speed: 6400 MT/s
      Size: 16 GB
"#;
        let result = parse_system_profiler_memory(input);
        assert_eq!(result, Some("16 GB LPDDR5 6400 MT/s".to_string()));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_parse_system_profiler_multi_slot() {
        let input = r#"
Memory:

    BANK 0/DIMM0:

      Size: 16 GB
      Type: DDR5
      Speed: 4800 MT/s

    BANK 1/DIMM0:

      Size: 16 GB
      Type: DDR5
      Speed: 4800 MT/s
"#;
        let result = parse_system_profiler_memory(input);
        assert_eq!(result, Some("2× 16 GB DDR5 4800 MT/s".to_string()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_parse_win32_physical_memory_ddr4() {
        let csv = r#""Capacity","SMBIOSMemoryType","Speed"
"8589934592","26","3200"
"8589934592","26","3200"
"#;
        let result = parse_win32_physical_memory(csv);
        assert_eq!(result, Some("2× 8 GB DDR4 3200 MT/s".to_string()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_parse_win32_physical_memory_ddr5() {
        let csv = r#""Capacity","SMBIOSMemoryType","Speed"
"17179869184","34","4800"
"17179869184","34","4800"
"#;
        let result = parse_win32_physical_memory(csv);
        assert_eq!(result, Some("2× 16 GB DDR5 4800 MT/s".to_string()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_parse_win32_physical_memory_unknown_type() {
        // SMBIOSMemoryType=0 → no type label emitted
        let csv = r#""Capacity","SMBIOSMemoryType","Speed"
"34359738368","0","0"
"#;
        let result = parse_win32_physical_memory(csv);
        assert_eq!(result, Some("32 GB".to_string()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn test_parse_win32_physical_memory_mixed_slots() {
        let csv = r#""Capacity","SMBIOSMemoryType","Speed"
"8589934592","26","3200"
"16777216","26","3200"
"#;
        // 8 GB + 16 MB (different sizes → two groups)
        let result = parse_win32_physical_memory(csv);
        let s = result.unwrap();
        assert!(s.contains("8 GB DDR4 3200 MT/s"));
        assert!(s.contains("16 MB DDR4 3200 MT/s"));
    }
}