Remove all linter warnings

This commit is contained in:
Igor Katson 2021-07-02 10:21:19 +01:00
parent 1f299247d2
commit d722f0edcb
11 changed files with 73 additions and 92 deletions

View file

@ -157,6 +157,6 @@ impl ChunkTracker {
if chunk_range.all() {
return Some(ChunkMarkingResult::Completed);
}
return Some(ChunkMarkingResult::NotCompleted);
Some(ChunkMarkingResult::NotCompleted)
}
}

View file

@ -193,20 +193,18 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
);
have_bytes += piece_info.len as u64;
have_pieces.set(piece_info.piece_index.get() as usize, true);
} else {
if at_least_one_file_required {
trace!(
"piece {} hash does not match, marking as needed",
piece_info.piece_index
);
needed_bytes += piece_info.len as u64;
needed_pieces.set(piece_info.piece_index.get() as usize, true);
} else {
trace!(
"piece {} hash does not match, but it is not required by any of the requested files, ignoring",
} else if at_least_one_file_required {
trace!(
"piece {} hash does not match, marking as needed",
piece_info.piece_index
);
}
needed_bytes += piece_info.len as u64;
needed_pieces.set(piece_info.piece_index.get() as usize, true);
} else {
trace!(
"piece {} hash does not match, but it is not required by any of the requested files, ignoring",
piece_info.piece_index
);
}
}
@ -304,7 +302,7 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
anyhow::bail!("read_chunk(): not enough capacity in the provided buffer")
}
let mut absolute_offset = self.lengths.chunk_absolute_offset(&chunk_info);
let mut buf = &mut result_buf[..];
let mut buf = result_buf;
for (file_idx, file_len) in self.torrent.info.iter_file_lengths().enumerate() {
if absolute_offset > file_len {
@ -345,7 +343,7 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
absolute_offset = 0;
}
return Ok(());
Ok(())
}
pub fn write_chunk<ByteBuf>(

View file

@ -1,4 +1,4 @@
use std::{collections::HashMap, marker::PhantomData};
use std::collections::HashMap;
use bincode::Options;
use byteorder::{ByteOrder, BE};
@ -212,7 +212,7 @@ where
Message::KeepAlive => Message::KeepAlive,
Message::Have(v) => Message::Have(*v),
Message::NotInterested => Message::NotInterested,
Message::Extended(e) => unimplemented!(),
Message::Extended(_) => unimplemented!(),
}
}
}
@ -618,7 +618,7 @@ pub struct ExtendedHandshake<ByteBuf: Eq + std::hash::Hash> {
#[cfg(test)]
mod tests {
use std::{io::Write, net::SocketAddr, ptr::read, str::FromStr};
use std::{net::SocketAddr, str::FromStr};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

View file

@ -39,8 +39,8 @@ pub struct PeerConnection<H> {
impl<H: PeerConnectionHandler> PeerConnection<H> {
pub fn new(addr: SocketAddr, info_hash: [u8; 20], peer_id: [u8; 20], handler: H) -> Self {
PeerConnection {
addr,
handler,
addr,
info_hash,
peer_id,
}
@ -103,13 +103,6 @@ impl<H: PeerConnectionHandler> PeerConnection<H> {
.context("error writing bitfield to peer")?;
debug!("sent bitfield to {}", self.addr);
}
// let len = {
// let bitfield = self.handler.get_have_bitfield();
// let msg = Message::Bitfield(ByteBuf(g.chunks.get_have_pieces().as_raw_slice()));
// let len = msg.serialize(&mut buf);
// debug!("sending to {}: {:?}, length={}", self.addr, &msg, len);
// len
// };
}
loop {

View file

@ -1,15 +1,7 @@
use serde::de::Deserializer;
use serde::de::Error as DeError;
use serde::Deserialize;
use serde::Serializer;
use std::collections::HashMap;
use std::marker::PhantomData;
use crate::buffers::ByteBuf;
use crate::buffers::ByteString;
use crate::clone_to_owned::CloneToOwned;
use crate::sha1w::ISha1;
use crate::type_aliases::Sha1;
use serde::de::Error as DeError;
pub struct BencodeDeserializer<'de> {
buf: &'de [u8],

View file

@ -5,6 +5,14 @@ pub enum SerErrorKind {
Other(anyhow::Error),
}
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),
}
}
}
#[derive(Debug)]
pub struct SerError {
kind: SerErrorKind,
@ -13,13 +21,13 @@ pub struct SerError {
impl SerError {
fn custom_with_ser<T: std::fmt::Display, W: std::io::Write>(
msg: T,
ser: &BencodeSerializer<W>,
_ser: &BencodeSerializer<W>,
) -> Self {
serde::ser::Error::custom(msg)
}
fn from_err_with_ser<E: std::error::Error + Send + Sync + 'static, W: std::io::Write>(
err: E,
ser: &BencodeSerializer<W>,
_ser: &BencodeSerializer<W>,
) -> Self {
Self {
kind: SerErrorKind::Other(err.into()),
@ -42,7 +50,7 @@ impl std::error::Error for SerError {}
impl std::fmt::Display for SerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
todo!()
write!(f, "{}", self.kind)
}
}
@ -113,14 +121,14 @@ impl<'ser, W: std::io::Write> serde::ser::SerializeTuple for SerializeTuple<'ser
}
struct SerializeTupleStruct<'ser, W: std::io::Write> {
ser: &'ser mut BencodeSerializer<W>,
_ser: &'ser mut BencodeSerializer<W>,
}
impl<'ser, W: std::io::Write> serde::ser::SerializeTupleStruct for SerializeTupleStruct<'ser, W> {
type Ok = ();
type Error = SerError;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
fn serialize_field<T: ?Sized>(&mut self, _value: &T) -> Result<(), Self::Error>
where
T: serde::Serialize,
{
@ -133,14 +141,14 @@ impl<'ser, W: std::io::Write> serde::ser::SerializeTupleStruct for SerializeTupl
}
struct SerializeTupleVariant<'ser, W: std::io::Write> {
ser: &'ser mut BencodeSerializer<W>,
_ser: &'ser mut BencodeSerializer<W>,
}
impl<'ser, W: std::io::Write> serde::ser::SerializeTupleVariant for SerializeTupleVariant<'ser, W> {
type Ok = ();
type Error = SerError;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
fn serialize_field<T: ?Sized>(&mut self, _value: &T) -> Result<(), Self::Error>
where
T: serde::Serialize,
{
@ -205,7 +213,7 @@ impl<'ser, W: std::io::Write> serde::ser::SerializeStruct for SerializeStruct<'s
}
struct SerializeStructVariant<'ser, W: std::io::Write> {
ser: &'ser mut BencodeSerializer<W>,
_ser: &'ser mut BencodeSerializer<W>,
}
impl<'ser, W: std::io::Write> serde::ser::SerializeStructVariant
for SerializeStructVariant<'ser, W>
@ -216,8 +224,8 @@ impl<'ser, W: std::io::Write> serde::ser::SerializeStructVariant
fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
value: &T,
_key: &'static str,
_value: &T,
) -> Result<(), Self::Error>
where
T: serde::Serialize,
@ -249,7 +257,7 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
type SerializeStructVariant = SerializeStructVariant<'ser, W>;
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
Err(SerError::custom_with_ser(
"bencode doesn't support booleans",
&self,
@ -288,21 +296,21 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
self.write_number(v)
}
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
Err(SerError::custom_with_ser(
"bencode doesn't support f32",
&self,
))
}
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
Err(SerError::custom_with_ser(
"bencode doesn't support f32",
&self,
))
}
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
Err(SerError::custom_with_ser(
"bencode doesn't support chars",
&self,
@ -338,23 +346,23 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
))
}
fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
todo!()
}
fn serialize_unit_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
todo!()
}
fn serialize_newtype_struct<T: ?Sized>(
self,
name: &'static str,
value: &T,
_name: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::Serialize,
@ -364,10 +372,10 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
fn serialize_newtype_variant<T: ?Sized>(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
value: &T,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde::Serialize,
@ -375,42 +383,42 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
todo!()
}
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
self.write_byte(b'l')?;
Ok(SerializeSeq { ser: self })
}
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
todo!()
}
fn serialize_tuple_struct(
self,
name: &'static str,
len: usize,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
todo!()
}
fn serialize_tuple_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
todo!()
}
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
self.write_byte(b'd')?;
Ok(SerializeMap { ser: self })
}
fn serialize_struct(
self,
name: &'static str,
len: usize,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
self.write_byte(b'd')?;
Ok(SerializeStruct { ser: self })
@ -418,10 +426,10 @@ impl<'ser, W: std::io::Write> Serializer for &'ser mut BencodeSerializer<W> {
fn serialize_struct_variant(
self,
name: &'static str,
variant_index: u32,
variant: &'static str,
len: usize,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
todo!()
}

View file

@ -1,5 +1,3 @@
use std::io::Write;
// Wrapper for sha1 libraries.
// Sha1 computation is the majority of CPU usage of this library.
// openssl seems 2-3x faster, so using it for now, but
@ -70,6 +68,7 @@ impl ISha1 for Sha1System {
}
fn update(&mut self, buf: &[u8]) {
use std::io::Write;
self.inner.write_all(buf).unwrap();
}

View file

@ -35,6 +35,6 @@ impl BlockingSpawner {
return tokio::task::block_in_place(f);
}
return f();
f()
}
}

View file

@ -77,7 +77,7 @@ impl TorrentManagerBuilder {
self.overwrite,
self.only_files,
self.force_tracker_interval,
self.spawner.unwrap_or(BlockingSpawner::new(true)),
self.spawner.unwrap_or_else(|| BlockingSpawner::new(true)),
)
}
}
@ -207,7 +207,6 @@ impl TorrentManager {
);
spawn("speed estimator updater", {
let state = mgr.state.clone();
let estimator = estimator.clone();
async move {
loop {
let downloaded = state.stats.downloaded_and_checked.load(Ordering::Relaxed);
@ -295,14 +294,11 @@ impl TorrentManager {
anyhow::bail!("tracker responded with {:?}", response.status());
}
let bytes = response.bytes().await?;
match crate::serde_bencode_de::from_bytes::<TrackerError>(&bytes) {
Ok(error) => anyhow::bail!(
if let Ok(error) = crate::serde_bencode_de::from_bytes::<TrackerError>(&bytes) {
anyhow::bail!(
"tracker returned failure. Failure reason: {}",
error.failure_reason
),
Err(_) => {
// ignore, assume ok response
}
)
};
let response = crate::serde_bencode_de::from_bytes::<TrackerResponse>(&bytes)?;
@ -340,7 +336,7 @@ impl TorrentManager {
event = None;
let interval = self
.force_tracker_interval
.unwrap_or(Duration::from_secs(interval));
.unwrap_or_else(|| Duration::from_secs(interval));
debug!(
"sleeping for {:?} after calling tracker {}",
interval,

View file

@ -240,8 +240,6 @@ where
mod tests {
use std::io::Read;
use crate::serde_bencode_de::from_bytes;
use super::*;
#[test]

View file

@ -13,10 +13,7 @@ use anyhow::Context;
use futures::{stream::FuturesUnordered, StreamExt};
use log::{debug, info, trace, warn};
use parking_lot::{Mutex, RwLock};
use tokio::{
sync::mpsc::{channel, Sender, UnboundedSender},
time::timeout,
};
use tokio::{sync::mpsc::UnboundedSender, time::timeout};
use crate::{
buffers::{ByteBuf, ByteString},