deglob some enums, use concise iteration syntax

This commit is contained in:
Daniel Eades 2021-11-25 12:39:52 +00:00
parent fbf72fd5af
commit 052f51ff71
15 changed files with 68 additions and 80 deletions

View File

@ -214,7 +214,7 @@ impl TorClientConfig {
dircfg.network_config(self.tor_network.clone());
dircfg.schedule_config(self.download_schedule.clone());
dircfg.cache_path(self.storage.expand_cache_dir()?);
for (k, v) in self.override_net_params.iter() {
for (k, v) in &self.override_net_params {
dircfg.override_net_param(k.clone(), *v);
}
dircfg.build()

View File

@ -67,7 +67,7 @@ impl CmdLine {
/// Compose elements of this cmdline into a single toml string.
fn build_toml(&self) -> String {
let mut toml_s = String::new();
for line in self.contents.iter() {
for line in &self.contents {
toml_s.push_str(tweak_toml_bareword(line).as_ref().unwrap_or(line));
toml_s.push('\n');
}

View File

@ -246,7 +246,7 @@ impl<E: Display> Display for RetryError<E> {
self.doing, n
)?;
for (attempt, e) in self.errors.iter() {
for (attempt, e) in &self.errors {
write!(f, "\n{}: {}", attempt, e)?;
}
Ok(())

View File

@ -644,7 +644,7 @@ impl Body for Netinfo {
.try_into()
.expect("Too many addrs in netinfo cell");
w.write_u8(n_addrs);
for addr in self.my_addr.iter() {
for addr in &self.my_addr {
enc_one_netinfo_addr(w, addr);
}
}
@ -732,7 +732,7 @@ impl Body for Versions {
ChanMsg::Versions(self)
}
fn write_body_onto<W: Writer + ?Sized>(self, w: &mut W) {
for v in self.versions.iter() {
for v in &self.versions {
w.write_u16(*v);
}
}
@ -907,7 +907,7 @@ impl Body for Certs {
.try_into()
.expect("Too many certs to encode in cell.");
w.write_u8(n_certs);
for c in self.certs.iter() {
for c in &self.certs {
enc_one_tor_cert(w, c)
}
}
@ -964,7 +964,7 @@ impl Body for AuthChallenge {
w.write_all(&self.challenge[..]);
assert!(self.methods.len() <= std::u16::MAX as usize);
w.write_u16(self.methods.len() as u16);
for m in self.methods.iter() {
for m in &self.methods {
w.write_u16(*m);
}
}

View File

@ -789,7 +789,7 @@ impl Body for Extend2 {
fn encode_onto(self, w: &mut Vec<u8>) {
let n_linkspecs: u8 = self.linkspec.len().try_into().expect("Too many linkspecs");
w.write_u8(n_linkspecs);
for ls in self.linkspec.iter() {
for ls in &self.linkspec {
w.write(ls);
}
w.write_u16(self.handshake_type);
@ -971,53 +971,51 @@ impl Readable for ResolvedVal {
return Err(Error::BadMessage("Wrong length for RESOLVED answer"));
}
}
use ResolvedVal::*;
Ok(match tp {
RES_HOSTNAME => Hostname(r.take(len)?.into()),
RES_IPV4 => Ip(IpAddr::V4(r.extract()?)),
RES_IPV6 => Ip(IpAddr::V6(r.extract()?)),
RES_HOSTNAME => Self::Hostname(r.take(len)?.into()),
RES_IPV4 => Self::Ip(IpAddr::V4(r.extract()?)),
RES_IPV6 => Self::Ip(IpAddr::V6(r.extract()?)),
RES_ERR_TRANSIENT => {
r.advance(len)?;
TransientError
Self::TransientError
}
RES_ERR_NONTRANSIENT => {
r.advance(len)?;
NontransientError
Self::NontransientError
}
_ => Unrecognized(tp, r.take(len)?.into()),
_ => Self::Unrecognized(tp, r.take(len)?.into()),
})
}
}
impl Writeable for ResolvedVal {
fn write_onto<B: Writer + ?Sized>(&self, w: &mut B) {
use ResolvedVal::*;
match self {
Hostname(h) => {
Self::Hostname(h) => {
w.write_u8(RES_HOSTNAME);
let h_len: u8 = h.len().try_into().expect("Hostname too long");
w.write_u8(h_len);
w.write_all(&h[..]);
}
Ip(IpAddr::V4(a)) => {
Self::Ip(IpAddr::V4(a)) => {
w.write_u8(RES_IPV4);
w.write_u8(4); // length
w.write(a);
}
Ip(IpAddr::V6(a)) => {
Self::Ip(IpAddr::V6(a)) => {
w.write_u8(RES_IPV6);
w.write_u8(16); // length
w.write(a);
}
TransientError => {
Self::TransientError => {
w.write_u8(RES_ERR_TRANSIENT);
w.write_u8(0); // length
}
NontransientError => {
Self::NontransientError => {
w.write_u8(RES_ERR_NONTRANSIENT);
w.write_u8(0); // length
}
Unrecognized(tp, v) => {
Self::Unrecognized(tp, v) => {
w.write_u8(*tp);
let v_len: u8 = v
.len()
@ -1090,7 +1088,7 @@ impl Body for Resolved {
Ok(Resolved { answers })
}
fn encode_onto(self, w: &mut Vec<u8>) {
for (rv, ttl) in self.answers.iter() {
for (rv, ttl) in &self.answers {
w.write(rv);
w.write_u32(*ttl);
}

View File

@ -786,7 +786,7 @@ impl<B: AbstractCircBuilder + 'static, R: Runtime> AbstractCircMgr<B, R> {
// all have failed)
let best = PendingEntry::find_best(&pending, usage);
if restrict_circ {
for item in best.iter() {
for item in &best {
// TODO: Do we want to tentatively restrict _all_ of these?
// not clear to me.
item.tentative_restrict_mut(usage)?;

View File

@ -92,6 +92,7 @@ mod test {
#[derive(derive_builder::Builder, Debug)]
#[builder(build_fn(error = "ConfigBuildError"))]
#[allow(dead_code)]
struct Cephalopod {
// arms have suction cups for their whole length
arms: u8,

View File

@ -221,19 +221,18 @@ impl<'a> DiffCommand<'a> {
/// implementation is potentially O(n) in the size of the input.
#[cfg(any(test, fuzzing, feature = "slow-diff-apply"))]
fn apply_to(&self, target: &mut DiffResult<'a>) -> Result<()> {
use DiffCommand::*;
match self {
Delete { low, high } => {
Self::Delete { low, high } => {
target.remove_lines(*low, *high)?;
}
DeleteToEnd { low } => {
Self::DeleteToEnd { low } => {
target.remove_lines(*low, target.lines.len())?;
}
Replace { low, high, lines } => {
Self::Replace { low, high, lines } => {
target.remove_lines(*low, *high)?;
target.insert_at(*low, lines)?;
}
Insert { pos, lines } => {
Self::Insert { pos, lines } => {
// This '+1' seems off, but it's what the spec says. I wonder
// if the spec is wrong.
target.insert_at(*pos + 1, lines)?;
@ -295,10 +294,8 @@ impl<'a> DiffCommand<'a> {
/// Return the lines that we should add to the output
fn lines(&self) -> Option<&[&'a str]> {
use DiffCommand::*;
match self {
Replace { lines, .. } => Some(lines.as_slice()),
Insert { lines, .. } => Some(lines.as_slice()),
Self::Replace { lines, .. } | Self::Insert { lines, .. } => Some(lines.as_slice()),
_ => None,
}
}
@ -306,10 +303,8 @@ impl<'a> DiffCommand<'a> {
/// Return a mutable reference to the vector of lines we should
/// add to the output.
fn linebuf_mut(&mut self) -> Option<&mut Vec<&'a str>> {
use DiffCommand::*;
match self {
Replace { ref mut lines, .. } => Some(lines),
Insert { ref mut lines, .. } => Some(lines),
Self::Replace { ref mut lines, .. } | Self::Insert { ref mut lines, .. } => Some(lines),
_ => None,
}
}
@ -319,12 +314,10 @@ impl<'a> DiffCommand<'a> {
///
/// We use this line number to know which lines we should copy.
fn following_lines(&self) -> Option<usize> {
use DiffCommand::*;
match self {
Delete { high, .. } => Some(high + 1),
DeleteToEnd { .. } => None,
Replace { high, .. } => Some(high + 1),
Insert { pos, .. } => Some(pos + 1),
Self::Delete { high, .. } | Self::Replace { high, .. } => Some(high + 1),
Self::DeleteToEnd { .. } => None,
Self::Insert { pos, .. } => Some(pos + 1),
}
}
@ -334,18 +327,17 @@ impl<'a> DiffCommand<'a> {
/// This can be the same as following_lines(), if we shouldn't
/// actually remove any lines.
fn first_removed_line(&self) -> usize {
use DiffCommand::*;
match self {
Delete { low, .. } => *low,
DeleteToEnd { low } => *low,
Replace { low, .. } => *low,
Insert { pos, .. } => *pos + 1,
Self::Delete { low, .. } => *low,
Self::DeleteToEnd { low } => *low,
Self::Replace { low, .. } => *low,
Self::Insert { pos, .. } => *pos + 1,
}
}
/// Return true if this is an Insert command.
fn is_insert(&self) -> bool {
matches!(self, DiffCommand::Insert { .. })
matches!(self, Self::Insert { .. })
}
/// Extract a single command from a line iterator that yields lines
@ -380,8 +372,6 @@ impl<'a> DiffCommand<'a> {
return Err(Error::BadDiff("range cannot begin at usize::MAX"));
}
use DiffCommand::*;
match (low, high) {
(lo, Some(RangeEnd::Num(hi))) if lo > hi.into() => {
return Err(Error::BadDiff("mis-ordered lines in range"))
@ -390,23 +380,23 @@ impl<'a> DiffCommand<'a> {
}
let mut cmd = match (command, low, high) {
("d", low, None) => Delete { low, high: low },
("d", low, Some(RangeEnd::Num(high))) => Delete {
("d", low, None) => Self::Delete { low, high: low },
("d", low, Some(RangeEnd::Num(high))) => Self::Delete {
low,
high: high.into(),
},
("d", low, Some(RangeEnd::DollarSign)) => DeleteToEnd { low },
("c", low, None) => Replace {
("d", low, Some(RangeEnd::DollarSign)) => Self::DeleteToEnd { low },
("c", low, None) => Self::Replace {
low,
high: low,
lines: Vec::new(),
},
("c", low, Some(RangeEnd::Num(high))) => Replace {
("c", low, Some(RangeEnd::Num(high))) => Self::Replace {
low,
high: high.into(),
lines: Vec::new(),
},
("a", low, None) => Insert {
("a", low, None) => Self::Insert {
pos: low,
lines: Vec::new(),
},
@ -551,7 +541,7 @@ impl<'a> DiffResult<'a> {
use digest::Digest;
use tor_llcrypto::d::Sha3_256;
let mut d = Sha3_256::new();
for line in self.lines.iter() {
for line in &self.lines {
d.update(line.as_bytes());
d.update(b"\n");
}
@ -565,7 +555,7 @@ impl<'a> DiffResult<'a> {
impl<'a> Display for DiffResult<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
for elt in self.lines.iter() {
for elt in &self.lines {
writeln!(f, "{}", elt)?
}
Ok(())
@ -671,7 +661,6 @@ mod test {
#[test]
fn parse_command() -> Result<()> {
use DiffCommand::*;
fn parse(s: &str) -> Result<DiffCommand<'_>> {
let mut iter = s.lines();
let cmd = DiffCommand::from_line_iterator(&mut iter)?;
@ -689,16 +678,16 @@ mod test {
}
let p = parse("3,8d\n")?;
assert!(matches!(p, Delete { low: 3, high: 8 }));
assert!(matches!(p, DiffCommand::Delete { low: 3, high: 8 }));
let p = parse("3d\n")?;
assert!(matches!(p, Delete { low: 3, high: 3 }));
assert!(matches!(p, DiffCommand::Delete { low: 3, high: 3 }));
let p = parse("100,$d\n")?;
assert!(matches!(p, DeleteToEnd { low: 100 }));
assert!(matches!(p, DiffCommand::DeleteToEnd { low: 100 }));
let p = parse("30,40c\nHello\nWorld\n.\n")?;
assert!(matches!(
p,
Replace {
DiffCommand::Replace {
low: 30,
high: 40,
..
@ -708,7 +697,7 @@ mod test {
let p = parse("30c\nHello\nWorld\n.\n")?;
assert!(matches!(
p,
Replace {
DiffCommand::Replace {
low: 30,
high: 30,
..
@ -717,10 +706,10 @@ mod test {
assert_eq!(p.lines(), Some(&["Hello", "World"][..]));
let p = parse("999a\nHello\nWorld\n.\n")?;
assert!(matches!(p, Insert { pos: 999, .. }));
assert!(matches!(p, DiffCommand::Insert { pos: 999, .. }));
assert_eq!(p.lines(), Some(&["Hello", "World"][..]));
let p = parse("0a\nHello\nWorld\n.\n")?;
assert!(matches!(p, Insert { pos: 0, .. }));
assert!(matches!(p, DiffCommand::Insert { pos: 0, .. }));
assert_eq!(p.lines(), Some(&["Hello", "World"][..]));
parse_err("hello world");

View File

@ -426,7 +426,7 @@ mod test {
_storage: Option<&Mutex<SqliteStore>>,
) -> Result<bool> {
let mut changed = false;
for (id, _ignore) in docs.iter() {
for id in docs.keys() {
if let DocId::Microdesc(id) = id {
if self.got_items.get(id) == Some(&false) {
self.got_items.insert(*id, true);

View File

@ -350,7 +350,7 @@ impl<DM: WriteNetDir> DirState for GetCertsState<DM> {
let mut changed = false;
// Here we iterate over the documents we want, taking them from
// our input and remembering them.
for id in self.missing_docs().iter() {
for id in &self.missing_docs() {
if let Some(cert) = docs.get(id) {
let parsed = AuthCert::parse(cert.as_str()?)?.check_signature()?;
let now = current_time(&self.writedir)?;

View File

@ -173,7 +173,7 @@ impl GuardSet {
/// Copy non-persistent status from every guard shared with `other`.
pub(crate) fn copy_status_from(&mut self, other: &GuardSet) {
for (id, guard) in self.guards.iter_mut() {
for (id, guard) in &mut self.guards {
if let Some(other_guard) = other.get(id) {
guard.copy_status_from(other_guard);
}
@ -438,7 +438,7 @@ impl GuardSet {
}
// Clear exploratory_circ_pending for all primary guards.
for id in self.primary.iter() {
for id in &self.primary {
if let Some(guard) = self.guards.get_mut(id) {
guard.note_exploratory_circ(false);
}
@ -519,7 +519,7 @@ impl GuardSet {
/// Mark every `Unreachable` primary guard as `Unknown`.
pub(crate) fn mark_primary_guards_retriable(&mut self) {
for id in self.primary.iter() {
for id in &self.primary {
if let Some(g) = self.guards.get_mut(id) {
g.mark_retriable();
}
@ -537,7 +537,7 @@ impl GuardSet {
/// Mark every `Unreachable` guard as `Unknown`.
pub(crate) fn mark_all_guards_retriable(&mut self) {
for (_, g) in self.guards.iter_mut() {
for g in self.guards.values_mut() {
g.mark_retriable();
}
}
@ -793,7 +793,7 @@ mod test {
guards.assert_consistency();
// make sure all the guards are okay.
for (g, guard) in guards.guards.iter() {
for (g, guard) in &guards.guards {
let relay = g.get_relay(&netdir).unwrap();
assert!(relay.is_flagged_guard());
assert!(guards.contains_relay(&relay));
@ -842,7 +842,7 @@ mod test {
guards.guards.keys().collect::<HashSet<_>>(),
guards2.guards.keys().collect::<HashSet<_>>()
);
for (k, g) in guards.guards.iter() {
for (k, g) in &guards.guards {
let g2 = guards2.guards.get(k).unwrap();
assert_eq!(format!("{:?}", g), format!("{:?}", g2));
}

View File

@ -410,7 +410,7 @@ impl PartialNetDir {
/// netdir, using the microdescriptors from the previous netdir.
pub fn fill_from_previous_netdir<'a>(&mut self, prev: &'a NetDir) -> Vec<&'a MdDigest> {
let mut loaded = Vec::new();
for ent in prev.mds.iter() {
for ent in &prev.mds {
if let MdEntry::Present { md, .. } = ent {
if self.netdir.mds.contains(md.digest()) {
loaded.push(md.digest());
@ -1054,7 +1054,7 @@ mod test {
let missing: HashSet<_> = dir.missing_microdescs().collect();
assert_eq!(missing.len(), 40);
assert_eq!(missing.len(), dir.netdir.consensus.relays().len());
for md in microdescs.iter() {
for md in &microdescs {
assert!(missing.contains(md.digest()));
}

View File

@ -1463,7 +1463,7 @@ impl SignatureGroup {
fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
let mut ok: HashSet<RsaIdentity> = HashSet::new();
let mut missing = Vec::new();
for sig in self.signatures.iter() {
for sig in &self.signatures {
let id_fingerprint = &sig.key_ids.id_fingerprint;
if ok.contains(id_fingerprint) {
continue;
@ -1483,7 +1483,7 @@ impl SignatureGroup {
/// authorities.
fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
for sig in self.signatures.iter() {
for sig in &self.signatures {
let id_fp = &sig.key_ids.id_fingerprint;
if signed_by.contains(id_fp) {
// Already found this in the list.
@ -1509,7 +1509,7 @@ impl SignatureGroup {
// than one certificate for a single authority.
let mut ok: HashSet<RsaIdentity> = HashSet::new();
for sig in self.signatures.iter() {
for sig in &self.signatures {
let id_fingerprint = &sig.key_ids.id_fingerprint;
if ok.contains(id_fingerprint) {
// We already checked at least one signature using this

View File

@ -46,7 +46,7 @@ impl Display for PortPolicy {
} else {
write!(f, "accept ")?;
let mut comma = "";
for range in self.allowed.iter() {
for range in &self.allowed {
write!(f, "{}{}", comma, range)?;
comma = ",";
}
@ -66,7 +66,7 @@ impl PortPolicy {
fn invert(&mut self) {
let mut prev_hi = 0;
let mut new_allowed = Vec::new();
for entry in self.allowed.iter() {
for entry in &self.allowed {
// ports prev_hi+1 through entry.lo-1 were rejected. We should
// make them allowed.
if entry.lo > prev_hi + 1 {

View File

@ -477,7 +477,7 @@ impl std::fmt::Display for Protocols {
entries.push(format!("{}={}", pk, dumpmask(*mask)))
}
}
for ent in self.unrecognized.iter() {
for ent in &self.unrecognized {
if ent.supported != 0 {
entries.push(format!(
"{}={}",