Skip to content

Commit 5e14e32

Browse files
authored
fix: make build and cargo clippy happy (benfred#795)
Signed-off-by: yihong0618 <zouzou0208@gmail.com>
1 parent 6357ae8 commit 5e14e32

File tree

13 files changed

+56
-71
lines changed

13 files changed

+56
-71
lines changed

src/binary_parser.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ pub fn parse_binary(filename: &Path, addr: u64, size: u64) -> Result<BinaryInfo,
125125
.filter(|header| {
126126
strtab
127127
.get_at(header.sh_name)
128-
.map_or(true, |name| name == ".bss")
128+
.is_none_or(|name| name == ".bss")
129129
})
130130
// if we have multiple sections here, take the largest
131131
.max_by_key(|header| header.sh_size)
@@ -171,11 +171,10 @@ pub fn parse_binary(filename: &Path, addr: u64, size: u64) -> Result<BinaryInfo,
171171
bss_end = bss_header.sh_addr + bss_header.sh_size;
172172
}
173173

174-
let pyruntime_header = elf.section_headers.iter().find(|header| {
175-
strtab
176-
.get_at(header.sh_name)
177-
.map_or(false, |name| name == ".PyRuntime")
178-
});
174+
let pyruntime_header = elf
175+
.section_headers
176+
.iter()
177+
.find(|header| strtab.get_at(header.sh_name) == Some(".PyRuntime"));
179178

180179
let mut pyruntime_addr = 0;
181180
let mut pyruntime_size = 0;

src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ impl std::str::FromStr for FileFormat {
8787
return Ok(*variant);
8888
}
8989
}
90-
Err(format!("Invalid fileformat: {}", s))
90+
Err(format!("Invalid fileformat: {s}"))
9191
}
9292
}
9393

src/console_viewer.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::collections::HashMap;
22
use std::io;
3-
use std::io::{Read, Write};
3+
use std::io::{BufReader, Read, Write};
44
use std::sync::{atomic, Arc, Mutex};
55
use std::thread;
66
use std::vec::Vec;
@@ -40,14 +40,17 @@ impl ConsoleViewer {
4040
let input_running = running.clone();
4141
let input_options = options.clone();
4242
thread::spawn(move || {
43+
let stdin = std::io::stdin();
44+
let mut buf_reader = BufReader::new(stdin);
45+
let mut buffer = [0u8; 1];
4346
while input_running.load(atomic::Ordering::Relaxed) {
4447
// TODO: there isn't a non-blocking version of stdin, so this will capture the
4548
// next keystroke after the ConsoleViewer object has been destroyed =(
46-
if let Some(Ok(key)) = std::io::stdin().bytes().next() {
49+
if buf_reader.read_exact(&mut buffer).is_ok() {
4750
let mut options = input_options.lock().unwrap();
4851
options.dirty = true;
4952
let previous_usage = options.usage;
50-
match key as char {
53+
match buffer[0] as char {
5154
'R' | 'r' => options.reset = true,
5255
'L' | 'l' => options.show_linenumbers = !options.show_linenumbers,
5356
'X' | 'x' => options.usage = false,
@@ -173,7 +176,7 @@ impl ConsoleViewer {
173176
if let Some(delay) = self.stats.last_delay {
174177
let late_rate = self.stats.late_samples as f64 / self.stats.overall_samples as f64;
175178
if late_rate > 0.10 && delay > std::time::Duration::from_secs(1) {
176-
let msg = format!("{:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate.", delay);
179+
let msg = format!("{delay:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate.");
177180
out!("{}", style(msg).red());
178181
header_lines += 1;
179182
}
@@ -327,7 +330,7 @@ impl ConsoleViewer {
327330
pub fn increment_error(&mut self, err: &Error) -> Result<(), Error> {
328331
self.maybe_reset();
329332
self.stats.errors += 1;
330-
self.stats.last_error = Some(format!("{}", err));
333+
self.stats.last_error = Some(format!("{err}"));
331334
self.increment_common()
332335
}
333336

@@ -492,13 +495,13 @@ impl Stats {
492495
// helper function for formatting time values (hide decimals for larger values)
493496
fn display_time(val: f64) -> String {
494497
if val > 1000.0 {
495-
format!("{:.0}", val)
498+
format!("{val:.0}")
496499
} else if val >= 100.0 {
497-
format!("{:.1}", val)
500+
format!("{val:.1}")
498501
} else if val >= 1.0 {
499-
format!("{:.2}", val)
502+
format!("{val:.2}")
500503
} else {
501-
format!("{:.3}", val)
504+
format!("{val:.3}")
502505
}
503506
}
504507

src/flamegraph.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ impl Flamegraph {
7676
fn get_lines(&self) -> Vec<String> {
7777
self.counts
7878
.iter()
79-
.map(|(k, v)| format!("{} {}", k, v))
79+
.map(|(k, v)| format!("{k} {v}"))
8080
.collect()
8181
}
8282

src/main.rs

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ fn sample_console(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
6262

6363
let display = match remoteprocess::Process::new(pid)?.cmdline() {
6464
Ok(cmdline) => cmdline.join(" "),
65-
Err(_) => format!("Pid {}", pid),
65+
Err(_) => format!("Pid {pid}"),
6666
};
6767

6868
let mut console =
@@ -81,7 +81,7 @@ fn sample_console(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
8181
}
8282

8383
if !config.subprocesses {
84-
println!("\nprocess {} ended", pid);
84+
println!("\nprocess {pid} ended");
8585
}
8686
Ok(())
8787
}
@@ -163,7 +163,7 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
163163
None => String::from("unknown"),
164164
},
165165
};
166-
format!("{}-{}.{}", name, local_time, ext)
166+
format!("{name}-{local_time}.{ext}")
167167
}
168168
};
169169

@@ -237,12 +237,12 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
237237
let now = std::time::Instant::now();
238238
if now - last_late_message > Duration::from_secs(1) {
239239
last_late_message = now;
240-
println!("{}{:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate", lede, delay)
240+
println!("{lede}{delay:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate")
241241
}
242242
} else {
243243
let term = console::Term::stdout();
244244
term.move_cursor_up(2)?;
245-
println!("{:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate.", delay);
245+
println!("{delay:.2?} behind in sampling, results may be inaccurate. Try reducing the sampling rate.");
246246
term.move_cursor_down(1)?;
247247
}
248248
}
@@ -273,9 +273,9 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
273273
if config.include_thread_ids {
274274
let threadid = trace.format_threadid();
275275
let thread_fmt = if let Some(thread_name) = &trace.thread_name {
276-
format!("thread ({}): {}", threadid, thread_name)
276+
format!("thread ({threadid}): {thread_name}")
277277
} else {
278-
format!("thread ({})", threadid)
278+
format!("thread ({threadid})")
279279
};
280280
trace.frames.push(Frame {
281281
name: thread_fmt,
@@ -313,9 +313,9 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
313313

314314
if config.duration == RecordDuration::Unlimited {
315315
let msg = if errors > 0 {
316-
format!("Collected {} samples ({} errors)", samples, errors)
316+
format!("Collected {samples} samples ({errors} errors)")
317317
} else {
318-
format!("Collected {} samples", samples)
318+
format!("Collected {samples} samples")
319319
};
320320
progress.set_message(msg);
321321
}
@@ -324,7 +324,7 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
324324
progress.finish();
325325
// write out a message here (so as not to interfere with progress bar) if we ended earlier
326326
if !exit_message.is_empty() {
327-
println!("\n{}{}", lede, exit_message);
327+
println!("\n{lede}{exit_message}");
328328
}
329329

330330
{
@@ -335,8 +335,7 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
335335
match config.format.as_ref().unwrap() {
336336
FileFormat::flamegraph => {
337337
println!(
338-
"{}Wrote flamegraph data to '{}'. Samples: {} Errors: {}",
339-
lede, filename, samples, errors
338+
"{lede}Wrote flamegraph data to '{filename}'. Samples: {samples} Errors: {errors}"
340339
);
341340
// open generated flame graph in the browser on OSX (theory being that on linux
342341
// you might be SSH'ed into a server somewhere and this isn't desired, but on
@@ -346,27 +345,21 @@ fn record_samples(pid: remoteprocess::Pid, config: &Config) -> Result<(), Error>
346345
}
347346
FileFormat::speedscope => {
348347
println!(
349-
"{}Wrote speedscope file to '{}'. Samples: {} Errors: {}",
350-
lede, filename, samples, errors
348+
"{lede}Wrote speedscope file to '{filename}'. Samples: {samples} Errors: {errors}"
351349
);
352-
println!("{}Visit https://www.speedscope.app/ to view", lede);
350+
println!("{lede}Visit https://www.speedscope.app/ to view");
353351
}
354352
FileFormat::raw => {
355353
println!(
356-
"{}Wrote raw flamegraph data to '{}'. Samples: {} Errors: {}",
357-
lede, filename, samples, errors
354+
"{lede}Wrote raw flamegraph data to '{filename}'. Samples: {samples} Errors: {errors}"
358355
);
359-
println!("{}You can use the flamegraph.pl script from https://github.com/brendangregg/flamegraph to generate a SVG", lede);
356+
println!("{lede}You can use the flamegraph.pl script from https://github.com/brendangregg/flamegraph to generate a SVG");
360357
}
361358
FileFormat::chrometrace => {
362359
println!(
363-
"{}Wrote chrome trace to '{}'. Samples: {} Errors: {}",
364-
lede, filename, samples, errors
365-
);
366-
println!(
367-
"{}Visit chrome://tracing or https://ui.perfetto.dev/ to view",
368-
lede
360+
"{lede}Wrote chrome trace to '{filename}'. Samples: {samples} Errors: {errors}"
369361
);
362+
println!("{lede}Visit chrome://tracing or https://ui.perfetto.dev/ to view");
370363
}
371364
};
372365

@@ -468,7 +461,7 @@ fn pyspy_main() -> Result<(), Error> {
468461
if config.capture_output && (!success || result.is_err()) {
469462
let mut buffer = String::new();
470463
if process_output.read_to_string(&mut buffer).is_ok() {
471-
eprintln!("{}", buffer);
464+
eprintln!("{buffer}");
472465
}
473466
}
474467

@@ -516,10 +509,10 @@ fn main() {
516509
}
517510
}
518511

519-
eprintln!("Error: {}", err);
512+
eprintln!("Error: {err}");
520513
for (i, suberror) in err.chain().enumerate() {
521514
if i > 0 {
522-
eprintln!("Reason: {}", suberror);
515+
eprintln!("Reason: {suberror}");
523516
}
524517
}
525518
std::process::exit(1);

src/python_bindings/v3_11_0.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ where
4848
pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool {
4949
debug_assert!(index / 8 < core::mem::size_of::<Storage>());
5050
let byte_index = index / 8;
51-
let byte = unsafe {
52-
*(core::ptr::addr_of!((*this).storage) as *const u8).offset(byte_index as isize)
53-
};
51+
let byte = unsafe { *(core::ptr::addr_of!((*this).storage) as *const u8).add(byte_index) };
5452
Self::extract_bit(byte, index)
5553
}
5654
#[inline]
@@ -78,9 +76,7 @@ where
7876
pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) {
7977
debug_assert!(index / 8 < core::mem::size_of::<Storage>());
8078
let byte_index = index / 8;
81-
let byte = unsafe {
82-
(core::ptr::addr_of_mut!((*this).storage) as *mut u8).offset(byte_index as isize)
83-
};
79+
let byte = unsafe { (core::ptr::addr_of_mut!((*this).storage) as *mut u8).add(byte_index) };
8480
unsafe { *byte = Self::change_bit(*byte, index, val) };
8581
}
8682
#[inline]

src/python_bindings/v3_12_0.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ where
4848
pub unsafe fn raw_get_bit(this: *const Self, index: usize) -> bool {
4949
debug_assert!(index / 8 < core::mem::size_of::<Storage>());
5050
let byte_index = index / 8;
51-
let byte = unsafe {
52-
*(core::ptr::addr_of!((*this).storage) as *const u8).offset(byte_index as isize)
53-
};
51+
let byte = unsafe { *(core::ptr::addr_of!((*this).storage) as *const u8).add(byte_index) };
5452
Self::extract_bit(byte, index)
5553
}
5654
#[inline]
@@ -78,9 +76,7 @@ where
7876
pub unsafe fn raw_set_bit(this: *mut Self, index: usize, val: bool) {
7977
debug_assert!(index / 8 < core::mem::size_of::<Storage>());
8078
let byte_index = index / 8;
81-
let byte = unsafe {
82-
(core::ptr::addr_of_mut!((*this).storage) as *mut u8).offset(byte_index as isize)
83-
};
79+
let byte = unsafe { (core::ptr::addr_of_mut!((*this).storage) as *mut u8).add(byte_index) };
8480
unsafe { *byte = Self::change_bit(*byte, index, val) };
8581
}
8682
#[inline]

src/python_data_access.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,6 @@ pub fn copy_int<P: ProcessMemory>(process: &P, addr: usize) -> Result<i64, Error
142142
}
143143

144144
/// Allows iteration of a python dictionary. Only supports python 3.6+ right now
145-
146145
pub struct DictIterator<'a, P: 'a> {
147146
process: &'a P,
148147
entries_addr: usize,
@@ -386,7 +385,7 @@ where
386385
if value_type_name == "bool" {
387386
(if value > 0 { "True" } else { "False" }).to_owned()
388387
} else {
389-
format!("{}", value)
388+
format!("{value}")
390389
}
391390
};
392391

@@ -415,7 +414,7 @@ where
415414
if let Some((offset, _)) = value.char_indices().nth((max_length - 5) as usize) {
416415
format!("\"{}...\"", &value[..offset])
417416
} else {
418-
format!("\"{}\"", value)
417+
format!("\"{value}\"")
419418
}
420419
} else if flags & PY_TPFLAGS_DICT_SUBCLASS != 0 {
421420
if version.major == 3 && version.minor >= 6 {
@@ -430,7 +429,7 @@ where
430429
values.push("...".to_owned());
431430
break;
432431
}
433-
values.push(format!("{}: {}", key, value));
432+
values.push(format!("{key}: {value}"));
434433
}
435434
format!("{{{}}}", values.join(", "))
436435
} else {
@@ -488,10 +487,10 @@ where
488487
"numpy.int64" => format_obval::<i64, P>(addr, process)?,
489488
"numpy.float32" => format_obval::<f32, P>(addr, process)?,
490489
"numpy.float64" => format_obval::<f64, P>(addr, process)?,
491-
_ => format!("<{} at 0x{:x}>", value_type_name, addr),
490+
_ => format!("<{value_type_name} at 0x{addr:x}>"),
492491
}
493492
} else {
494-
format!("<{} at 0x{:x}>", value_type_name, addr)
493+
format!("<{value_type_name} at 0x{addr:x}>")
495494
};
496495

497496
Ok(formatted)
@@ -519,7 +518,7 @@ where
519518
let base_addr = addr as *mut u32;
520519
let offset = std::mem::size_of::<crate::python_bindings::v3_7_0::PyObject>() as isize;
521520
let result = unsafe { process.copy_pointer(base_addr.byte_offset(offset) as *const T)? };
522-
Ok(format!("{}", result))
521+
Ok(format!("{result}"))
523522
}
524523

525524
#[cfg(test)]

src/python_interpreters.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ impl CodeObject for v3_10_0::PyCodeObject {
723723
let mut bytecode_address: i32 = 0;
724724
while (i + 1) < size {
725725
let delta: u8 = table[i];
726-
let line_delta: i8 = unsafe { std::mem::transmute(table[i + 1]) };
726+
let line_delta: i8 = table[i + 1] as i8;
727727
i += 2;
728728

729729
if line_delta == -128 {

src/python_process_info.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -623,8 +623,8 @@ where
623623
..
624624
} => {
625625
let gil_ptr = interpreter_address + std::mem::offset_of!(v3_13_0::_is, ceval.gil);
626-
let gil = process.copy_struct::<usize>(gil_ptr)?;
627-
gil
626+
627+
process.copy_struct::<usize>(gil_ptr)?
628628
}
629629
Version {
630630
major: 3,
@@ -688,8 +688,7 @@ fn error_if_gil(config: &Config, version: &Version, msg: &str) -> Result<(), Err
688688
if !WARNED.load(std::sync::atomic::Ordering::Relaxed) {
689689
// only print this once
690690
eprintln!(
691-
"Cannot detect GIL holding in version '{}' on the current platform (reason: {})",
692-
version, msg
691+
"Cannot detect GIL holding in version '{version}' on the current platform (reason: {msg})"
693692
);
694693
eprintln!("Please open an issue in https://github.com/benfred/py-spy with the Python version and your platform.");
695694
WARNED.store(true, std::sync::atomic::Ordering::Relaxed);

0 commit comments

Comments
 (0)