Skip to content

Commit 7fc2341

Browse files
authored
Merge pull request #168 from rust-embedded/fix-some-clippy-lints
Apply a number of clippy lints
2 parents d8e000b + 5855320 commit 7fc2341

File tree

3 files changed

+81
-77
lines changed

3 files changed

+81
-77
lines changed

src/lib.rs

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::borrow::ToOwned;
12
use std::io::{self, BufReader, Write};
23
use std::path::Path;
34
use std::process::{Command, Stdio};
@@ -74,7 +75,7 @@ impl Context {
7475

7576
/// Get a context structure from a provided target flag, used when cargo
7677
/// was not used to build the binary.
77-
fn from_flag(metadata: Metadata, target_flag: Option<&str>) -> Result<Self> {
78+
fn from_flag(metadata: &Metadata, target_flag: Option<&str>) -> Result<Self> {
7879
let host_target_name = rustc_version::version_meta()?.host;
7980

8081
// Get the "default" target override in .cargo/config.
@@ -100,7 +101,7 @@ impl Context {
100101
fn from_target_name(target_name: &str) -> Result<Self> {
101102
let cfg = Cfg::of(target_name)?;
102103

103-
Ok(Context {
104+
Ok(Self {
104105
cfg,
105106
target: target_name.to_string(),
106107
})
@@ -279,13 +280,13 @@ To see all the flags the proxied tool accepts run `cargo-{} -- --help`.{}",
279280
}
280281
}
281282

282-
fn get_metadata(tool: &Tool, matches: &ArgMatches) -> Result<Metadata> {
283+
fn get_metadata(tool: Tool, matches: &ArgMatches) -> Result<Metadata> {
283284
let mut metadata_command = MetadataCommand::new();
284285
metadata_command.no_deps();
285286
if tool.needs_build() {
286287
if let Some(features) = matches.get_many::<String>("features") {
287288
metadata_command.features(CargoOpt::SomeFeatures(
288-
features.map(|s| s.to_owned()).collect(),
289+
features.map(ToOwned::to_owned).collect(),
289290
));
290291
}
291292
if matches.get_flag("no-default-features") {
@@ -306,17 +307,17 @@ fn get_metadata(tool: &Tool, matches: &ArgMatches) -> Result<Metadata> {
306307
Ok(metadata)
307308
}
308309

309-
pub fn run(tool: Tool, matches: ArgMatches) -> Result<i32> {
310+
pub fn run(tool: Tool, matches: &ArgMatches) -> Result<i32> {
310311
let mut tool_args = vec![];
311312
if let Some(args) = matches.get_many::<String>("args") {
312-
tool_args.extend(args.map(|s| s.as_str()));
313+
tool_args.extend(args.map(String::as_str));
313314
}
314315

315316
let tool_help = tool_args.first() == Some(&"--help");
316317

317318
let target_artifact = if tool.needs_build() && !tool_help {
318-
let metadata = get_metadata(&tool, &matches)?;
319-
cargo_build(&matches, &metadata)?.map(|a| (a, metadata))
319+
let metadata = get_metadata(tool, matches)?;
320+
cargo_build(matches, &metadata)?.map(|a| (a, metadata))
320321
} else {
321322
None
322323
};
@@ -328,8 +329,8 @@ pub fn run(tool: Tool, matches: ArgMatches) -> Result<i32> {
328329
Context::from_artifact(metadata, artifact)?
329330
} else {
330331
Context::from_flag(
331-
get_metadata(&tool, &matches)?,
332-
matches.get_one::<String>("target").map(|s| s.as_str()),
332+
&get_metadata(tool, matches)?,
333+
matches.get_one::<String>("target").map(String::as_str),
333334
)?
334335
};
335336

@@ -345,7 +346,7 @@ pub fn run(tool: Tool, matches: ArgMatches) -> Result<i32> {
345346
}
346347

347348
// Extra flags
348-
if let Tool::Readobj = tool {
349+
if tool == Tool::Readobj {
349350
// The default output style of `readobj` is JSON-like, which is not user friendly, so we
350351
// change it to the human readable GNU style
351352
lltool.arg("--elf-output-style=GNU");
@@ -354,23 +355,23 @@ pub fn run(tool: Tool, matches: ArgMatches) -> Result<i32> {
354355
if tool.needs_build() {
355356
// Artifact
356357
if let Some((artifact, _)) = &target_artifact {
357-
let file = match &artifact.executable {
358-
// Example and bins have an executable
359-
Some(val) => val,
360-
// Libs have an rlib and an rmeta. We want the rlib, which always
361-
// comes first in the filenames array after some quick testing.
362-
//
363-
// We could instead look for files ending in .rlib, but that would
364-
// fail for cdylib and other fancy crate kinds.
365-
None => &artifact.filenames[0],
366-
};
358+
// Example and bins have an executable while libs have an rlib and an rmeta. We
359+
// want the rlib, which always comes first in the filenames array after some quick
360+
// testing.
361+
//
362+
// We could instead look for files ending in .rlib, but that would
363+
// fail for cdylib and other fancy crate kinds.
364+
let file = artifact
365+
.executable
366+
.as_ref()
367+
.map_or_else(|| &artifact.filenames[0], |val| val);
367368

368369
match tool {
369370
// Tools that don't need a build
370371
Tool::Ar | Tool::As | Tool::Cov | Tool::Lld | Tool::Profdata => {}
371372
// for some tools we change the CWD (current working directory) and
372373
// make the artifact path relative. This makes the path that the
373-
// tool will print easier to read. e.g. `libfoo.rlib` instead of
374+
// tool will print easier to read. eg. `libfoo.rlib` instead of
374375
// `/home/user/rust/project/target/$T/debug/libfoo.rlib`.
375376
Tool::Objdump | Tool::Nm | Tool::Readobj | Tool::Size => {
376377
lltool
@@ -551,7 +552,7 @@ fn cargo_build_args<'a>(matches: &'a ArgMatches, cargo: &mut Command) -> (BuildT
551552
cargo.args(["--target", target]);
552553
}
553554

554-
let verbose = matches.get_count("verbose") as u64;
555+
let verbose = u64::from(matches.get_count("verbose"));
555556
if verbose > 1 {
556557
cargo.arg(format!("-{}", "v".repeat((verbose - 1) as usize)));
557558
}

src/postprocess.rs

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -10,49 +10,49 @@ use regex::{Captures, Regex};
1010
pub fn demangle(bytes: &[u8]) -> Cow<'_, [u8]> {
1111
let re = Regex::new(r"_Z.+?E\b").expect("BUG: Malformed Regex");
1212

13-
if let Ok(text) = str::from_utf8(bytes) {
14-
match re.replace_all(text, |cs: &Captures<'_>| {
13+
str::from_utf8(bytes).map_or_else(
14+
|_| bytes.into(),
15+
|text| match re.replace_all(text, |cs: &Captures<'_>| {
1516
format!("{}", rustc_demangle::demangle(cs.get(0).unwrap().as_str()))
1617
}) {
1718
Cow::Borrowed(s) => s.as_bytes().into(),
1819
Cow::Owned(s) => s.into_bytes().into(),
19-
}
20-
} else {
21-
bytes.into()
22-
}
20+
},
21+
)
2322
}
2423

2524
// This pass turns the addresses in the output of `size -A` into hexadecimal format
2625
pub fn size(bytes: &[u8]) -> Cow<'_, [u8]> {
27-
if let Ok(text) = str::from_utf8(bytes) {
28-
let mut s = text
29-
.lines()
30-
.map(|line| -> Cow<'_, str> {
31-
match line
32-
.split_whitespace()
33-
.nth(2)
34-
.and_then(|part| part.parse::<u64>().ok().map(|addr| (part, addr)))
35-
{
36-
// the lines to postprocess have the form ".section_name 100 1024" where
37-
// the second number is the address
38-
Some((needle, addr)) if line.starts_with('.') => {
39-
let pos = line.rfind(needle).unwrap();
40-
let hex_addr = format!("{addr:#x}");
41-
let start = pos + needle.len() - hex_addr.len();
42-
43-
format!("{}{}", &line[..start], hex_addr).into()
26+
str::from_utf8(bytes).map_or_else(
27+
|_| bytes.into(),
28+
|text| {
29+
let mut s = text
30+
.lines()
31+
.map(|line| -> Cow<'_, str> {
32+
match line
33+
.split_whitespace()
34+
.nth(2)
35+
.and_then(|part| part.parse::<u64>().ok().map(|addr| (part, addr)))
36+
{
37+
// the lines to postprocess have the form ".section_name 100 1024" where
38+
// the second number is the address
39+
Some((needle, addr)) if line.starts_with('.') => {
40+
let pos = line.rfind(needle).unwrap();
41+
let hex_addr = format!("{addr:#x}");
42+
let start = pos + needle.len() - hex_addr.len();
43+
44+
format!("{}{}", &line[..start], hex_addr).into()
45+
}
46+
_ => line.into(),
4447
}
45-
_ => line.into(),
46-
}
47-
})
48-
.collect::<Vec<_>>()
49-
.join("\n");
50-
51-
// `text.lines()` loses the trailing newline so we restore it here
52-
s.push('\n');
53-
54-
s.into_bytes().into()
55-
} else {
56-
bytes.into()
57-
}
48+
})
49+
.collect::<Vec<_>>()
50+
.join("\n");
51+
52+
// `text.lines()` loses the trailing newline so we restore it here
53+
s.push('\n');
54+
55+
s.into_bytes().into()
56+
},
57+
)
5858
}

src/tool.rs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,25 +23,27 @@ pub enum Tool {
2323
}
2424

2525
impl Tool {
26-
pub fn name(self) -> &'static str {
26+
#[must_use]
27+
pub const fn name(self) -> &'static str {
2728
match self {
28-
Tool::Ar => "ar",
29-
Tool::As => "as",
30-
Tool::Cov => "cov",
31-
Tool::Lld => "lld",
32-
Tool::Nm => "nm",
33-
Tool::Objcopy => "objcopy",
34-
Tool::Objdump => "objdump",
35-
Tool::Profdata => "profdata",
36-
Tool::Readobj => "readobj",
37-
Tool::Size => "size",
38-
Tool::Strip => "strip",
29+
Self::Ar => "ar",
30+
Self::As => "as",
31+
Self::Cov => "cov",
32+
Self::Lld => "lld",
33+
Self::Nm => "nm",
34+
Self::Objcopy => "objcopy",
35+
Self::Objdump => "objdump",
36+
Self::Profdata => "profdata",
37+
Self::Readobj => "readobj",
38+
Self::Size => "size",
39+
Self::Strip => "strip",
3940
}
4041
}
4142

43+
#[must_use]
4244
pub fn exe(self) -> String {
4345
match self {
44-
Tool::Lld => format!("rust-lld{EXE_SUFFIX}"),
46+
Self::Lld => format!("rust-lld{EXE_SUFFIX}"),
4547
_ => format!("llvm-{}{}", self.name(), EXE_SUFFIX),
4648
}
4749
}
@@ -71,7 +73,7 @@ impl Tool {
7173
path.to_string_lossy()
7274
);
7375
process::exit(102)
74-
};
76+
}
7577

7678
// Note: The first argument is the name of the binary (e.g. `rust-nm`)
7779
let args = env::args().skip(1);
@@ -96,7 +98,7 @@ impl Tool {
9698
pub fn cargo_exec(self, examples: Option<&str>) -> ! {
9799
let matches = crate::args(self, examples);
98100

99-
match crate::run(self, matches) {
101+
match crate::run(self, &matches) {
100102
Err(e) => {
101103
eprintln!("error: {e}");
102104
process::exit(101)
@@ -106,10 +108,11 @@ impl Tool {
106108
}
107109

108110
// Whether this tool requires the project to be previously built
109-
pub fn needs_build(self) -> bool {
111+
#[must_use]
112+
pub const fn needs_build(self) -> bool {
110113
match self {
111-
Tool::Ar | Tool::As | Tool::Cov | Tool::Lld | Tool::Profdata => false,
112-
Tool::Nm | Tool::Objcopy | Tool::Objdump | Tool::Readobj | Tool::Size | Tool::Strip => {
114+
Self::Ar | Self::As | Self::Cov | Self::Lld | Self::Profdata => false,
115+
Self::Nm | Self::Objcopy | Self::Objdump | Self::Readobj | Self::Size | Self::Strip => {
113116
true
114117
}
115118
}

0 commit comments

Comments
 (0)