Skip to content

Commit 8d9fae4

Browse files
committed
chore: clippy lint
1 parent e2fba06 commit 8d9fae4

File tree

8 files changed

+42
-42
lines changed

8 files changed

+42
-42
lines changed

Cargo.lock

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,18 @@ non_camel_case_types = "allow"
88
unused_assignments = "allow"
99
unreachable_code = "allow"
1010

11+
[lints.clippy]
12+
single_match = "allow"
13+
needless_range_loop = "allow"
14+
1115
[profile.release]
1216
panic = "abort"
1317
strip = false
1418
lto = false
1519

1620
[dependencies]
1721
chrono = "0.4.39"
18-
clap = { version = "4.5.30", features = ["derive"] }
22+
clap = { version = "4.5.31", features = ["derive"] }
1923
core-foundation = "0.10.0"
2024
libc = "0.2.170"
2125
num-traits = "0.2.19"

Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
lint:
22
cargo fmt --check
3+
cargo clippy --all-targets --all-features -- -D warnings
34
cargo check --release --locked
45

56
build:

src/app.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ fn enter_term() -> Terminal<impl Backend> {
3131
stdout().execute(terminal::EnterAlternateScreen).unwrap();
3232

3333
let term = CrosstermBackend::new(std::io::stdout());
34-
let term = Terminal::new(term).unwrap();
35-
term
34+
Terminal::new(term).unwrap()
3635
}
3736

3837
fn leave_term() {
@@ -218,7 +217,7 @@ fn run_sampler_thread(tx: mpsc::Sender<Event>, msec: Arc<RwLock<u32>>) {
218217
// get average of two values, used to smooth out metrics
219218
// see: https://github.com/vladkens/macmon/issues/10
220219
fn avg2<T: num_traits::Float>(a: T, b: T) -> T {
221-
return if a == T::zero() { b } else { (a + b) / T::from(2.0).unwrap() };
220+
if a == T::zero() { b } else { (a + b) / T::from(2.0).unwrap() }
222221
}
223222

224223
// MARK: App
@@ -275,11 +274,11 @@ impl App {
275274
// .title_style(Style::default().gray())
276275
.padding(Padding::ZERO);
277276

278-
if label_l.len() > 0 {
277+
if !label_l.is_empty() {
279278
block = block.title_top(Line::from(format!(" {label_l} ")));
280279
}
281280

282-
if label_r.len() > 0 {
281+
if !label_r.is_empty() {
283282
block = block.title_top(Line::from(format!(" {label_r} ")).alignment(Alignment::Right));
284283
}
285284

@@ -434,7 +433,7 @@ impl App {
434433

435434
pub fn run_loop(&mut self, interval: Option<u32>) -> WithError<()> {
436435
// use from arg if provided, otherwise use config restored value
437-
self.cfg.interval = interval.unwrap_or(self.cfg.interval).max(100).min(10_000);
436+
self.cfg.interval = interval.unwrap_or(self.cfg.interval).clamp(100, 10_000);
438437
let msec = Arc::new(RwLock::new(self.cfg.interval));
439438

440439
let (tx, rx) = mpsc::channel::<Event>();

src/config.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,7 @@ impl Config {
5050
};
5151

5252
let reader = std::io::BufReader::new(file);
53-
return match serde_json::from_reader(reader) {
54-
Ok(config) => config,
55-
Err(_) => Self::default(),
56-
};
53+
return serde_json::from_reader(reader).unwrap_or_default();
5754
}
5855

5956
Self::default()
@@ -89,7 +86,7 @@ impl Config {
8986

9087
pub fn dec_interval(&mut self) {
9188
let step = 250;
92-
self.interval = ((self.interval.saturating_sub(step) + step - 1) / step * step).max(step);
89+
self.interval = (self.interval.saturating_sub(step).div_ceil(step) * step).max(step);
9390
self.save();
9491
}
9592

src/debug.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::sources::{
88
type WithError<T> = Result<T, Box<dyn std::error::Error>>;
99

1010
fn print_divider(msg: &str) {
11-
if msg.len() == 0 {
11+
if msg.is_empty() {
1212
println!("{}", "-".repeat(80));
1313
return;
1414
}
@@ -88,12 +88,12 @@ pub fn print_debug() -> WithError<()> {
8888
continue;
8989
}
9090

91-
let ki = smc.read_key_info(&key)?;
91+
let ki = smc.read_key_info(key)?;
9292
if !(ki.data_type == FLOAT_TYPE && ki.data_size == 4) {
9393
continue;
9494
}
9595

96-
let val = smc.read_val(&key);
96+
let val = smc.read_val(key);
9797
if val.is_err() {
9898
continue;
9999
}
@@ -107,7 +107,7 @@ pub fn print_debug() -> WithError<()> {
107107
print!("{}={:04.1} ", key, val);
108108
}
109109

110-
println!(""); // close previous line
110+
println!(); // close previous line
111111

112112
print_divider("IOHID");
113113
let hid = IOHIDSensors::new()?;

src/metrics.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@ pub struct Metrics {
4747

4848
pub fn zero_div<T: core::ops::Div<Output = T> + Default + PartialEq>(a: T, b: T) -> T {
4949
let zero: T = Default::default();
50-
return if b == zero { zero } else { a / b };
50+
if b == zero { zero } else { a / b }
5151
}
5252

53-
fn calc_freq(item: CFDictionaryRef, freqs: &Vec<u32>) -> (u32, f32) {
53+
fn calc_freq(item: CFDictionaryRef, freqs: &[u32]) -> (u32, f32) {
5454
let items = cfio_get_residencies(item); // (ns, freq)
5555
let (len1, len2) = (items.len(), freqs.len());
5656
assert!(len1 > len2, "cacl_freq invalid data: {} vs {}", len1, len2); // todo?
@@ -69,17 +69,17 @@ fn calc_freq(item: CFDictionaryRef, freqs: &Vec<u32>) -> (u32, f32) {
6969
}
7070

7171
let usage_ratio = zero_div(usage, total);
72-
let min_freq = freqs.first().unwrap().clone() as f64;
73-
let max_freq = freqs.last().unwrap().clone() as f64;
72+
let min_freq = *freqs.first().unwrap() as f64;
73+
let max_freq = *freqs.last().unwrap() as f64;
7474
let from_max = (avg_freq.max(min_freq) * usage_ratio) / max_freq;
7575

7676
(avg_freq as u32, from_max as f32)
7777
}
7878

79-
fn calc_freq_final(items: &Vec<(u32, f32)>, freqs: &Vec<u32>) -> (u32, f32) {
79+
fn calc_freq_final(items: &[(u32, f32)], freqs: &[u32]) -> (u32, f32) {
8080
let avg_freq = zero_div(items.iter().map(|x| x.0 as f32).sum(), items.len() as f32);
81-
let avg_perc = zero_div(items.iter().map(|x| x.1 as f32).sum(), items.len() as f32);
82-
let min_freq = freqs.first().unwrap().clone() as f32;
81+
let avg_perc = zero_div(items.iter().map(|x| x.1).sum(), items.len() as f32);
82+
let min_freq = *freqs.first().unwrap() as f32;
8383

8484
(avg_freq.max(min_freq) as u32, avg_perc)
8585
}
@@ -93,7 +93,7 @@ fn init_smc() -> WithError<(SMC, Vec<String>, Vec<String>)> {
9393

9494
let names = smc.read_all_keys().unwrap_or(vec![]);
9595
for name in &names {
96-
let key = match smc.read_key_info(&name) {
96+
let key = match smc.read_key_info(name) {
9797
Ok(key) => key,
9898
Err(_) => continue,
9999
};
@@ -102,7 +102,7 @@ fn init_smc() -> WithError<(SMC, Vec<String>, Vec<String>)> {
102102
continue;
103103
}
104104

105-
let _ = match smc.read_val(&name) {
105+
let _ = match smc.read_val(name) {
106106
Ok(val) => val,
107107
Err(_) => continue,
108108
};
@@ -204,7 +204,7 @@ impl Sampler {
204204
fn get_temp(&mut self) -> WithError<TempMetrics> {
205205
// HID for M1, SMC for M2/M3
206206
// UPD: Looks like HID/SMC related to OS version, not to the chip (SMC available from macOS 14)
207-
match self.smc_cpu_keys.len() > 0 {
207+
match !self.smc_cpu_keys.is_empty() {
208208
true => self.get_temp_smc(),
209209
false => self.get_temp_hid(),
210210
}
@@ -248,7 +248,7 @@ impl Sampler {
248248

249249
if x.group == "GPU Stats" && x.subgroup == GPU_FREQ_DICE_SUBG {
250250
match x.channel.as_str() {
251-
"GPUPH" => rs.gpu_usage = calc_freq(x.item, &self.soc.gpu_freqs[1..].to_vec()),
251+
"GPUPH" => rs.gpu_usage = calc_freq(x.item, &self.soc.gpu_freqs[1..]),
252252
_ => {}
253253
}
254254
}

src/sources.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -325,15 +325,13 @@ pub fn libc_ram() -> WithError<(u64, u64)> {
325325

326326
let page_size_kb = libc::sysconf(libc::_SC_PAGESIZE) as u64;
327327

328-
usage = (0
329-
+ stats.active_count as u64
328+
usage = (stats.active_count as u64
330329
+ stats.inactive_count as u64
331330
+ stats.wire_count as u64
332331
+ stats.speculative_count as u64
333332
+ stats.compressor_page_count as u64
334333
- stats.purgeable_count as u64
335-
- stats.external_page_count as u64
336-
+ 0)
334+
- stats.external_page_count as u64)
337335
* page_size_kb;
338336
}
339337

@@ -412,7 +410,7 @@ pub fn get_dvfs_mhz(dict: CFDictionaryRef, key: &str) -> (Vec<u32>, Vec<u32>) {
412410
pub fn run_system_profiler() -> WithError<serde_json::Value> {
413411
// system_profiler -listDataTypes
414412
let out = std::process::Command::new("system_profiler")
415-
.args(&["SPHardwareDataType", "SPDisplaysDataType", "SPSoftwareDataType", "-json"])
413+
.args(["SPHardwareDataType", "SPDisplaysDataType", "SPSoftwareDataType", "-json"])
416414
.output()?;
417415

418416
let out = std::str::from_utf8(&out.stdout)?;
@@ -500,7 +498,7 @@ pub fn get_soc_info() -> WithError<SocInfo> {
500498

501499
fn cfio_get_chan(items: Vec<(&str, Option<&str>)>) -> WithError<CFMutableDictionaryRef> {
502500
// if no items are provided, return all channels
503-
if items.len() == 0 {
501+
if items.is_empty() {
504502
unsafe {
505503
let c = IOReportCopyAllChannels(0, 0);
506504
let r = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, CFDictionaryGetCount(c), c);
@@ -512,7 +510,7 @@ fn cfio_get_chan(items: Vec<(&str, Option<&str>)>) -> WithError<CFMutableDiction
512510
let mut channels = vec![];
513511
for (group, subgroup) in items {
514512
let gname = cfstr(group);
515-
let sname = subgroup.map_or(null(), |x| cfstr(x));
513+
let sname = subgroup.map_or(null(), cfstr);
516514
let chan = unsafe { IOReportCopyChannelsInGroup(gname, sname, 0, 0, 0) };
517515
channels.push(chan);
518516

@@ -583,7 +581,7 @@ impl IOReport {
583581
}
584582

585583
pub fn get_samples(&mut self, duration: u64, count: usize) -> Vec<(IOReportIterator, u64)> {
586-
let count = count.max(1).min(32);
584+
let count = count.clamp(1, 32);
587585
let mut samples: Vec<(IOReportIterator, u64)> = Vec::with_capacity(count);
588586
let step_msec = duration / count as u64;
589587

@@ -663,8 +661,8 @@ pub struct IOHIDSensors {
663661

664662
impl IOHIDSensors {
665663
pub fn new() -> WithError<Self> {
666-
let keys = vec![cfstr("PrimaryUsagePage"), cfstr("PrimaryUsage")];
667-
let nums = vec![cfnum(kHIDPage_AppleVendor), cfnum(kHIDUsage_AppleVendor_TemperatureSensor)];
664+
let keys = [cfstr("PrimaryUsagePage"), cfstr("PrimaryUsage")];
665+
let nums = [cfnum(kHIDPage_AppleVendor), cfnum(kHIDUsage_AppleVendor_TemperatureSensor)];
668666

669667
let dict = unsafe {
670668
CFDictionaryCreate(
@@ -799,6 +797,7 @@ pub struct SensorVal {
799797

800798
// MARK: SMC
801799

800+
#[allow(clippy::upper_case_acronyms)]
802801
pub struct SMC {
803802
conn: u32,
804803
keys: HashMap<u32, KeyInfo>,
@@ -861,7 +860,7 @@ impl SMC {
861860
let key = key.bytes().fold(0, |acc, x| (acc << 8) + x as u32);
862861
if let Some(ki) = self.keys.get(&key) {
863862
// println!("cache hit for {}", key);
864-
return Ok(ki.clone());
863+
return Ok(*ki);
865864
}
866865

867866
let ival = KeyData { data8: 9, key, ..Default::default() };

0 commit comments

Comments
 (0)