rcpufetch 0.0.4

[ALPHA] A rusty crossplatform, but simple CLI binutil for reading CPU information.
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
//! macOS CPU information module for rcpufetch.
//!
//! This module implements comprehensive CPU information gathering for macOS systems,
//! supporting both Intel and Apple Silicon architectures. It uses sysctl APIs and
//! system commands to collect model, vendor, core counts, cache sizes, frequency,
//! and CPU feature flags. All public items are documented following the standards
//! outlined in CONTRIBUTING.md and the linux.rs example.

use crate::art::logos::get_logo_lines_for_vendor;
use std::process::Command;

/// Struct representing parsed macOS CPU information.
///
/// Contains comprehensive CPU information gathered from sysctl and system commands,
/// including model, vendor, architecture, core counts, cache sizes, frequency, and flags.
pub struct MacOSCpuInfo {
    /// CPU model name from sysctl
    model: String,
    /// Vendor (Intel, AMD, Apple, or Unknown)
    vendor: String,
    /// System architecture (e.g., x86_64, arm64)
    architecture: String,
    /// Byte order (Little/Big Endian)
    byte_order: String,
    /// Physical core count
    physical_cores: u32,
    /// Logical core count (including hyperthreading)
    logical_cores: u32,
    /// Base frequency in MHz (if available)
    base_mhz: Option<f32>,
    /// L1 cache (size in KB, count)
    l1_size: Option<(u32, u32)>,
    /// L2 cache (size in KB, count)
    l2_size: Option<(u32, u32)>,
    /// L3 cache (size in KB, count)
    l3_size: Option<(u32, u32)>,
    /// CPU feature flags and capabilities
    flags: String,
}

impl MacOSCpuInfo {
    /// Gather all CPU information for macOS.
    ///
    /// Collects model, vendor, architecture, core counts, cache sizes, frequency,
    /// and CPU flags using sysctl and system commands. Handles both Intel and Apple Silicon.
    ///
    /// # Returns
    ///
    /// * `Ok(MacOSCpuInfo)` if all required information is gathered
    /// * `Err(String)` if a critical error occurs during information gathering
    pub fn new() -> Result<Self, String> {
        // Get CPU brand string
        let model = Self::get_sysctl_string("machdep.cpu.brand_string")?;
        
        // Get architecture using uname -m
        let architecture = Self::get_architecture()?;
        
        // Get byte order from sysctl and format it
        let byte_order = Self::get_sysctl_string("hw.byteorder")
            .map(|order| {
                match order.trim() {
                    "1234" => "Little Endian".to_string(),
                    "4321" => "Big Endian".to_string(),
                    _ => format!("Unknown ({})", order)
                }
            })
            .unwrap_or_else(|_| "Unknown".to_string());
        
        // Determine vendor from brand string
        let vendor = if model.to_lowercase().contains("intel") {
            "Intel".to_string()
        } else if model.to_lowercase().contains("amd") {
            "AMD".to_string()
        } else if model.to_lowercase().contains("apple") {
            "Apple".to_string()
        } else {
            "Unknown".to_string()
        };
        
        // Get core counts
        let physical_cores = Self::get_sysctl_u32("machdep.cpu.core_count")
            .unwrap_or_else(|_| Self::get_sysctl_u32("machdep.cpu.cores_per_package").unwrap_or(0));
        let logical_cores = Self::get_sysctl_u32("machdep.cpu.thread_count")
            .unwrap_or_else(|_| Self::get_sysctl_u32("machdep.cpu.logical_per_package").unwrap_or(physical_cores));
        
        // Get base frequency (if available)
        let base_mhz = Self::get_sysctl_string("machdep.cpu.max_basic")
            .ok()
            .and_then(|s| s.parse::<f32>().ok());
        
        // Parse cache information - prefer detailed perflevel cache info for Apple Silicon
        let (l1_size, l2_size, l3_size) = Self::get_cache_info();
        
        // Get CPU flags
        let flags = Self::get_cpu_flags();
        
        Ok(Self {
            model,
            vendor,
            architecture,
            byte_order,
            physical_cores,
            logical_cores,
            base_mhz,
            l1_size,
            l2_size,
            l3_size,
            flags,
        })
    }
    
    /// Helper function to format cache size with appropriate units (KB or MB).
    ///
    /// Converts cache sizes above 1000KB to megabytes with decimal precision.
    ///
    /// # Arguments
    ///
    /// * `size_kb` - Cache size in kilobytes
    ///
    /// # Returns
    ///
    /// Returns a formatted string with appropriate units (e.g., "288KB" or "6.0MB")
    fn format_cache_size(size_kb: u32) -> String {
        if size_kb >= 1000 {
            format!("{:.1}MB", size_kb as f32 / 1024.0)
        } else {
            format!("{}KB", size_kb)
        }
    }

    /// Helper function to get comprehensive cache information.
    ///
    /// Returns L1, L2, and L3 cache sizes and counts, using sysctl keys and
    /// performance level queries for Apple Silicon.
    ///
    /// # Returns
    ///
    /// Tuple of (L1, L2, L3) cache info as Option<(size_kb, count)>
    fn get_cache_info() -> (Option<(u32, u32)>, Option<(u32, u32)>, Option<(u32, u32)>) {
        // First try the traditional hw.cachesize approach
        let cache_sizes = Self::get_sysctl_string("hw.cachesize").unwrap_or_default();
        let cache_config = Self::get_sysctl_string("hw.cacheconfig").unwrap_or_default();
        
        let size_parts: Vec<&str> = cache_sizes.split_whitespace().collect();
        let config_parts: Vec<&str> = cache_config.split_whitespace().collect();
        
        let l1_size = if size_parts.len() >= 2 && config_parts.len() >= 2 {
            let size_bytes = size_parts[1].parse::<u32>().unwrap_or(0);
            let count = config_parts[1].parse::<u32>().unwrap_or(0);
            if size_bytes > 0 && count > 0 { 
                Some((size_bytes / 1024, count)) // Convert bytes to KB
            } else { None }
        } else { None };
        
        let l2_size = if size_parts.len() >= 3 && config_parts.len() >= 3 {
            let size_bytes = size_parts[2].parse::<u32>().unwrap_or(0);
            let count = config_parts[2].parse::<u32>().unwrap_or(0);
            if size_bytes > 0 && count > 0 { 
                Some((size_bytes / 1024, count)) // Convert bytes to KB
            } else { None }
        } else { None };
        
        let mut l3_size = if size_parts.len() >= 4 && config_parts.len() >= 4 {
            let size_bytes = size_parts[3].parse::<u32>().unwrap_or(0);
            let count = config_parts[3].parse::<u32>().unwrap_or(0);
            if size_bytes > 0 && count > 0 { 
                Some((size_bytes / 1024, count)) // Convert bytes to KB
            } else { None }
        } else { None };
        
        // For Apple Silicon, if L3 is not available from hw.cachesize, check performance level caches
        if l3_size.is_none() {
            // Check if we have performance level cache information (Apple Silicon)
            let perf0_l2 = Self::get_sysctl_u32("hw.perflevel0.l2cachesize").ok();
            let perf1_l2 = Self::get_sysctl_u32("hw.perflevel1.l2cachesize").ok();
            
            if let (Some(p0_l2), Some(p1_l2)) = (perf0_l2, perf1_l2) {
                // If we have different performance levels with different L2 sizes,
                // report the larger one as "shared cache" equivalent
                if p0_l2 != p1_l2 {
                    let larger_cache = std::cmp::max(p0_l2, p1_l2);
                    l3_size = Some((larger_cache / 1024, 1)); // Convert bytes to KB, show as 1 unit
                }
            }
        }
        
        (l1_size, l2_size, l3_size)
    }

    /// Helper function to get a string value from sysctl.
    ///
    /// # Arguments
    ///
    /// * `key` - sysctl key to query
    ///
    /// # Returns
    ///
    /// * `Ok(String)` with the sysctl value
    /// * `Err(String)` with error context if sysctl fails
    fn get_sysctl_string(key: &str) -> Result<String, String> {
        let output = Command::new("sysctl")
            .arg("-n")
            .arg(key)
            .output()
            .map_err(|e| format!("Failed to execute sysctl: {}", e))?;
        
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            Err(format!("sysctl command failed for key: {}", key))
        }
    }
    
    /// Helper function to get a u32 value from sysctl.
    ///
    /// # Arguments
    ///
    /// * `key` - sysctl key to query
    ///
    /// # Returns
    ///
    /// * `Ok(u32)` with the parsed value
    /// * `Err(String)` with error context if sysctl fails or value is not a valid u32
    fn get_sysctl_u32(key: &str) -> Result<u32, String> {
        let value_str = Self::get_sysctl_string(key)?;
        value_str.parse::<u32>()
            .map_err(|e| format!("Failed to parse '{}' as u32: {}", value_str, e))
    }

    /// Get system architecture using uname -m.
    ///
    /// # Returns
    ///
    /// * `Ok(String)` with the architecture string
    /// * `Err(String)` if uname fails
    fn get_architecture() -> Result<String, String> {
        let output = Command::new("uname")
            .arg("-m")
            .output()
            .map_err(|e| format!("Failed to execute uname: {}", e))?;
        
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            Err("uname command failed".to_string())
        }
    }

    /// Get CPU flags from sysctl hw.optional.arm.* keys.
    ///
    /// Queries all available ARM CPU feature flags via sysctl and returns a comma-separated
    /// string of enabled features, similar to Linux /proc/cpuinfo flags. Only features with
    /// value '1' (enabled) are included in the output.
    ///
    /// # Returns
    ///
    /// Returns a comma-separated string of enabled CPU feature flags (e.g., "FEAT_AES,FEAT_SHA256,FEAT_CRC32")
    /// or an empty string if no flags are available or if not running on ARM architecture.
    fn get_cpu_flags() -> String {
        // Try to get a list of all hw.optional.arm.* sysctl keys
        let output = Command::new("sysctl")
            .arg("hw.optional.arm.")
            .output();
        
        match output {
            Ok(result) if result.status.success() => {
                let output_str = String::from_utf8_lossy(&result.stdout);
                let mut enabled_flags = Vec::new();
                
                for line in output_str.lines() {
                    if let Some((key, value)) = line.split_once(": ") {
                        // Parse the value - only include flags that are enabled (value = 1)
                        if value.trim() == "1" {
                            // Extract the flag name from the key (everything after "hw.optional.arm.")
                            if let Some(flag_name) = key.strip_prefix("hw.optional.arm.") {
                                enabled_flags.push(flag_name.to_string());
                            }
                        }
                    }
                }
                
                enabled_flags.join(",")
            }
            _ => String::new() // Return empty string if sysctl fails (e.g., not ARM architecture)
        }
    }

    /// Display CPU information with logo (side-by-side layout).
    ///
    /// Displays comprehensive CPU information alongside a vendor logo in a side-by-side layout.
    /// The logo can be overridden to display a different vendor's logo regardless of the actual CPU vendor.
    ///
    /// # Arguments
    ///
    /// * `logo_override` - Optional vendor ID to override the detected logo
    pub fn display_info_with_logo(&self, logo_override: Option<&str>) {
        let vendor_to_use = logo_override.unwrap_or(&self.vendor);
        let logo_lines = get_logo_lines_for_vendor(vendor_to_use).unwrap_or_else(|| vec![]);
        
        let mut info_lines = self.get_info_lines();
        
        // Handle flags wrapping
        if !self.flags.is_empty() {
            let logo_width = logo_lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
            let sep = "   ";
            let left_margin = logo_width + sep.len();
            let total_width = 100; // Terminal width
            let wrap_width = total_width - left_margin;
            
            // Wrap flags text
            let flag_label = "Flags: ";
            let indent = "       "; // 7 spaces to align with "Flags: "
            let mut flag_lines = Vec::new();
            let mut current_line = String::from(flag_label);
            
            for word in self.flags.split(',') {
                let word = word.trim();
                if current_line.len() + word.len() + 2 > wrap_width { // +2 for ", "
                    flag_lines.push(current_line);
                    current_line = format!("{}{}", indent, word);
                } else {
                    if current_line.trim_end().ends_with(":") {
                        current_line.push_str(word);
                    } else {
                        current_line.push_str(", ");
                        current_line.push_str(word);
                    }
                }
            }
            if !current_line.trim().is_empty() {
                flag_lines.push(current_line);
            }
            
            // Add flag lines to info_lines
            info_lines.extend(flag_lines);
        }
        
        let logo_width = logo_lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
        let sep = "   ";
        let max_lines = std::cmp::max(logo_lines.len(), info_lines.len());

        // Print logo and info side by side
        for i in 0..max_lines {
            let logo = logo_lines.get(i).map(|s| s.as_str()).unwrap_or("");
            let mut info = info_lines.get(i).map(|s| s.as_str()).unwrap_or("").to_string();
            
            // If there's no logo content on this line, remove the indent from flag lines
            let indent = "       "; // 7 spaces to align with "Flags: "
            if logo.is_empty() && info.starts_with(indent) {
                info = info[indent.len()..].to_string();
            }
            
            println!("{:<width$}{}{}", logo, sep, info, width=logo_width);
        }
    }

    /// Display CPU information without any logo.
    ///
    /// Displays comprehensive CPU information in a simple list format without any vendor logo
    /// or side-by-side alignment. Flags are wrapped for readability.
    pub fn display_info_no_logo(&self) {
        let info_lines = self.get_info_lines();
        
        // Print CPU information without logo
        for line in info_lines {
            println!("{}", line);
        }
        
        // Print flags with wrapping
        if !self.flags.is_empty() {
            print!("Flags: ");
            let wrap_width = 80; // Standard terminal width
            let mut current_line_len = 7; // "Flags: " length
            let mut first_flag = true;
            
            for word in self.flags.split(',') {
                let word = word.trim();
                if !first_flag && current_line_len + word.len() + 2 > wrap_width { // +2 for ", "
                    println!();
                    print!("       {}", word); // 7 spaces to align with "Flags: "
                    current_line_len = 7 + word.len();
                } else {
                    if first_flag {
                        print!("{}", word);
                        current_line_len += word.len();
                        first_flag = false;
                    } else {
                        print!(", {}", word);
                        current_line_len += word.len() + 2; // +2 for ", "
                    }
                }
            }
            println!(); // Final newline
        }
    }

    /// Get the formatted information lines for display.
    ///
    /// Generates the formatted CPU information lines that are used by both logo and no-logo
    /// display methods. For Apple Silicon, includes performance-level cache details.
    ///
    /// # Returns
    ///
    /// Vector of formatted information lines as strings.
    fn get_info_lines(&self) -> Vec<String> {
        let mut lines = vec![
            format!("Name: {}", self.model),
            format!("Architecture: {}", self.architecture),
            format!("Byte Order: {}", self.byte_order),
            format!("Vendor: {}", self.vendor),
            format!("Cores: {} cores ({} threads)", self.physical_cores, self.logical_cores),
        ];
        
        if let Some(mhz) = self.base_mhz {
            lines.push(format!("Base Frequency: {:.2} MHz", mhz));
        }
        
        // For Apple Silicon, provide more detailed cache information
        if self.vendor == "Apple" {
            // Try to get performance level specific cache info
            if let Ok(perf0_l1i) = Self::get_sysctl_u32("hw.perflevel0.l1icachesize") {
                if let Ok(perf0_l1d) = Self::get_sysctl_u32("hw.perflevel0.l1dcachesize") {
                    let l1i_formatted = Self::format_cache_size(perf0_l1i / 1024);
                    let l1d_formatted = Self::format_cache_size(perf0_l1d / 1024);
                    lines.push(format!("P-Core L1 Cache: {} I + {} D", l1i_formatted, l1d_formatted));
                }
            }
            if let Ok(perf1_l1i) = Self::get_sysctl_u32("hw.perflevel1.l1icachesize") {
                if let Ok(perf1_l1d) = Self::get_sysctl_u32("hw.perflevel1.l1dcachesize") {
                    let l1i_formatted = Self::format_cache_size(perf1_l1i / 1024);
                    let l1d_formatted = Self::format_cache_size(perf1_l1d / 1024);
                    lines.push(format!("E-Core L1 Cache: {} I + {} D", l1i_formatted, l1d_formatted));
                }
            }
            if let Ok(perf0_l2) = Self::get_sysctl_u32("hw.perflevel0.l2cachesize") {
                let l2_formatted = Self::format_cache_size(perf0_l2 / 1024);
                lines.push(format!("P-Core L2 Cache: {}", l2_formatted));
            }
            if let Ok(perf1_l2) = Self::get_sysctl_u32("hw.perflevel1.l2cachesize") {
                let l2_formatted = Self::format_cache_size(perf1_l2 / 1024);
                lines.push(format!("E-Core L2 Cache: {}", l2_formatted));
            }
        } else {
            // For non-Apple systems, use traditional cache display
            if let Some((l1, l1_count)) = self.l1_size {
                let l1_formatted = Self::format_cache_size(l1);
                lines.push(format!("L1 Cache Size: {} ({} cores)", l1_formatted, l1_count));
            }
            
            if let Some((l2, l2_count)) = self.l2_size {
                let l2_formatted = Self::format_cache_size(l2);
                lines.push(format!("L2 Cache Size: {} ({} cores)", l2_formatted, l2_count));
            }
            
            if let Some((l3, l3_count)) = self.l3_size {
                let l3_formatted = Self::format_cache_size(l3);
                lines.push(format!("L3 Cache Size: {} ({} cores)", l3_formatted, l3_count));
            }
        }
        
        // Don't add flags here - they will be handled separately with wrapping
        
        lines
    }
}