Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use split_once for cleaner code #12615

Merged
merged 1 commit into from
Sep 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions crates/mdman/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,16 @@ fn process_args() -> Result<Options, Error> {
let man = args
.next()
.ok_or_else(|| format_err!("--man requires a value"))?;
let parts: Vec<_> = man.splitn(2, '=').collect();
let key_parts: Vec<_> = parts[0].splitn(2, ':').collect();
if parts.len() != 2 || key_parts.len() != 2 {
bail!("--man expected value with form name:1=link");
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old code errored on having too many = or : which the new code no longer does. Do we care?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't fully understand the format but we can keep the behavior the same for this refactor

let section: u8 = key_parts[1].parse().with_context(|| {
format!("expected unsigned integer for section, got `{}`", parts[1])
let parts = man.split_once('=').ok_or_else(|| {
anyhow::format_err!("--man expected value with form name:1=link")
})?;
let key_parts = parts.0.split_once(':').ok_or_else(|| {
anyhow::format_err!("--man expected value with form name:1=link")
})?;
let section: u8 = key_parts.1.parse().with_context(|| {
format!("expected unsigned integer for section, got `{}`", parts.1)
})?;
man_map.insert((key_parts[0].to_string(), section), parts[1].to_string());
man_map.insert((key_parts.0.to_string(), section), parts.1.to_string());
}
s => {
sources.push(PathBuf::from(s));
Expand Down
40 changes: 15 additions & 25 deletions src/cargo/core/compiler/custom_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,32 +681,24 @@ impl BuildOutput {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next() != Some("cargo") {
// skip this line since it doesn't start with "cargo:"
continue;
}
let data = match iter.next() {
Some(val) => {
let data = match line.split_once(':') {
Some(("cargo", val)) => {
if val.starts_with(":") {
// Line started with `cargo::`.
bail!("unsupported output in {}: `{}`\n\
bail!("unsupported output in {whence}: `{line}`\n\
Found a `cargo::key=value` build directive which is reserved for future use.\n\
Either change the directive to `cargo:key=value` syntax (note the single `:`) or upgrade your version of Rust.\n\
See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \
for more information about build script outputs.", whence, line);
for more information about build script outputs.");
}
val
}
None => continue,
_ => continue,
};

// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_end()),
let (key, value) = match data.split_once('=') {
Some((a,b)) => (a, b.trim_end()),
// Line started with `cargo:` but didn't match `key=value`.
_ => bail!("invalid output in {}: `{}`\n\
Expected a line with `cargo:key=value` with an `=` character, \
Expand Down Expand Up @@ -765,9 +757,7 @@ impl BuildOutput {
check_and_add_target!("bin", Target::is_bin, LinkArgTarget::Bin);
}
"rustc-link-arg-bin" => {
let mut parts = value.splitn(2, '=');
let bin_name = parts.next().unwrap().to_string();
let arg = parts.next().ok_or_else(|| {
let (bin_name, arg) = value.split_once('=').ok_or_else(|| {
anyhow::format_err!(
"invalid instruction `cargo:{}={}` from {}\n\
The instruction should have the form cargo:{}=BIN=ARG",
Expand All @@ -790,7 +780,10 @@ impl BuildOutput {
bin_name
);
}
linker_args.push((LinkArgTarget::SingleBin(bin_name), arg.to_string()));
linker_args.push((
LinkArgTarget::SingleBin(bin_name.to_owned()),
arg.to_string(),
));
}
"rustc-link-arg-tests" => {
check_and_add_target!("test", Target::is_test, LinkArgTarget::Test);
Expand Down Expand Up @@ -936,12 +929,9 @@ impl BuildOutput {
///
/// [`cargo:rustc-env`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-env
pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
let mut iter = value.splitn(2, '=');
let name = iter.next();
let val = iter.next();
match (name, val) {
(Some(n), Some(v)) => Ok((n.to_owned(), v.to_owned())),
_ => bail!("Variable rustc-env has no value in {}: {}", whence, value),
match value.split_once('=') {
Some((n, v)) => Ok((n.to_owned(), v.to_owned())),
_ => bail!("Variable rustc-env has no value in {whence}: {value}"),
}
}
}
Expand Down
16 changes: 3 additions & 13 deletions src/cargo/core/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,19 +634,9 @@ where
{
let mut search_path = vec![];
for dir in paths {
let dir = match dir.to_str() {
Some(s) => {
let mut parts = s.splitn(2, '=');
match (parts.next(), parts.next()) {
(Some("native"), Some(path))
| (Some("crate"), Some(path))
| (Some("dependency"), Some(path))
| (Some("framework"), Some(path))
| (Some("all"), Some(path)) => path.into(),
_ => dir.clone(),
}
}
None => dir.clone(),
let dir = match dir.to_str().and_then(|s| s.split_once("=")) {
Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => path.into(),
_ => dir.clone(),
};
if dir.starts_with(&root_output) {
search_path.push(dir);
Expand Down
28 changes: 12 additions & 16 deletions src/cargo/core/package_id_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,24 +123,20 @@ impl PackageIdSpec {
)
})?;
match frag {
Some(fragment) => {
let mut parts = fragment.splitn(2, [':', '@']);
let name_or_version = parts.next().unwrap();
match parts.next() {
Some(part) => {
let version = part.to_semver()?;
(InternedString::new(name_or_version), Some(version))
}
None => {
if name_or_version.chars().next().unwrap().is_alphabetic() {
(InternedString::new(name_or_version), None)
} else {
let version = name_or_version.to_semver()?;
(InternedString::new(path_name), Some(version))
}
Some(fragment) => match fragment.split_once([':', '@']) {
Some((name, part)) => {
let version = part.to_semver()?;
(InternedString::new(name), Some(version))
}
None => {
if fragment.chars().next().unwrap().is_alphabetic() {
(InternedString::new(&fragment), None)
} else {
let version = fragment.to_semver()?;
(InternedString::new(path_name), Some(version))
}
}
}
},
None => (InternedString::new(path_name), None),
}
};
Expand Down
6 changes: 2 additions & 4 deletions src/cargo/core/source/source_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,8 @@ impl SourceId {
/// 656c58fb7c5ef5f12bc747f");
/// ```
pub fn from_url(string: &str) -> CargoResult<SourceId> {
let mut parts = string.splitn(2, '+');
let kind = parts.next().unwrap();
let url = parts
.next()
let (kind, url) = string
.split_once('+')
.ok_or_else(|| anyhow::format_err!("invalid source `{}`", string))?;

match kind {
Expand Down
16 changes: 7 additions & 9 deletions src/cargo/sources/registry/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,15 +587,13 @@ impl<'cfg> RegistryIndex<'cfg> {
// `<pkg>=<p_req>o-><f_req>` where `<pkg>` is the name of a crate on
// this source, `<p_req>` is the version installed and `<f_req> is the
// version requested (argument to `--precise`).
let precise = match source_id.precise() {
Some(p) if p.starts_with(name) && p[name.len()..].starts_with('=') => {
let mut vers = p[name.len() + 1..].splitn(2, "->");
let current_vers = vers.next().unwrap().to_semver().unwrap();
let requested_vers = vers.next().unwrap().to_semver().unwrap();
Some((current_vers, requested_vers))
}
_ => None,
};
let precise = source_id
.precise()
.filter(|p| p.starts_with(name) && p[name.len()..].starts_with('='))
.map(|p| {
let (current, requested) = p[name.len() + 1..].split_once("->").unwrap();
(current.to_semver().unwrap(), requested.to_semver().unwrap())
});
let summaries = summaries.filter(|s| match &precise {
Some((current, requested)) => {
if req.matches(current) {
Expand Down