Skip to content

Commit bb50ddf

Browse files
committed
Use str::strip_{prefix,suffix} when possible
1 parent 0cd7ff7 commit bb50ddf

File tree

41 files changed

+457
-421
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+457
-421
lines changed

src/bootstrap/compile.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -963,10 +963,11 @@ pub fn run_cargo(
963963
.collect::<Vec<_>>();
964964
for (prefix, extension, expected_len) in toplevel {
965965
let candidates = contents.iter().filter(|&&(_, ref filename, ref meta)| {
966-
filename.starts_with(&prefix[..])
967-
&& filename[prefix.len()..].starts_with('-')
968-
&& filename.ends_with(&extension[..])
969-
&& meta.len() == expected_len
966+
meta.len() == expected_len
967+
&& filename
968+
.strip_prefix(&prefix[..])
969+
.map(|s| s.starts_with('-') && s.ends_with(&extension[..]))
970+
.unwrap_or(false)
970971
});
971972
let max = candidates
972973
.max_by_key(|&&(_, _, ref metadata)| FileTime::from_last_modification_time(metadata));

src/bootstrap/doc.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -461,22 +461,21 @@ impl Step for Std {
461461

462462
builder.run(&mut cargo.into());
463463
};
464-
let krates = ["alloc", "core", "std", "proc_macro", "test"];
465-
for krate in &krates {
464+
static KRATES: &[&str] = &["alloc", "core", "std", "proc_macro", "test"];
465+
for krate in KRATES {
466466
run_cargo_rustdoc_for(krate);
467467
}
468468
builder.cp_r(&my_out, &out);
469469

470470
// Look for src/libstd, src/libcore etc in the `x.py doc` arguments and
471471
// open the corresponding rendered docs.
472472
for path in builder.paths.iter().map(components_simplified) {
473-
if path.get(0) == Some(&"src")
474-
&& path.get(1).map_or(false, |dir| dir.starts_with("lib"))
475-
{
476-
let requested_crate = &path[1][3..];
477-
if krates.contains(&requested_crate) {
478-
let index = out.join(requested_crate).join("index.html");
479-
open(builder, &index);
473+
if let ["src", path, ..] = path.as_slice() {
474+
if let Some(krate) = path.strip_prefix("lib") {
475+
if KRATES.contains(&krate) {
476+
let index = out.join(krate).join("index.html");
477+
open(builder, &index);
478+
}
480479
}
481480
}
482481
}

src/bootstrap/lib.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -436,10 +436,9 @@ impl Build {
436436
output(Command::new(&build.initial_rustc).arg("--version").arg("--verbose"));
437437
let local_release = local_version_verbose
438438
.lines()
439-
.filter(|x| x.starts_with("release:"))
439+
.filter_map(|x| x.strip_prefix("release:"))
440440
.next()
441441
.unwrap()
442-
.trim_start_matches("release:")
443442
.trim();
444443
let my_version = channel::CFG_RELEASE_NUM;
445444
if local_release.split('.').take(2).eq(my_version.split('.').take(2)) {
@@ -1089,10 +1088,10 @@ impl Build {
10891088
let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package));
10901089
let toml = t!(fs::read_to_string(&toml_file_name));
10911090
for line in toml.lines() {
1092-
let prefix = "version = \"";
1093-
let suffix = "\"";
1094-
if line.starts_with(prefix) && line.ends_with(suffix) {
1095-
return line[prefix.len()..line.len() - suffix.len()].to_string();
1091+
if let Some(stripped) =
1092+
line.strip_prefix("version = \"").and_then(|s| s.strip_suffix("\""))
1093+
{
1094+
return stripped.to_owned();
10961095
}
10971096
}
10981097

src/librustc_apfloat/ieee.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,21 +1191,24 @@ impl<S: Semantics> Float for IeeeFloat<S> {
11911191
}
11921192

11931193
// Handle a leading minus sign.
1194-
let minus = s.starts_with('-');
1195-
if minus || s.starts_with('+') {
1196-
s = &s[1..];
1197-
if s.is_empty() {
1198-
return Err(ParseError("String has no digits"));
1194+
let minus = {
1195+
let m = s.strip_prefix('-');
1196+
if let Some(remnant) = m.or_else(|| s.strip_prefix('+')) {
1197+
s = remnant;
1198+
if s.is_empty() {
1199+
return Err(ParseError("String has no digits"));
1200+
}
11991201
}
1200-
}
1202+
m.is_some()
1203+
};
12011204

12021205
// Adjust the rounding mode for the absolute value below.
12031206
if minus {
12041207
round = -round;
12051208
}
12061209

1207-
let r = if s.starts_with("0x") || s.starts_with("0X") {
1208-
s = &s[2..];
1210+
let r = if let Some(tail) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
1211+
s = tail;
12091212
if s.is_empty() {
12101213
return Err(ParseError("Invalid string"));
12111214
}

src/librustc_ast/util/comments.rs

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -29,27 +29,31 @@ pub struct Comment {
2929
}
3030

3131
pub fn is_line_doc_comment(s: &str) -> bool {
32-
let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
33-
|| s.starts_with("//!");
34-
debug!("is {:?} a doc comment? {}", s, res);
35-
res
32+
let yes = match s.as_bytes() {
33+
[b'/', b'/', b'/', c, ..] => *c != b'/',
34+
[b'/', b'/', b'/', ..] => true,
35+
[b'/', b'/', b'!', ..] => true,
36+
_ => false,
37+
};
38+
debug!("is {:?} a line doc comment? {}", s, yes);
39+
yes
3640
}
3741

3842
pub fn is_block_doc_comment(s: &str) -> bool {
39-
// Prevent `/**/` from being parsed as a doc comment
40-
let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
41-
|| s.starts_with("/*!"))
42-
&& s.len() >= 5;
43-
debug!("is {:?} a doc comment? {}", s, res);
44-
res
43+
// Previously, `/**/` was incorrectly regarded as a doc comment because it
44+
// starts with `/**` and ends with `*/`. However, this caused an ICE
45+
// because some code assumed that the length of a doc comment is at least 5.
46+
let yes = match s.as_bytes() {
47+
[b'/', b'*', b'*', c, _, ..] => *c != b'*',
48+
[b'/', b'*', b'!', _, _, ..] => true,
49+
_ => false,
50+
};
51+
debug!("is {:?} a block doc comment? {}", s, yes);
52+
yes
4553
}
4654

47-
// FIXME(#64197): Try to privatize this again.
4855
pub fn is_doc_comment(s: &str) -> bool {
49-
(s.starts_with("///") && is_line_doc_comment(s))
50-
|| s.starts_with("//!")
51-
|| (s.starts_with("/**") && is_block_doc_comment(s))
52-
|| s.starts_with("/*!")
56+
is_line_doc_comment(s) || is_block_doc_comment(s)
5357
}
5458

5559
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
@@ -127,22 +131,26 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String {
127131
const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
128132

129133
for prefix in ONELINERS {
130-
if comment.starts_with(*prefix) {
131-
return (&comment[prefix.len()..]).to_string();
134+
if let Some(tail) = comment.strip_prefix(*prefix) {
135+
return tail.to_owned();
132136
}
133137
}
134138

135-
if comment.starts_with("/*") {
136-
let lines =
137-
comment[3..comment.len() - 2].lines().map(|s| s.to_string()).collect::<Vec<String>>();
139+
match comment
140+
.strip_prefix("/**")
141+
.or_else(|| comment.strip_prefix("/*!"))
142+
.and_then(|s| s.strip_suffix("*/"))
143+
{
144+
Some(doc) => {
145+
let lines = doc.lines().map(|s| s.to_string()).collect::<Vec<String>>();
138146

139-
let lines = vertical_trim(lines);
140-
let lines = horizontal_trim(lines);
147+
let lines = vertical_trim(lines);
148+
let lines = horizontal_trim(lines);
141149

142-
return lines.join("\n");
150+
lines.join("\n")
151+
}
152+
_ => panic!("not a doc-comment: {}", comment),
143153
}
144-
145-
panic!("not a doc-comment: {}", comment);
146154
}
147155

148156
/// Returns `None` if the first `col` chars of `s` contain a non-whitespace char.

src/librustc_codegen_llvm/intrinsic.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,8 +1289,8 @@ fn generic_simd_intrinsic(
12891289
));
12901290
}
12911291

1292-
if name.starts_with("simd_shuffle") {
1293-
let n: u64 = name["simd_shuffle".len()..].parse().unwrap_or_else(|_| {
1292+
if let Some(tail) = name.strip_prefix("simd_shuffle") {
1293+
let n: u64 = tail.parse().unwrap_or_else(|_| {
12941294
span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?")
12951295
});
12961296

@@ -1307,7 +1307,7 @@ fn generic_simd_intrinsic(
13071307
require!(
13081308
in_elem == ret_ty.simd_type(tcx),
13091309
"expected return element type `{}` (element of input `{}`), \
1310-
found `{}` with element type `{}`",
1310+
found `{}` with element type `{}`",
13111311
in_elem,
13121312
in_ty,
13131313
ret_ty,

src/librustc_codegen_ssa/back/link.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1901,10 +1901,9 @@ fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
19011901

19021902
// Converts a library file-stem into a cc -l argument
19031903
fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1904-
if stem.starts_with("lib") && !config.target.options.is_like_windows {
1905-
&stem[3..]
1906-
} else {
1907-
stem
1904+
match stem.strip_prefix("lib") {
1905+
Some(tail) if !config.target.options.is_like_windows => tail,
1906+
_ => stem,
19081907
}
19091908
}
19101909

src/librustc_driver/args.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ use std::fs;
44
use std::io;
55

66
pub fn arg_expand(arg: String) -> Result<Vec<String>, Error> {
7-
if arg.starts_with('@') {
8-
let path = &arg[1..];
7+
if let Some(path) = arg.strip_prefix('@') {
98
let file = match fs::read_to_string(path) {
109
Ok(file) => file,
1110
Err(ref err) if err.kind() == io::ErrorKind::InvalidData => {

src/librustc_incremental/persist/fs.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -697,13 +697,13 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> {
697697
let lock_file_to_session_dir: FxHashMap<String, Option<String>> = lock_files
698698
.into_iter()
699699
.map(|lock_file_name| {
700-
assert!(lock_file_name.ends_with(LOCK_FILE_EXT));
701-
let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
702-
let session_dir = {
703-
let dir_prefix = &lock_file_name[0..dir_prefix_end];
704-
session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix))
705-
};
706-
(lock_file_name, session_dir.map(String::clone))
700+
if let Some(dir_prefix) = lock_file_name.strip_suffix(LOCK_FILE_EXT) {
701+
let dir =
702+
session_directories.iter().find(|dir_name| dir_name.starts_with(dir_prefix));
703+
(lock_file_name, dir.map(String::clone))
704+
} else {
705+
panic!("{:?} does not end with {}", lock_file_name, LOCK_FILE_EXT);
706+
}
707707
})
708708
.collect();
709709

src/librustc_llvm/build.rs

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::borrow::Cow;
12
use std::env;
23
use std::path::{Path, PathBuf};
34
use std::process::Command;
@@ -188,10 +189,8 @@ fn main() {
188189
cmd.args(&components);
189190

190191
for lib in output(&mut cmd).split_whitespace() {
191-
let name = if lib.starts_with("-l") {
192-
&lib[2..]
193-
} else if lib.starts_with('-') {
194-
&lib[1..]
192+
let name = if let Some(tail) = lib.strip_prefix("-l").or_else(|| lib.strip_prefix('-')) {
193+
tail
195194
} else if Path::new(lib).exists() {
196195
// On MSVC llvm-config will print the full name to libraries, but
197196
// we're only interested in the name part
@@ -227,18 +226,14 @@ fn main() {
227226
let mut cmd = Command::new(&llvm_config);
228227
cmd.arg(llvm_link_arg).arg("--ldflags");
229228
for lib in output(&mut cmd).split_whitespace() {
230-
if is_crossed {
231-
if lib.starts_with("-LIBPATH:") {
232-
println!("cargo:rustc-link-search=native={}", lib[9..].replace(&host, &target));
233-
} else if lib.starts_with("-L") {
234-
println!("cargo:rustc-link-search=native={}", lib[2..].replace(&host, &target));
235-
}
236-
} else if lib.starts_with("-LIBPATH:") {
237-
println!("cargo:rustc-link-search=native={}", &lib[9..]);
238-
} else if lib.starts_with("-l") {
239-
println!("cargo:rustc-link-lib={}", &lib[2..]);
240-
} else if lib.starts_with("-L") {
241-
println!("cargo:rustc-link-search=native={}", &lib[2..]);
229+
if let Some(tail) = lib.strip_prefix("-LIBPATH:").or_else(|| lib.strip_prefix("-L")) {
230+
let lib: Cow<'_, str> = match is_crossed {
231+
true => tail.replace(&host, &target).into(),
232+
false => tail.into(),
233+
};
234+
println!("cargo:rustc-link-search=native={}", lib);
235+
} else if let Some(tail) = lib.strip_prefix("-l") {
236+
println!("cargo:rustc-link-lib={}", tail);
242237
}
243238
}
244239

@@ -249,10 +244,10 @@ fn main() {
249244
let llvm_linker_flags = env::var_os("LLVM_LINKER_FLAGS");
250245
if let Some(s) = llvm_linker_flags {
251246
for lib in s.into_string().unwrap().split_whitespace() {
252-
if lib.starts_with("-l") {
253-
println!("cargo:rustc-link-lib={}", &lib[2..]);
254-
} else if lib.starts_with("-L") {
255-
println!("cargo:rustc-link-search=native={}", &lib[2..]);
247+
if let Some(tail) = lib.strip_prefix("-l") {
248+
println!("cargo:rustc-link-lib={}", tail);
249+
} else if let Some(tail) = lib.strip_prefix("-L") {
250+
println!("cargo:rustc-link-search=native={}", tail);
256251
}
257252
}
258253
}

src/librustc_metadata/locator.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -551,12 +551,18 @@ impl<'a> CrateLocator<'a> {
551551
None => return FileDoesntMatch,
552552
Some(file) => file,
553553
};
554-
let (hash, found_kind) = if file.starts_with(&rlib_prefix) && file.ends_with(".rlib") {
555-
(&file[(rlib_prefix.len())..(file.len() - ".rlib".len())], CrateFlavor::Rlib)
556-
} else if file.starts_with(&rlib_prefix) && file.ends_with(".rmeta") {
557-
(&file[(rlib_prefix.len())..(file.len() - ".rmeta".len())], CrateFlavor::Rmeta)
558-
} else if file.starts_with(&dylib_prefix) && file.ends_with(&dypair.1) {
559-
(&file[(dylib_prefix.len())..(file.len() - dypair.1.len())], CrateFlavor::Dylib)
554+
let (hash, found_kind) = if let Some(stripped) =
555+
file.strip_prefix(&rlib_prefix).and_then(|p| p.strip_suffix(".rlib"))
556+
{
557+
(stripped, CrateFlavor::Rlib)
558+
} else if let Some(stripped) =
559+
file.strip_prefix(&rlib_prefix).and_then(|p| p.strip_suffix(".rmeta"))
560+
{
561+
(stripped, CrateFlavor::Rmeta)
562+
} else if let Some(stripped) =
563+
file.strip_prefix(&dylib_prefix).and_then(|p| p.strip_suffix(&dypair.1))
564+
{
565+
(stripped, CrateFlavor::Dylib)
560566
} else {
561567
if file.starts_with(&staticlib_prefix) && file.ends_with(&staticpair.1) {
562568
staticlibs

src/librustc_mir/borrow_check/diagnostics/move_errors.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -488,14 +488,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
488488
{
489489
if let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span)
490490
{
491-
if pat_snippet.starts_with('&') {
492-
let pat_snippet = pat_snippet[1..].trim_start();
493-
let (suggestion, to_remove) = if pat_snippet.starts_with("mut")
494-
&& pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace)
495-
{
496-
(pat_snippet["mut".len()..].trim_start(), "&mut")
497-
} else {
498-
(pat_snippet, "&")
491+
if let Some(snippet) = pat_snippet.strip_prefix('&').map(str::trim_start) {
492+
let (suggestion, to_remove) = match snippet.strip_prefix("mut") {
493+
Some(tail) if tail.starts_with(rustc_lexer::is_whitespace) => {
494+
(tail.trim_start(), "&mut")
495+
}
496+
_ => (snippet, "&"),
499497
};
500498
suggestions.push((pat_span, to_remove, suggestion.to_owned()));
501499
}

0 commit comments

Comments
 (0)