Auto merge of #11130 - Muscraft:use-ready-macro, r=Eh2406

switch to `std::task::ready!()` where possible

In Rust 1.64.0, [`std::task::ready`](https://doc.rust-lang.org/stable/std/task/macro.ready.html) was [stabilized](https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html#stabilized-apis). Using `ready!()` can make what is happening clearer in the code as it expands to roughly:
```rust
let num = match fut.poll(cx) {
    Poll::Ready(t) => t,
    Poll::Pending => return Poll::Pending,
};
```
This PR replaces places using `Poll::Pending => return Poll::Pending`  with `ready!()` where appropriate.

I was unsure about how useful the new macro would be in one place in [`cargo/registry/index.rs`](247ca7fd04/src/cargo/sources/registry/index.rs (L425-L429)), so I left it out and will add it in if needed.

Close #11128

r? `@Eh2406`
This commit is contained in:
bors 2022-09-22 19:29:20 +00:00
commit dbd1c18379
4 changed files with 44 additions and 76 deletions

View File

@ -1,5 +1,5 @@
use std::collections::{HashMap, HashSet};
use std::task::Poll;
use std::task::{ready, Poll};
use crate::core::PackageSet;
use crate::core::{Dependency, PackageId, QueryKind, Source, SourceId, SourceMap, Summary};
@ -482,10 +482,7 @@ impl<'cfg> PackageRegistry<'cfg> {
for &s in self.overrides.iter() {
let src = self.sources.get_mut(s).unwrap();
let dep = Dependency::new_override(dep.package_name(), s);
let mut results = match src.query_vec(&dep, QueryKind::Exact) {
Poll::Ready(results) => results?,
Poll::Pending => return Poll::Pending,
};
let mut results = ready!(src.query_vec(&dep, QueryKind::Exact))?;
if !results.is_empty() {
return Poll::Ready(Ok(Some(results.remove(0))));
}
@ -580,10 +577,7 @@ impl<'cfg> Registry for PackageRegistry<'cfg> {
assert!(self.patches_locked);
let (override_summary, n, to_warn) = {
// Look for an override and get ready to query the real source.
let override_summary = match self.query_overrides(dep) {
Poll::Ready(override_summary) => override_summary?,
Poll::Pending => return Poll::Pending,
};
let override_summary = ready!(self.query_overrides(dep))?;
// Next up on our list of candidates is to check the `[patch]`
// section of the manifest. Here we look through all patches
@ -880,23 +874,17 @@ fn summary_for_patch(
// No summaries found, try to help the user figure out what is wrong.
if let Some(locked) = locked {
// Since the locked patch did not match anything, try the unlocked one.
let orig_matches = match source.query_vec(orig_patch, QueryKind::Exact) {
Poll::Pending => return Poll::Pending,
Poll::Ready(deps) => deps,
}
.unwrap_or_else(|e| {
log::warn!(
"could not determine unlocked summaries for dep {:?}: {:?}",
orig_patch,
e
);
Vec::new()
});
let orig_matches =
ready!(source.query_vec(orig_patch, QueryKind::Exact)).unwrap_or_else(|e| {
log::warn!(
"could not determine unlocked summaries for dep {:?}: {:?}",
orig_patch,
e
);
Vec::new()
});
let summary = match summary_for_patch(orig_patch, &None, orig_matches, source) {
Poll::Pending => return Poll::Pending,
Poll::Ready(summary) => summary?,
};
let summary = ready!(summary_for_patch(orig_patch, &None, orig_matches, source))?;
// The unlocked version found a match. This returns a value to
// indicate that this entry should be unlocked.
@ -905,18 +893,15 @@ fn summary_for_patch(
// Try checking if there are *any* packages that match this by name.
let name_only_dep = Dependency::new_override(orig_patch.package_name(), orig_patch.source_id());
let name_summaries = match source.query_vec(&name_only_dep, QueryKind::Exact) {
Poll::Pending => return Poll::Pending,
Poll::Ready(deps) => deps,
}
.unwrap_or_else(|e| {
log::warn!(
"failed to do name-only summary query for {:?}: {:?}",
name_only_dep,
e
);
Vec::new()
});
let name_summaries =
ready!(source.query_vec(&name_only_dep, QueryKind::Exact)).unwrap_or_else(|e| {
log::warn!(
"failed to do name-only summary query for {:?}: {:?}",
name_only_dep,
e
);
Vec::new()
});
let mut vers = name_summaries
.iter()
.map(|summary| summary.version())

View File

@ -19,7 +19,7 @@ use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::str;
use std::task::Poll;
use std::task::{ready, Poll};
use std::time::Duration;
use url::Url;
@ -383,10 +383,7 @@ impl<'cfg> RegistryData for HttpRegistry<'cfg> {
// Load the registry config.
if self.registry_config.is_none() && path != Path::new("config.json") {
match self.config()? {
Poll::Ready(_) => {}
Poll::Pending => return Poll::Pending,
}
ready!(self.config()?);
}
let mut handle = ops::http_handle(self.config)?;
@ -515,11 +512,11 @@ impl<'cfg> RegistryData for HttpRegistry<'cfg> {
}
}
match self.load(Path::new(""), Path::new("config.json"), None)? {
Poll::Ready(LoadResponse::Data {
match ready!(self.load(Path::new(""), Path::new("config.json"), None)?) {
LoadResponse::Data {
raw_data,
index_version: _,
}) => {
} => {
trace!("config loaded");
self.registry_config = Some(serde_json::from_slice(&raw_data)?);
if paths::create_dir_all(&config_json_path.parent().unwrap()).is_ok() {
@ -529,13 +526,12 @@ impl<'cfg> RegistryData for HttpRegistry<'cfg> {
}
Poll::Ready(Ok(self.registry_config.clone()))
}
Poll::Ready(LoadResponse::NotFound) => {
LoadResponse::NotFound => {
Poll::Ready(Err(anyhow::anyhow!("config.json not found in registry")))
}
Poll::Ready(LoadResponse::CacheValid) => {
LoadResponse::CacheValid => {
panic!("config.json is not stored in the index cache")
}
Poll::Pending => Poll::Pending,
}
}

View File

@ -80,7 +80,7 @@ use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::str;
use std::task::Poll;
use std::task::{ready, Poll};
/// Crates.io treats hyphen and underscores as interchangeable, but the index and old Cargo do not.
/// Therefore, the index must store uncanonicalized version of the name so old Cargo's can find it.
@ -268,10 +268,7 @@ impl<'cfg> RegistryIndex<'cfg> {
pub fn hash(&mut self, pkg: PackageId, load: &mut dyn RegistryData) -> Poll<CargoResult<&str>> {
let req = OptVersionReq::exact(pkg.version());
let summary = self.summaries(pkg.name(), &req, load)?;
let summary = match summary {
Poll::Ready(mut summary) => summary.next(),
Poll::Pending => return Poll::Pending,
};
let summary = ready!(summary).next();
Poll::Ready(Ok(summary
.ok_or_else(|| internal(format!("no hash listed for {}", pkg)))?
.summary
@ -302,10 +299,7 @@ impl<'cfg> RegistryIndex<'cfg> {
// has run previously this will parse a Cargo-specific cache file rather
// than the registry itself. In effect this is intended to be a quite
// cheap operation.
let summaries = match self.load_summaries(name, load)? {
Poll::Ready(summaries) => summaries,
Poll::Pending => return Poll::Pending,
};
let summaries = ready!(self.load_summaries(name, load)?);
// Iterate over our summaries, extract all relevant ones which match our
// version requirement, and then parse all corresponding rows in the
@ -422,12 +416,9 @@ impl<'cfg> RegistryIndex<'cfg> {
f: &mut dyn FnMut(Summary),
) -> Poll<CargoResult<()>> {
if self.config.offline() {
match self.query_inner_with_online(dep, load, yanked_whitelist, f, false)? {
Poll::Ready(0) => {}
Poll::Ready(_) => return Poll::Ready(Ok(())),
Poll::Pending => return Poll::Pending,
}
// If offline, and there are no matches, try again with online.
// This should only return `Poll::Ready(Ok(()))` if there is at least 1 match.
//
// If there are 0 matches it should fall through and try again with online.
// This is necessary for dependencies that are not used (such as
// target-cfg or optional), but are not downloaded. Normally the
// build should succeed if they are not downloaded and not used,
@ -435,6 +426,9 @@ impl<'cfg> RegistryIndex<'cfg> {
// then cargo will fail to download and an error message
// indicating that the required dependency is unavailable while
// offline will be displayed.
if ready!(self.query_inner_with_online(dep, load, yanked_whitelist, f, false)?) > 0 {
return Poll::Ready(Ok(()));
}
}
self.query_inner_with_online(dep, load, yanked_whitelist, f, true)
.map_ok(|_| ())
@ -450,10 +444,7 @@ impl<'cfg> RegistryIndex<'cfg> {
) -> Poll<CargoResult<usize>> {
let source_id = self.source_id;
let summaries = match self.summaries(dep.package_name(), dep.version_req(), load)? {
Poll::Ready(summaries) => summaries,
Poll::Pending => return Poll::Pending,
};
let summaries = ready!(self.summaries(dep.package_name(), dep.version_req(), load))?;
let summaries = summaries
// First filter summaries for `--offline`. If we're online then
@ -582,10 +573,7 @@ impl Summaries {
Err(e) => log::debug!("cache missing for {:?} error: {}", relative, e),
}
let response = match load.load(root, relative, index_version.as_deref())? {
Poll::Pending => return Poll::Pending,
Poll::Ready(response) => response,
};
let response = ready!(load.load(root, relative, index_version.as_deref())?);
match response {
LoadResponse::CacheValid => {

View File

@ -15,7 +15,7 @@ use std::fs::File;
use std::mem;
use std::path::Path;
use std::str;
use std::task::Poll;
use std::task::{ready, Poll};
/// A remote registry is a registry that lives at a remote URL (such as
/// crates.io). The git index is cloned locally, and `.crate` files are
@ -236,13 +236,12 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> {
debug!("loading config");
self.prepare()?;
self.config.assert_package_cache_locked(&self.index_path);
match self.load(Path::new(""), Path::new("config.json"), None)? {
Poll::Ready(LoadResponse::Data { raw_data, .. }) => {
match ready!(self.load(Path::new(""), Path::new("config.json"), None)?) {
LoadResponse::Data { raw_data, .. } => {
trace!("config loaded");
Poll::Ready(Ok(Some(serde_json::from_slice(&raw_data)?)))
}
Poll::Ready(_) => Poll::Ready(Ok(None)),
Poll::Pending => Poll::Pending,
_ => Poll::Ready(Ok(None)),
}
}