Skip to content

Commit 8bd3231

Browse files
committed
Auto merge of #12631 - Eh2406:strip_prefix, r=epage
Ues strip_prefix for cleaner code ### What does this PR try to resolve? In #12629 (review) Ed pointed out how much cleaner the code can be using `strip_prefix`, so I found a bunch more places where we should be using it. ### How should we test and review this PR? Internal refactor and test still pass.
2 parents 4518131 + 2b28383 commit 8bd3231

File tree

12 files changed

+31
-33
lines changed

12 files changed

+31
-33
lines changed

Cargo.lock

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

crates/cargo-platform/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "cargo-platform"
3-
version = "0.1.4"
3+
version = "0.1.5"
44
edition.workspace = true
55
license.workspace = true
66
homepage = "https://github.com/rust-lang/cargo"

crates/cargo-platform/examples/matches.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ fn get_target() -> String {
3535
.expect("rustc failed to run");
3636
let stdout = String::from_utf8(output.stdout).unwrap();
3737
for line in stdout.lines() {
38-
if line.starts_with("host: ") {
39-
return String::from(&line[6..]);
38+
if let Some(line) = line.strip_prefix("host: ") {
39+
return String::from(line);
4040
}
4141
}
4242
panic!("Failed to find host: {}", stdout);

crates/cargo-platform/src/lib.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,7 @@ impl FromStr for Platform {
126126
type Err = ParseError;
127127

128128
fn from_str(s: &str) -> Result<Platform, ParseError> {
129-
if s.starts_with("cfg(") && s.ends_with(')') {
130-
let s = &s[4..s.len() - 1];
129+
if let Some(s) = s.strip_prefix("cfg(").and_then(|s| s.strip_suffix(')')) {
131130
s.parse().map(Platform::Cfg)
132131
} else {
133132
Platform::validate_named_platform(s)?;

crates/cargo-test-support/src/publish.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,11 @@ pub fn validate_crate_contents(
131131
(name, contents)
132132
})
133133
.collect();
134-
assert!(expected_crate_name.ends_with(".crate"));
135-
let base_crate_name = Path::new(&expected_crate_name[..expected_crate_name.len() - 6]);
134+
let base_crate_name = Path::new(
135+
expected_crate_name
136+
.strip_suffix(".crate")
137+
.expect("must end with .crate"),
138+
);
136139
let actual_files: HashSet<PathBuf> = files.keys().cloned().collect();
137140
let expected_files: HashSet<PathBuf> = expected_files
138141
.iter()

src/bin/cargo/main.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,17 +106,18 @@ fn list_commands(config: &Config) -> BTreeMap<String, CommandInfo> {
106106
};
107107
for entry in entries.filter_map(|e| e.ok()) {
108108
let path = entry.path();
109-
let filename = match path.file_name().and_then(|s| s.to_str()) {
110-
Some(filename) => filename,
111-
_ => continue,
109+
let Some(filename) = path.file_name().and_then(|s| s.to_str()) else {
110+
continue;
112111
};
113-
if !filename.starts_with(prefix) || !filename.ends_with(suffix) {
112+
let Some(name) = filename
113+
.strip_prefix(prefix)
114+
.and_then(|s| s.strip_suffix(suffix))
115+
else {
114116
continue;
115-
}
117+
};
116118
if is_executable(entry.path()) {
117-
let end = filename.len() - suffix.len();
118119
commands.insert(
119-
filename[prefix.len()..end].to_string(),
120+
name.to_string(),
120121
CommandInfo::External { path: path.clone() },
121122
);
122123
}

src/cargo/core/resolver/encode.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ impl EncodableResolve {
338338
let mut to_remove = Vec::new();
339339
for (k, v) in metadata.iter().filter(|p| p.0.starts_with(prefix)) {
340340
to_remove.push(k.to_string());
341-
let k = &k[prefix.len()..];
341+
let k = k.strip_prefix(prefix).unwrap();
342342
let enc_id: EncodablePackageId = k
343343
.parse()
344344
.with_context(|| internal("invalid encoding of checksum in lockfile"))?;
@@ -601,8 +601,8 @@ impl FromStr for EncodablePackageId {
601601
let version = s.next();
602602
let source_id = match s.next() {
603603
Some(s) => {
604-
if s.starts_with('(') && s.ends_with(')') {
605-
Some(SourceId::from_url(&s[1..s.len() - 1])?)
604+
if let Some(s) = s.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
605+
Some(SourceId::from_url(s)?)
606606
} else {
607607
anyhow::bail!("invalid serialized PackageId")
608608
}

src/cargo/util/config/de.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,8 @@ impl<'config> ConfigMapAccess<'config> {
216216
// `CARGO_PROFILE_DEV_PACKAGE_`
217217
let env_prefix = format!("{}_", de.key.as_env_key());
218218
for env_key in de.config.env_keys() {
219-
if env_key.starts_with(&env_prefix) {
220-
// `CARGO_PROFILE_DEV_PACKAGE_bar_OPT_LEVEL = 3`
221-
let rest = &env_key[env_prefix.len()..];
219+
// `CARGO_PROFILE_DEV_PACKAGE_bar_OPT_LEVEL = 3`
220+
if let Some(rest) = env_key.strip_prefix(&env_prefix) {
222221
// `rest = bar_OPT_LEVEL`
223222
let part = rest.splitn(2, '_').next().unwrap();
224223
// `part = "bar"`

src/cargo/util/rustc.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ impl Rustc {
6363
let extract = |field: &str| -> CargoResult<&str> {
6464
verbose_version
6565
.lines()
66-
.find(|l| l.starts_with(field))
67-
.map(|l| &l[field.len()..])
66+
.find_map(|l| l.strip_prefix(field))
6867
.ok_or_else(|| {
6968
anyhow::format_err!(
7069
"`rustc -vV` didn't have a line for `{}`, got:\n{}",

tests/testsuite/install.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2292,9 +2292,9 @@ fn failed_install_retains_temp_directory() {
22922292
.unwrap();
22932293

22942294
// Find the path in the output.
2295-
let start = stderr.find("found at `").unwrap() + 10;
2296-
let end = stderr[start..].find('.').unwrap() - 1;
2297-
let path = Path::new(&stderr[start..(end + start)]);
2295+
let stderr = stderr.split_once("found at `").unwrap().1;
2296+
let end = stderr.find('.').unwrap() - 1;
2297+
let path = Path::new(&stderr[..end]);
22982298
assert!(path.exists());
22992299
assert!(path.join("release/deps").exists());
23002300
}

tests/testsuite/lto.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -453,10 +453,8 @@ fn verify_lto(output: &Output, krate: &str, krate_info: &str, expected_lto: Lto)
453453
krate, krate_info, line, line2, stderr
454454
);
455455
}
456-
let actual_lto = if let Some(index) = line.find("-C lto=") {
457-
let s = &line[index..];
458-
let end = s.find(' ').unwrap();
459-
let mode = &line[index..index + end];
456+
let actual_lto = if let Some((_, line)) = line.split_once("-C lto=") {
457+
let mode = line.splitn(2, ' ').next().unwrap();
460458
if mode == "off" {
461459
Lto::Off
462460
} else {

tests/testsuite/ssh.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,9 @@ fn known_host_works() {
184184
// Validate the fingerprint while we're here.
185185
let fingerprint = stderr
186186
.lines()
187-
.find(|line| line.starts_with(" The ECDSA key fingerprint"))
187+
.find_map(|line| line.strip_prefix(" The ECDSA key fingerprint is: "))
188188
.unwrap()
189189
.trim();
190-
let fingerprint = &fingerprint[30..];
191190
let finger_out = sshd.exec(&["ssh-keygen", "-l", "-f", "/etc/ssh/ssh_host_ecdsa_key.pub"]);
192191
let gen_finger = std::str::from_utf8(&finger_out.stdout).unwrap();
193192
// <key-size> <fingerprint> <comments…>

0 commit comments

Comments
 (0)