Cargo clippy: fix the majority of errors

This commit is contained in:
Igor Katson 2022-12-08 20:20:23 +00:00
parent 871d927596
commit 6968a4e449
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
19 changed files with 69 additions and 91 deletions

View file

@ -113,12 +113,12 @@ impl std::fmt::Display for ErrorContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut it = self.field_stack.iter();
if let Some(field) = it.next() {
write!(f, "\"{}\"", field)?;
write!(f, "\"{field}\"")?;
} else {
return Ok(());
}
for field in self.field_stack.iter().skip(1) {
write!(f, " -> \"{}\"", field)?;
write!(f, " -> \"{field}\"")?;
}
f.write_str(": ")
}
@ -134,7 +134,7 @@ impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::Other(err) => err.fmt(f),
ErrorKind::NotSupported(s) => write!(f, "{} is not supported by bencode", s),
ErrorKind::NotSupported(s) => write!(f, "{s} is not supported by bencode"),
}
}
}
@ -183,7 +183,7 @@ impl Error {
}
fn set_context(mut self, de: &BencodeDeserializer<'_>) -> Self {
self.context = ErrorContext {
field_stack: de.field_context.iter().map(|s| format!("{}", s)).collect(),
field_stack: de.field_context.iter().map(|s| format!("{s}")).collect(),
};
self
}
@ -427,7 +427,7 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut BencodeDeserializer<'de>
}
self.buf = self.buf.get(1..).unwrap_or_default();
visitor
.visit_seq(SeqAccess { de: &mut self })
.visit_seq(SeqAccess { de: self })
.map_err(|e: Self::Error| e.set_context(self))
}
@ -459,7 +459,7 @@ impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut BencodeDeserializer<'de>
}
self.buf = self.buf.get(1..).unwrap_or_default();
visitor
.visit_map(MapAccess { de: &mut self })
.visit_map(MapAccess { de: self })
.map_err(|e: Self::Error| e.set_context(self))
}

View file

@ -12,7 +12,7 @@ pub enum SerErrorKind {
impl std::fmt::Display for SerErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SerErrorKind::Other(e) => write!(f, "{}", e),
SerErrorKind::Other(e) => write!(f, "{e}"),
}
}
}
@ -84,7 +84,7 @@ impl<W: std::io::Write> BencodeSerializer<W> {
self.write_raw(&[byte])
}
fn write_number<N: std::fmt::Display>(&mut self, number: N) -> Result<(), SerError> {
self.write_fmt(format_args!("i{}e", number))
self.write_fmt(format_args!("i{number}e"))
}
fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), SerError> {
if !self.hack_no_bytestring_prefix {

View file

@ -29,7 +29,7 @@ struct HexBytes<'a>(&'a [u8]);
impl<'a> std::fmt::Display for HexBytes<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for byte in self.0 {
write!(f, "{:02x?}", byte)?;
write!(f, "{byte:02x?}")?;
}
Ok(())
}
@ -44,9 +44,9 @@ fn debug_bytes(b: &[u8], f: &mut std::fmt::Formatter<'_>, debug_strings: bool) -
// A test if all chars are "printable".
if s.chars().all(|c| c.escape_debug().len() == 1) {
if debug_strings {
return write!(f, "{:?}", s);
return write!(f, "{s:?}");
} else {
return write!(f, "{}", s);
return write!(f, "{s}");
}
}
}

View file

@ -509,7 +509,7 @@ mod tests {
const WHAT_IS_THAT: &[u8]= b"64313a6164323a696432303abd7b477cfbcd10f30b705da20201e7101d8df155393a696e666f5f6861736832303acab507494d02ebb1178b38f2e9d7be299c86b86265313a71393a6765745f7065657273313a74323a0007313a79313a7165";
fn write(filename: &str, data: &[u8]) {
let full = format!("/tmp/{}.bin", filename);
let full = format!("/tmp/{filename}.bin");
let mut f = std::fs::OpenOptions::new()
.create(true)
.write(true)
@ -519,7 +519,7 @@ mod tests {
}
fn debug_hex_bencode(name: &str, data: &[u8]) {
println!("{}", name);
println!("{name}");
let data = hex::decode(data).unwrap();
println!(
@ -544,8 +544,8 @@ mod tests {
bprotocol::serialize_message(&mut buf, transaction_id, version, ip, kind).unwrap();
if buf.as_slice() != data {
write(&format!("{}-serialized", name), buf.as_slice());
write(&format!("{}-expected", name), data);
write(&format!("{name}-serialized"), buf.as_slice());
write(&format!("{name}-expected"), data);
panic!(
"{} results don't match, dumped to /tmp/{}-*.bin",
name, name

View file

@ -34,8 +34,8 @@ fn dump_dht(dht: &Dht, filename: &Path, tempfile_name: &Path) -> anyhow::Result<
.truncate(true)
.create(true)
.write(true)
.open(&tempfile_name)
.with_context(|| format!("error opening {:?}", tempfile_name))?;
.open(tempfile_name)
.with_context(|| format!("error opening {tempfile_name:?}"))?;
let addr = dht.listen_addr();
match dht
@ -46,13 +46,13 @@ fn dump_dht(dht: &Dht, filename: &Path, tempfile_name: &Path) -> anyhow::Result<
}
Err(e) => {
return Err(e).with_context(|| {
format!("error serializing DHT routing table to {:?}", tempfile_name)
format!("error serializing DHT routing table to {tempfile_name:?}")
})
}
}
std::fs::rename(tempfile_name, filename)
.with_context(|| format!("error renaming {:?} to {:?}", tempfile_name, filename))
.with_context(|| format!("error renaming {tempfile_name:?} to {filename:?}"))
}
impl PersistentDht {
@ -92,7 +92,7 @@ impl PersistentDht {
}
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => None,
_ => return Err(e).with_context(|| format!("error reading {:?}", config_filename)),
_ => return Err(e).with_context(|| format!("error reading {config_filename:?}")),
},
};
let (listen_addr, routing_table) = de

View file

@ -50,7 +50,7 @@ pub async fn read_metainfo_from_peer_receiver<A: Stream<Item = SocketAddr> + Unp
BlockingSpawner::new(true),
)
.await
.with_context(|| format!("error reading metainfo from {}", addr));
.with_context(|| format!("error reading metainfo from {addr}"));
drop(token);
ret
}

View file

@ -34,12 +34,8 @@ pub fn update_hash_from_file<Sha1: ISha1>(
let mut read = 0;
while bytes_to_read > 0 {
let chunk = std::cmp::min(buf.len(), bytes_to_read);
file.read_exact(&mut buf[..chunk]).with_context(|| {
format!(
"failed reading chunk of size {}, read so far {}",
chunk, read
)
})?;
file.read_exact(&mut buf[..chunk])
.with_context(|| format!("failed reading chunk of size {chunk}, read so far {read}"))?;
bytes_to_read -= chunk;
read += chunk;
hash.update(&buf[..chunk]);
@ -93,7 +89,7 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
self.len - self.processed_bytes
}
fn mark_processed_bytes(&mut self, bytes: u64) {
self.processed_bytes += bytes as u64
self.processed_bytes += bytes
}
}
let mut file_iterator = self
@ -247,16 +243,12 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
file_g
.seek(SeekFrom::Start(absolute_offset))
.with_context(|| {
format!(
"error seeking to {}, file id: {}",
absolute_offset, file_idx
)
format!("error seeking to {absolute_offset}, file id: {file_idx}")
})?;
update_hash_from_file(&mut file_g, &mut h, &mut buf, to_read_in_file).with_context(
|| {
format!(
"error reading {} bytes, file_id: {} (\"{:?}\")",
to_read_in_file, file_idx, name
"error reading {to_read_in_file} bytes, file_id: {file_idx} (\"{name:?}\")"
)
},
)?;
@ -315,18 +307,12 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
file_g
.seek(SeekFrom::Start(absolute_offset))
.with_context(|| {
format!(
"error seeking to {}, file id: {}",
absolute_offset, file_idx
)
format!("error seeking to {absolute_offset}, file id: {file_idx}")
})?;
file_g
.read_exact(&mut buf[..to_read_in_file])
.with_context(|| {
format!(
"error reading {} bytes, file_id: {}",
file_idx, to_read_in_file
)
format!("error reading {file_idx} bytes, file_id: {to_read_in_file}")
})?;
buf = &mut buf[to_read_in_file..];
@ -376,14 +362,11 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
file_g
.seek(SeekFrom::Start(absolute_offset))
.with_context(|| {
format!(
"error seeking to {} in file {} (\"{:?}\")",
absolute_offset, file_idx, name
)
format!("error seeking to {absolute_offset} in file {file_idx} (\"{name:?}\")")
})?;
file_g
.write_all(&buf[..to_write])
.with_context(|| format!("error writing to file {} (\"{:?}\")", file_idx, name))?;
.with_context(|| format!("error writing to file {file_idx} (\"{name:?}\")"))?;
buf = &buf[to_write..];
if buf.is_empty() {
break;

View file

@ -15,12 +15,10 @@ async fn check_response(r: reqwest::Response) -> anyhow::Result<reqwest::Respons
}
let status = r.status();
let url = r.url().clone();
let body = r.text().await.with_context(|| {
format!(
"cannot read response body for request to {} ({})",
url, status,
)
})?;
let body = r
.text()
.await
.with_context(|| format!("cannot read response body for request to {url} ({status})"))?;
anyhow::bail!("{} -> {}: {}", url, status, body)
}

View file

@ -110,7 +110,7 @@ impl HandlerLocked {
anyhow::bail!("already received piece {}", index);
}
let offset_end = offset + size;
(&mut self.buffer[offset..offset_end]).copy_from_slice(data);
self.buffer[offset..offset_end].copy_from_slice(data);
self.received_pieces[index as usize] = true;
if self.received_pieces.iter().all(|p| *p) {

View file

@ -72,14 +72,14 @@ pub struct Session {
async fn torrent_from_url(url: &str) -> anyhow::Result<TorrentMetaV1Owned> {
let response = reqwest::get(url)
.await
.with_context(|| format!("error downloading torrent metadata from {}", url))?;
.with_context(|| format!("error downloading torrent metadata from {url}"))?;
if !response.status().is_success() {
anyhow::bail!("GET {} returned {}", url, response.status())
}
let b = response
.bytes()
.await
.with_context(|| format!("error reading repsonse body from {}", url))?;
.with_context(|| format!("error reading repsonse body from {url}"))?;
torrent_from_bytes(&b).context("error decoding torrent")
}
@ -91,9 +91,9 @@ fn torrent_from_file(filename: &str) -> anyhow::Result<TorrentMetaV1Owned> {
.context("error reading stdin")?;
} else {
File::open(filename)
.with_context(|| format!("error opening {}", filename))?
.with_context(|| format!("error opening {filename}"))?
.read_to_end(&mut buf)
.with_context(|| format!("error reading {}", filename))?;
.with_context(|| format!("error reading {filename}"))?;
}
torrent_from_bytes(&buf).context("error decoding torrent")
}
@ -107,7 +107,7 @@ fn compute_only_files<ByteBuf: AsRef<[u8]>>(
for (idx, (filename, _)) in torrent.iter_filenames_and_lengths()?.enumerate() {
let full_path = filename
.to_pathbuf()
.with_context(|| format!("filename of file {} is not valid utf8", idx))?;
.with_context(|| format!("filename of file {idx} is not valid utf8"))?;
if filename_re.is_match(full_path.to_str().unwrap()) {
only_files.push(idx);
}

View file

@ -116,7 +116,7 @@ impl TorrentManagerHandle {
pub fn add_tracker(&self, url: Url) -> bool {
let mgr = self.manager.clone();
if mgr.trackers.lock().insert(url.clone()) {
spawn(format!("tracker monitor {}", url), async move {
spawn(format!("tracker monitor {url}"), async move {
mgr.single_tracker_monitor(url).await
});
true

View file

@ -723,7 +723,7 @@ impl PeerHandler {
}
fn on_bitfield(&self, handle: PeerHandle, bitfield: ByteString) -> anyhow::Result<()> {
if bitfield.len() != self.state.lengths.piece_bitfield_bytes() as usize {
if bitfield.len() != self.state.lengths.piece_bitfield_bytes() {
anyhow::bail!(
"dropping {} as its bitfield has unexpected size. Got {}, expected {}",
handle,
@ -754,7 +754,7 @@ impl PeerHandler {
// Additional spawn per peer, not good.
spawn(
format!("peer_chunk_requester({})", handle),
format!("peer_chunk_requester({handle})"),
self.clone().task_peer_chunk_requester(handle),
);
Ok(())
@ -984,7 +984,7 @@ impl PeerHandler {
.state
.file_ops()
.check_piece(handle, chunk_info.piece_index, &chunk_info)
.with_context(|| format!("error checking piece={}", index))?
.with_context(|| format!("error checking piece={index}"))?
{
true => {
let piece_len =
@ -1036,7 +1036,7 @@ impl PeerHandler {
};
Ok::<_, anyhow::Error>(())
})
.with_context(|| format!("error processing received chunk {:?}", chunk_info))?;
.with_context(|| format!("error processing received chunk {chunk_info:?}"))?;
Ok(())
}
}

View file

@ -127,7 +127,7 @@ where
where
E: serde::de::Error,
{
IpAddr::from_str(v).map_err(|e| E::custom(format!("cannot parse ip: {}", e)))
IpAddr::from_str(v).map_err(|e| E::custom(format!("cannot parse ip: {e}")))
}
}
de.deserialize_str(Visitor {})
@ -185,16 +185,16 @@ impl TrackerRequest {
write!(s, "&compact={}", if self.compact { 1 } else { 0 }).unwrap();
write!(s, "&no_peer_id={}", if self.no_peer_id { 1 } else { 0 }).unwrap();
if let Some(ip) = &self.ip {
write!(s, "&ip={}", ip).unwrap();
write!(s, "&ip={ip}").unwrap();
}
if let Some(numwant) = &self.numwant {
write!(s, "&numwant={}", numwant).unwrap();
write!(s, "&numwant={numwant}").unwrap();
}
if let Some(key) = &self.key {
write!(s, "&key={}", key).unwrap();
write!(s, "&key={key}").unwrap();
}
if let Some(trackerid) = &self.trackerid {
write!(s, "&trackerid={}", trackerid).unwrap();
write!(s, "&trackerid={trackerid}").unwrap();
}
s
}

View file

@ -22,7 +22,7 @@ impl std::fmt::Debug for Id20 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<")?;
for byte in self.0 {
write!(f, "{:02x?}", byte)?;
write!(f, "{byte:02x?}")?;
}
write!(f, ">")?;
Ok(())

View file

@ -85,7 +85,7 @@ impl Lengths {
if total_length == 0 {
anyhow::bail!("torrent with 0 length")
}
let total_pieces = ceil_div_u64(total_length as u64, piece_length as u64) as u32;
let total_pieces = ceil_div_u64(total_length, piece_length as u64) as u32;
Ok(Self {
chunk_length,
piece_length,

View file

@ -31,7 +31,7 @@ fn try_decode_azureus_style(p: &Id20) -> Option<AzureusStyle> {
return None;
}
let mut version = ['0'; 4];
for (i, c) in (&p[3..7]).iter().copied().enumerate() {
for (i, c) in p[3..7].iter().copied().enumerate() {
version[i] = c as char;
}
let kind = AzureusStyleKind::from_bytes(p[1], p[2]);
@ -51,9 +51,9 @@ pub fn generate_peer_id() -> Id20 {
let mut peer_id = [0u8; 20];
let u = uuid::Uuid::new_v4();
(&mut peer_id[4..20]).copy_from_slice(&u.as_bytes()[..]);
peer_id[4..20].copy_from_slice(&u.as_bytes()[..]);
(&mut peer_id[..8]).copy_from_slice(b"-rQ0001-");
peer_id[..8].copy_from_slice(b"-rQ0001-");
Id20(peer_id)
}

View file

@ -76,8 +76,8 @@ where
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.to_string() {
Ok(s) => write!(f, "{:?}", s),
Err(e) => write!(f, "<{:?}>", e),
Ok(s) => write!(f, "{s:?}"),
Err(e) => write!(f, "<{e:?}>"),
}
}
}

View file

@ -73,7 +73,7 @@ impl<'a, ByteBuf: 'a + std::hash::Hash + Eq + Serialize> ExtendedMessage<ByteBuf
where
ByteBuf: Deserialize<'a> + From<&'a [u8]>,
{
let emsg_id = buf.get(0).copied().ok_or_else(|| {
let emsg_id = buf.first().copied().ok_or_else(|| {
MessageDeserializeError::Other(anyhow::anyhow!(
"cannot deserialize extended message: can't read first byte"
))

View file

@ -119,12 +119,11 @@ impl std::fmt::Display for MessageDeserializeError {
MessageDeserializeError::NotEnoughData(b, name) => {
write!(
f,
"not enough data to deserialize {}: expected at least {} more bytes",
name, b
"not enough data to deserialize {name}: expected at least {b} more bytes"
)
}
MessageDeserializeError::UnsupportedMessageId(msg_id) => {
write!(f, "unsupported message id {}", msg_id)
write!(f, "unsupported message id {msg_id}")
}
MessageDeserializeError::IncorrectLenPrefix {
received,
@ -132,8 +131,7 @@ impl std::fmt::Display for MessageDeserializeError {
msg_id,
} => write!(
f,
"incorrect len prefix for message id {}, expected {}, received {}",
msg_id, expected, received
"incorrect len prefix for message id {msg_id}, expected {expected}, received {received}"
),
MessageDeserializeError::OtherBincode {
error,
@ -142,10 +140,9 @@ impl std::fmt::Display for MessageDeserializeError {
len_prefix,
} => write!(
f,
"error deserializing {} (msg_id={}, len_prefix={}): {:?}",
name, msg_id, len_prefix, error
"error deserializing {name} (msg_id={msg_id}, len_prefix={len_prefix}): {error:?}"
),
MessageDeserializeError::Other(e) => write!(f, "{}", e),
MessageDeserializeError::Other(e) => write!(f, "{e}"),
}
}
}
@ -272,7 +269,7 @@ where
Message::Request(request) => {
const MSG_LEN: usize = PREAMBLE_LEN + 12;
out.resize(MSG_LEN, 0);
debug_assert_eq!((&out[PREAMBLE_LEN..]).len(), 12);
debug_assert_eq!(out[PREAMBLE_LEN..].len(), 12);
ser.serialize_into(&mut out[PREAMBLE_LEN..], request)
.unwrap();
Ok(MSG_LEN)
@ -281,7 +278,7 @@ where
let block_len = b.as_ref().len();
let msg_len = PREAMBLE_LEN + block_len;
out.resize(msg_len, 0);
(&mut out[PREAMBLE_LEN..PREAMBLE_LEN + block_len]).copy_from_slice(b.as_ref());
out[PREAMBLE_LEN..PREAMBLE_LEN + block_len].copy_from_slice(b.as_ref());
Ok(msg_len)
}
Message::Choke | Message::Unchoke | Message::Interested | Message::NotInterested => {
@ -382,7 +379,7 @@ where
}
MSGID_HAVE => {
let expected_len = 4;
match rest.get(..expected_len as usize) {
match rest.get(..expected_len) {
Some(h) => Ok((Message::Have(BE::read_u32(h)), PREAMBLE_LEN + expected_len)),
None => {
let missing = expected_len - rest.len();
@ -399,7 +396,7 @@ where
});
}
let expected_len = len_prefix as usize - 1;
match rest.get(..expected_len as usize) {
match rest.get(..expected_len) {
Some(bitfield) => Ok((
Message::Bitfield(ByteBuf::from(bitfield)),
PREAMBLE_LEN + expected_len,
@ -412,7 +409,7 @@ where
}
MSGID_REQUEST => {
let expected_len = 12;
match rest.get(..expected_len as usize) {
match rest.get(..expected_len) {
Some(b) => {
let request = decoder_config.deserialize::<Request>(b).unwrap();
Ok((Message::Request(request), PREAMBLE_LEN + expected_len))
@ -509,7 +506,7 @@ impl<'a> Handshake<'a> {
}
pub fn deserialize(b: &[u8]) -> Result<(Handshake<'_>, usize), MessageDeserializeError> {
let pstr_len = *b
.get(0)
.first()
.ok_or(MessageDeserializeError::NotEnoughData(1, "handshake"))?;
let expected_len = 1usize + pstr_len as usize + 48;
let hbuf = b