retch-sysinfo 0.1.49

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
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
// SPDX-FileCopyrightText: 2026 Ken Tobias
// SPDX-License-Identifier: GPL-3.0-or-later

//! GPU detection and identification.
//!
//! Handles parsing PCI IDs and querying the system for graphics card
//! vendor and model information.

#[cfg(not(any(target_os = "macos", target_os = "windows")))]
use std::collections::HashSet;
use std::fs;

/// Information about a detected GPU.
#[derive(Debug, Clone, Default)]
pub struct GpuInfo {
    /// The marketing or model name of the GPU.
    pub name: String,
    /// Total VRAM in bytes, if detected.
    pub vram_bytes: Option<u64>,
}

impl GpuInfo {
    /// Formats the GPU name and VRAM into a human-readable string.
    pub fn format(&self) -> String {
        if let Some(vram) = self.vram_bytes {
            let vram_gb = vram as f64 / 1024.0 / 1024.0 / 1024.0;
            if vram_gb >= 1.0 {
                format!("{} ({:.0} GB)", self.name, vram_gb)
            } else {
                let vram_mb = vram / 1024 / 1024;
                format!("{} ({} MB)", self.name, vram_mb)
            }
        } else {
            self.name.clone()
        }
    }
}

/// Refines AMD GPU names by mapping codenames to marketing names.
///
/// Fallback only: on Linux, [`lookup_amdgpu_ids`] is consulted first — it resolves the
/// exact marketing name from the device *and revision*, which this table cannot (e.g.
/// Strix Halo `1586` is an 8040S, 8050S, or 8060S depending on revision).
///
/// Matching is first-substring-wins, so more specific codenames MUST come before their
/// prefixes: "Strix Halo" before "Strix" (a `1586` "Strix Halo [...]" pci.ids name once
/// matched the "Strix" entry and was mislabeled as the Strix Point 880M/890M).
pub fn improve_amd_gpu_name(name: &str) -> String {
    let codenames = [
        ("Phoenix1", "Radeon 780M"),
        ("Phoenix2", "Radeon 740M / 760M"),
        ("Renoir", "Radeon Graphics (Renoir)"),
        ("Lucienne", "Radeon Graphics (Lucienne)"),
        ("Cezanne", "Radeon Graphics (Cezanne)"),
        ("Barcelo", "Radeon Graphics (Barcelo)"),
        ("Rembrandt", "Radeon 680M"),
        ("Raphael", "Radeon Graphics (Raphael)"),
        ("Mendocino", "Radeon 610M"),
        ("Strix Halo", "Radeon 8050S / 8060S"),
        ("Strix", "Radeon 880M / 890M"),
        ("Krackan", "Radeon 840M / 860M"),
    ];

    for (codename, marketing) in codenames {
        if name.contains(codename) {
            return marketing.to_string();
        }
    }

    name.to_string()
}

/// Looks up an AMD GPU's exact marketing name in libdrm's `amdgpu.ids` database content.
///
/// The database is keyed by *(device id, revision id)*, which is what disambiguates
/// same-device variants that pci.ids lumps together (Strix Halo `1586` rev `C1` is the
/// "AMD Radeon 8060S Graphics", rev `C2` the 8050S, rev `D5` the 8040S). This mirrors how
/// fastfetch resolves AMD names on Linux.
///
/// Format (after `#` comments and a bare version line): `device_id,\trevision_id,\tname`.
/// IDs are bare uppercase hex; sysfs-style `0x`-prefixed lowercase input is accepted.
/// Malformed lines are skipped. The name is the remainder after the second comma, so
/// commas in product names are safe.
pub fn lookup_amdgpu_ids_in(content: &str, device_id: &str, revision_id: &str) -> Option<String> {
    let device_id = device_id.trim().trim_start_matches("0x");
    let revision_id = revision_id.trim().trim_start_matches("0x");

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.splitn(3, ',');
        let (Some(dev), Some(rev), Some(name)) = (parts.next(), parts.next(), parts.next()) else {
            continue; // version line or malformed
        };
        if dev.trim().eq_ignore_ascii_case(device_id)
            && rev.trim().eq_ignore_ascii_case(revision_id)
        {
            let name = name.trim();
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Reads libdrm's `amdgpu.ids` and resolves the exact AMD marketing name, if present.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn lookup_amdgpu_ids(device_id: &str, revision_id: &str) -> Option<String> {
    let content = fs::read_to_string("/usr/share/libdrm/amdgpu.ids").ok()?;
    lookup_amdgpu_ids_in(&content, device_id, revision_id)
}

/// Helper to lookup PCI device name in standard system pci.ids files.
pub fn lookup_pci_device(vendor_id: &str, device_id: &str) -> Option<String> {
    let vendor_id = vendor_id.trim_start_matches("0x").to_lowercase();
    let device_id = device_id.trim_start_matches("0x").to_lowercase();

    let paths = ["/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids"];

    for path in &paths {
        if let Ok(content) = fs::read_to_string(path) {
            let mut in_vendor = false;
            for line in content.lines() {
                if line.starts_with('#') || line.is_empty() {
                    continue;
                }

                if !line.starts_with('\t') {
                    // Vendor line: "vendor_id  Vendor Name"
                    in_vendor = line.starts_with(&vendor_id);
                } else if in_vendor && line.starts_with('\t') && !line.starts_with("\t\t") {
                    // Device line: "\tdevice_id  Device Name"
                    let trimmed = line.trim_start();
                    if let Some(stripped) = trimmed.strip_prefix(&device_id) {
                        let name = stripped.trim();
                        return Some(name.to_string());
                    }
                }
            }
        }
    }
    None
}

/// Parses VRAM string (e.g. "8 GB", "1536 MB") into bytes.
pub fn parse_vram_str(s: &str) -> Option<u64> {
    let parts: Vec<&str> = s.split_whitespace().collect();
    if parts.len() >= 2 {
        if let Ok(val) = parts[0].parse::<f64>() {
            let unit = parts[1].to_uppercase();
            if unit.starts_with("GB") {
                return Some((val * 1024.0 * 1024.0 * 1024.0) as u64);
            } else if unit.starts_with("MB") {
                return Some((val * 1024.0 * 1024.0) as u64);
            } else if unit.starts_with("KB") {
                return Some((val * 1024.0) as u64);
            }
        }
    }
    None
}

/// Parses the output of `system_profiler SPDisplaysDataType` on macOS.
pub fn parse_system_profiler_displays(stdout: &str) -> Vec<GpuInfo> {
    let mut gpus = Vec::new();
    let mut current_gpu = None;
    for line in stdout.lines() {
        let trimmed = line.trim();
        if let Some(stripped) = trimmed.strip_prefix("Chipset Model:") {
            if let Some(gpu) = current_gpu.take() {
                gpus.push(gpu);
            }
            let name = stripped.trim().to_string();
            current_gpu = Some(GpuInfo {
                name,
                vram_bytes: None,
            });
        } else if let Some(stripped) = trimmed.strip_prefix("VRAM (Total):") {
            if let Some(ref mut gpu) = current_gpu {
                let vram_str = stripped.trim();
                gpu.vram_bytes = parse_vram_str(vram_str);
            }
        } else if let Some(stripped) = trimmed.strip_prefix("VRAM (Dynamic, Max):") {
            if let Some(ref mut gpu) = current_gpu {
                let vram_str = stripped.trim();
                gpu.vram_bytes = parse_vram_str(vram_str);
            }
        } else if trimmed.starts_with("Displays:") {
            if let Some(gpu) = current_gpu.take() {
                gpus.push(gpu);
            }
        }
    }
    if let Some(gpu) = current_gpu {
        gpus.push(gpu);
    }
    gpus
}

/// Parses the output of `wmic path win32_VideoController` or PowerShell CIM query for GPU information.
pub fn parse_wmi_videocontroller(output: &str) -> Vec<GpuInfo> {
    let mut gpus = Vec::new();
    let mut name = String::new();
    let mut vram = None;

    for line in output.lines() {
        let trimmed = line.trim();
        let parts: Vec<&str> = if trimmed.contains('=') {
            trimmed.splitn(2, '=').collect()
        } else if trimmed.contains(':') {
            trimmed.splitn(2, ':').collect()
        } else {
            continue;
        };

        if parts.len() == 2 {
            let key = parts[0].trim().to_lowercase();
            let val = parts[1].trim();

            if key == "name" {
                if !name.is_empty() {
                    gpus.push(GpuInfo {
                        name: name.clone(),
                        vram_bytes: vram,
                    });
                    vram = None;
                }
                name = val.to_string();
            } else if key == "adapterram" {
                if vram.is_some() && !name.is_empty() {
                    gpus.push(GpuInfo {
                        name: name.clone(),
                        vram_bytes: vram,
                    });
                    name = String::new();
                    vram = None;
                }
                if let Ok(bytes) = val.parse::<u64>() {
                    vram = Some(bytes);
                }
            }
        }
    }

    if !name.is_empty() {
        gpus.push(GpuInfo {
            name,
            vram_bytes: vram,
        });
    }

    gpus
}

/// Detects GPUs using system APIs or profiles.
pub fn detect_gpus() -> Vec<GpuInfo> {
    #[cfg(target_os = "macos")]
    {
        crate::macos_ffi::get_gpus()
            .into_iter()
            .map(|(name, vram_bytes)| GpuInfo { name, vram_bytes })
            .collect()
    }

    #[cfg(target_os = "windows")]
    {
        // Read GPU info from the display adapter device class in the registry.
        // HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\<NNNN>
        // Each numbered subkey represents one adapter.
        use crate::win_reg;
        const ADAPTER_CLASS: &str =
            "SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}";

        let mut gpus = Vec::new();
        for subkey_name in win_reg::enum_reg_subkeys(win_reg::HKEY_LOCAL_MACHINE, ADAPTER_CLASS) {
            // Skip the "Properties" subkey and any non-numeric entries
            if subkey_name.eq_ignore_ascii_case("Properties") {
                continue;
            }
            let subkey = format!("{}\\{}", ADAPTER_CLASS, subkey_name);
            let name = win_reg::get_reg_string(win_reg::HKEY_LOCAL_MACHINE, &subkey, "DriverDesc")
                .unwrap_or_default();
            if name.is_empty() {
                continue;
            }
            // VRAM is stored as REG_BINARY (little-endian u64) in HardwareInformation.MemorySize
            let vram_bytes = win_reg::get_reg_binary(
                win_reg::HKEY_LOCAL_MACHINE,
                &subkey,
                "HardwareInformation.MemorySize",
            )
            .and_then(|b| {
                if b.len() >= 8 {
                    Some(u64::from_le_bytes(b[..8].try_into().ok()?))
                } else if b.len() >= 4 {
                    Some(u32::from_le_bytes(b[..4].try_into().ok()?) as u64)
                } else {
                    None
                }
            })
            .filter(|&v| v > 0);
            gpus.push(GpuInfo {
                name: name.clone(),
                vram_bytes,
            });
        }

        if gpus.is_empty() {
            eprintln!("warning: GPU detection failed on Windows (registry adapter class returned no results)");
        }

        gpus
    }

    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    {
        let mut gpus = Vec::new();
        let mut seen_devices = HashSet::new();

        // Scan /sys/class/drm for all card* and renderD* entries
        if let Ok(entries) = std::fs::read_dir("/sys/class/drm") {
            for entry in entries.flatten() {
                let name = entry.file_name().into_string().unwrap_or_default();
                if !name.starts_with("card") && !name.starts_with("renderD") {
                    continue;
                }

                let device_path = entry.path().join("device");
                if let Ok(real_path) = std::fs::canonicalize(&device_path) {
                    if !seen_devices.insert(real_path) {
                        continue;
                    }

                    // Try to identify vendor and model
                    let vendor_id = fs::read_to_string(device_path.join("vendor"))
                        .unwrap_or_default()
                        .trim()
                        .to_string();
                    let device_id = fs::read_to_string(device_path.join("device"))
                        .unwrap_or_default()
                        .trim()
                        .to_string();

                    if vendor_id.is_empty() || device_id.is_empty() {
                        continue;
                    }

                    // AMD: prefer libdrm's amdgpu.ids, keyed by device + revision — the
                    // only source that separates same-device variants (8040S/8050S/8060S).
                    // pci.ids + the codename table remain the fallback.
                    let amdgpu_ids_name = if vendor_id.contains("1002") {
                        fs::read_to_string(device_path.join("revision"))
                            .ok()
                            .and_then(|rev| lookup_amdgpu_ids(&device_id, rev.trim()))
                    } else {
                        None
                    };

                    let mut gpu_name = amdgpu_ids_name.unwrap_or_else(|| {
                        let mut name =
                            lookup_pci_device(&vendor_id, &device_id).unwrap_or_else(|| {
                                if vendor_id.contains("10de") {
                                    "NVIDIA GPU".to_string()
                                } else if vendor_id.contains("1002") {
                                    "AMD GPU".to_string()
                                } else if vendor_id.contains("8086") {
                                    "Intel GPU".to_string()
                                } else {
                                    "Unknown GPU".to_string()
                                }
                            });
                        // Refine AMD GPU names (codename table fallback)
                        if vendor_id.contains("1002") {
                            name = improve_amd_gpu_name(&name);
                        }
                        name
                    });

                    // NVIDIA special case: try /proc for even better name
                    if vendor_id.contains("10de") {
                        if let Ok(pci_slot_path) = fs::read_link(&device_path) {
                            if let Some(slot_name) = pci_slot_path.file_name() {
                                let proc_info_path = format!(
                                    "/proc/driver/nvidia/gpus/{}/information",
                                    slot_name.to_string_lossy()
                                );
                                if let Ok(info) = fs::read_to_string(proc_info_path) {
                                    for line in info.lines() {
                                        if line.starts_with("Model:") {
                                            gpu_name =
                                                line.replace("Model:", "").trim().to_string();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    let mut vram_bytes = None;
                    // Try to get VRAM from common sysfs locations (mainly AMD)
                    let vram_path = device_path.join("mem_info_vram_total");
                    if let Ok(vram_str) = fs::read_to_string(vram_path) {
                        if let Ok(v) = vram_str.trim().parse::<u64>() {
                            vram_bytes = Some(v);
                        }
                    }

                    gpus.push(GpuInfo {
                        name: gpu_name,
                        vram_bytes,
                    });
                }
            }
        }

        if gpus.is_empty() {
            // Fallback for non-standard setups or if /sys/class/drm is empty
            if let Ok(model) = fs::read_to_string("/sys/class/drm/card0/device/model") {
                let model = model.trim();
                if !model.is_empty() {
                    gpus.push(GpuInfo {
                        name: model.to_string(),
                        vram_bytes: None,
                    });
                }
            }
        }

        gpus
    }
}

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

    #[test]
    fn test_gpu_info_format() {
        let info = GpuInfo {
            name: "NVIDIA GeForce RTX 4090".to_string(),
            vram_bytes: Some(24 * 1024 * 1024 * 1024),
        };
        assert_eq!(info.format(), "NVIDIA GeForce RTX 4090 (24 GB)");

        let info = GpuInfo {
            name: "Intel Arc A770".to_string(),
            vram_bytes: Some(16 * 1024 * 1024 * 1024),
        };
        assert_eq!(info.format(), "Intel Arc A770 (16 GB)");

        let info = GpuInfo {
            name: "Radeon 780M".to_string(),
            vram_bytes: Some(512 * 1024 * 1024),
        };
        assert_eq!(info.format(), "Radeon 780M (512 MB)");

        let info = GpuInfo {
            name: "Generic GPU".to_string(),
            vram_bytes: None,
        };
        assert_eq!(info.format(), "Generic GPU");
    }

    #[test]
    fn test_improve_amd_gpu_name() {
        assert_eq!(
            improve_amd_gpu_name("AMD Radeon Phoenix1 Graphics"),
            "Radeon 780M"
        );
        assert_eq!(improve_amd_gpu_name("AMD Rembrandt"), "Radeon 680M");
        assert_eq!(improve_amd_gpu_name("Unknown GPU"), "Unknown GPU");
    }

    #[test]
    fn test_improve_amd_gpu_name_strix_halo_before_strix() {
        // Regression: "Strix Halo" (8050S/8060S) must not be swallowed by the "Strix"
        // (Strix Point, 880M/890M) substring — first-substring-wins makes order load-bearing.
        assert_eq!(
            improve_amd_gpu_name(
                "Strix Halo [Radeon Graphics / Radeon 8050S Graphics / Radeon 8060S Graphics]"
            ),
            "Radeon 8050S / 8060S"
        );
        assert_eq!(
            improve_amd_gpu_name("Strix [Radeon 880M / 890M]"),
            "Radeon 880M / 890M"
        );
        assert_eq!(
            improve_amd_gpu_name("Krackan [Radeon 840M / 860M Graphics]"),
            "Radeon 840M / 860M"
        );
    }

    // Shape of /usr/share/libdrm/amdgpu.ids: comments, a bare version line, then
    // "device_id,\trevision_id,\tname" rows (bare uppercase hex ids).
    const AMDGPU_IDS_FIXTURE: &str = "\
# List of AMDGPU IDs
#
# Syntax:
# device_id,\trevision_id,\tproduct_name        <-- single tab after comma

1.0.0
1114,\tC2,\tAMD Radeon 860M Graphics
1586,\tC1,\tAMD Radeon 8060S Graphics
1586,\tC2,\tAMD Radeon 8050S Graphics
1586,\tD5,\tAMD Radeon 8040S Graphics
15DD,\tC3,\tAMD Radeon(TM) Vega 8 Graphics
garbage line without commas
731F,\tC1,\tAMD Radeon RX 5700 XT
";

    #[test]
    fn test_lookup_amdgpu_ids_revision_disambiguates() {
        // The same device id resolves to different products by revision — the reason this
        // source is preferred over pci.ids (which lumps all 1586 variants together).
        assert_eq!(
            lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "1586", "C1"),
            Some("AMD Radeon 8060S Graphics".to_string())
        );
        assert_eq!(
            lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "1586", "C2"),
            Some("AMD Radeon 8050S Graphics".to_string())
        );
        assert_eq!(
            lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "1586", "D5"),
            Some("AMD Radeon 8040S Graphics".to_string())
        );
    }

    #[test]
    fn test_lookup_amdgpu_ids_accepts_sysfs_style_ids() {
        // sysfs reports "0x1586" / "0xc1"; the database stores "1586" / "C1".
        assert_eq!(
            lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "0x1586", "0xc1"),
            Some("AMD Radeon 8060S Graphics".to_string())
        );
    }

    #[test]
    fn test_lookup_amdgpu_ids_no_match_and_junk_lines() {
        // Unknown device or revision → None (caller falls back to pci.ids); comments,
        // the version line, and malformed rows must not match or panic.
        assert_eq!(lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "9999", "C1"), None);
        assert_eq!(lookup_amdgpu_ids_in(AMDGPU_IDS_FIXTURE, "1586", "FF"), None);
        assert_eq!(lookup_amdgpu_ids_in("", "1586", "C1"), None);
    }

    #[test]
    fn test_parse_vram_str() {
        assert_eq!(parse_vram_str("8 GB"), Some(8 * 1024 * 1024 * 1024));
        assert_eq!(parse_vram_str("1536 MB"), Some(1536 * 1024 * 1024));
        assert_eq!(parse_vram_str("512 MB"), Some(512 * 1024 * 1024));
        assert_eq!(parse_vram_str("1024 KB"), Some(1024 * 1024));
        assert_eq!(parse_vram_str("invalid"), None);
        assert_eq!(parse_vram_str("8"), None);
    }

    #[test]
    fn test_parse_system_profiler_displays() {
        let mock_output = r#"
Graphics/Displays:

    Apple M1 Max:

      Chipset Model: Apple M1 Max
      Type: GPU
      Bus: Built-In
      Total Number of Cores: 32
      Vendor: Apple (0x106b)
      Metal Support: Metal 3
      VRAM (Dynamic, Max): 8192 MB
      Displays:
        Color LCD:
          Display Type: Built-In Retina LCD

    Intel UHD Graphics 630:

      Chipset Model: Intel UHD Graphics 630
      Type: GPU
      Bus: Built-In
      VRAM (Total): 1536 MB
      Vendor: Intel (0x8086)
"#;
        let gpus = parse_system_profiler_displays(mock_output);
        assert_eq!(gpus.len(), 2);
        assert_eq!(gpus[0].name, "Apple M1 Max");
        assert_eq!(gpus[0].vram_bytes, Some(8192 * 1024 * 1024));
        assert_eq!(gpus[1].name, "Intel UHD Graphics 630");
        assert_eq!(gpus[1].vram_bytes, Some(1536 * 1024 * 1024));
    }

    #[test]
    fn test_parse_wmi_videocontroller() {
        let wmic_output = r#"
AdapterRAM=4294967296
Name=NVIDIA GeForce RTX 4090

AdapterRAM=2147483648
Name=Intel(R) UHD Graphics 770
"#;
        let gpus = parse_wmi_videocontroller(wmic_output);
        assert_eq!(gpus.len(), 2);
        assert_eq!(gpus[0].name, "NVIDIA GeForce RTX 4090");
        assert_eq!(gpus[0].vram_bytes, Some(4294967296));
        assert_eq!(gpus[1].name, "Intel(R) UHD Graphics 770");
        assert_eq!(gpus[1].vram_bytes, Some(2147483648));

        let powershell_output = r#"
Name       : NVIDIA GeForce RTX 4090
AdapterRAM : 4294967296

Name       : Intel(R) UHD Graphics 770
AdapterRAM : 2147483648
"#;
        let gpus = parse_wmi_videocontroller(powershell_output);
        assert_eq!(gpus.len(), 2);
        assert_eq!(gpus[0].name, "NVIDIA GeForce RTX 4090");
        assert_eq!(gpus[0].vram_bytes, Some(4294967296));
        assert_eq!(gpus[1].name, "Intel(R) UHD Graphics 770");
        assert_eq!(gpus[1].vram_bytes, Some(2147483648));
    }
}