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() { if chunk_range.all() {
return Some(ChunkMarkingResult::Completed); 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_bytes += piece_info.len as u64;
have_pieces.set(piece_info.piece_index.get() as usize, true); have_pieces.set(piece_info.piece_index.get() as usize, true);
} else { } else if at_least_one_file_required {
if at_least_one_file_required { trace!(
trace!( "piece {} hash does not match, marking as needed",
"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 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") anyhow::bail!("read_chunk(): not enough capacity in the provided buffer")
} }
let mut absolute_offset = self.lengths.chunk_absolute_offset(&chunk_info); 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() { for (file_idx, file_len) in self.torrent.info.iter_file_lengths().enumerate() {
if absolute_offset > file_len { if absolute_offset > file_len {
@ -345,7 +343,7 @@ impl<'a, Sha1Impl: ISha1> FileOps<'a, Sha1Impl> {
absolute_offset = 0; absolute_offset = 0;
} }
return Ok(()); Ok(())
} }
pub fn write_chunk<ByteBuf>( 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 bincode::Options;
use byteorder::{ByteOrder, BE}; use byteorder::{ByteOrder, BE};
@ -212,7 +212,7 @@ where
Message::KeepAlive => Message::KeepAlive, Message::KeepAlive => Message::KeepAlive,
Message::Have(v) => Message::Have(*v), Message::Have(v) => Message::Have(*v),
Message::NotInterested => Message::NotInterested, 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)] #[cfg(test)]
mod tests { mod tests {
use std::{io::Write, net::SocketAddr, ptr::read, str::FromStr}; use std::{net::SocketAddr, str::FromStr};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};

View file

@ -39,8 +39,8 @@ pub struct PeerConnection<H> {
impl<H: PeerConnectionHandler> PeerConnection<H> { impl<H: PeerConnectionHandler> PeerConnection<H> {
pub fn new(addr: SocketAddr, info_hash: [u8; 20], peer_id: [u8; 20], handler: H) -> Self { pub fn new(addr: SocketAddr, info_hash: [u8; 20], peer_id: [u8; 20], handler: H) -> Self {
PeerConnection { PeerConnection {
addr,
handler, handler,
addr,
info_hash, info_hash,
peer_id, peer_id,
} }
@ -103,13 +103,6 @@ impl<H: PeerConnectionHandler> PeerConnection<H> {
.context("error writing bitfield to peer")?; .context("error writing bitfield to peer")?;
debug!("sent bitfield to {}", self.addr); 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 { 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::ByteBuf;
use crate::buffers::ByteString;
use crate::clone_to_owned::CloneToOwned;
use crate::sha1w::ISha1; use crate::sha1w::ISha1;
use crate::type_aliases::Sha1; use crate::type_aliases::Sha1;
use serde::de::Error as DeError;
pub struct BencodeDeserializer<'de> { pub struct BencodeDeserializer<'de> {
buf: &'de [u8], buf: &'de [u8],

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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