Skip to content

Commit

Permalink
chore: fix clippy and rust problems
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed Jul 16, 2024
1 parent 6b7bcc9 commit 67ad620
Show file tree
Hide file tree
Showing 131 changed files with 1,387 additions and 640 deletions.
43 changes: 28 additions & 15 deletions examples/get_metadata/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ use peer::protocols::{NullProtocol, PeerExtensionProtocol, PeerWireProtocol};
use peer::{IPeerManagerMessage, OPeerManagerMessage, PeerInfo, PeerManagerBuilder, PeerProtocolCodec};
use pendulum::future::TimerBuilder;
use pendulum::HashedWheelBuilder;
use select::discovery::error::DiscoveryError;
use select::discovery::{IDiscoveryMessage, ODiscoveryMessage, UtMetadataModule};
use select::{ControlMessage, IExtendedMessage, IUberMessage, OExtendedMessage, OUberMessage, UberModuleBuilder};
use select::{ControlMessage, DiscoveryTrait, IExtendedMessage, IUberMessage, OExtendedMessage, OUberMessage, UberModuleBuilder};
use tokio_core::reactor::Core;

// Legacy Handshaker, when bip_dht is migrated, it will accept S directly
Expand Down Expand Up @@ -69,6 +70,7 @@ where
fn metadata(&mut self, _data: ()) {}
}

#[allow(clippy::too_many_lines)]
fn main() {
let matches = clap_app!(myapp =>
(version: "1.0")
Expand Down Expand Up @@ -100,7 +102,7 @@ fn main() {
// Set a low handshake timeout so we don't wait on peers that aren't listening on tcp
HandshakerConfig::default().with_connect_timeout(Duration::from_millis(500)),
)
.build(TcpTransport, core.handle())
.build(TcpTransport, &core.handle())
.unwrap()
.into_parts();
// Create a peer manager that will hold our peers and heartbeat/send messages to them
Expand All @@ -109,7 +111,7 @@ fn main() {
// Hook up a future that feeds incoming (handshaken) peers over to the peer manager
core.handle().spawn(
handshaker_recv
.map_err(|_| ())
.map_err(|()| ())
.map(|complete_msg| {
// Our handshaker finished handshaking some peer, get
// the peer info as well as the peer itself (socket)
Expand Down Expand Up @@ -141,11 +143,22 @@ fn main() {
);

// Create our UtMetadata selection module
let (uber_send, uber_recv) = UberModuleBuilder::new()
.with_extended_builder(Some(ExtendedMessageBuilder::new()))
.with_discovery_module(UtMetadataModule::new())
.build()
.split();
let (uber_send, uber_recv) = {
let mut this = UberModuleBuilder::new().with_extended_builder(Some(ExtendedMessageBuilder::new()));
let module = UtMetadataModule::new();
this.discovery.push(Box::new(module)
as Box<
dyn DiscoveryTrait<
SinkItem = IDiscoveryMessage,
SinkError = Box<DiscoveryError>,
Item = ODiscoveryMessage,
Error = Box<DiscoveryError>,
>,
>);
this
}
.build()
.split();

// Tell the uber module we want to download metainfo for the given hash
let uber_send = core
Expand All @@ -159,7 +172,7 @@ fn main() {
let timer = TimerBuilder::default().build(HashedWheelBuilder::default().build());
let timer_recv = timer.sleep_stream(Duration::from_millis(100)).unwrap().map(Either::B);

let merged_recv = peer_manager_recv.map(Either::A).map_err(|_| ()).select(timer_recv);
let merged_recv = peer_manager_recv.map(Either::A).map_err(|()| ()).select(timer_recv);

// Hook up a future that receives messages from the peer manager
core.handle().spawn(future::loop_fn(
Expand All @@ -183,23 +196,23 @@ fn main() {
info, message,
))),
Either::A(OPeerManagerMessage::PeerAdded(info)) => {
println!("Connected To Peer: {:?}", info);
println!("Connected To Peer: {info:?}");
Some(IUberMessage::Control(ControlMessage::PeerConnected(info)))
}
Either::A(OPeerManagerMessage::PeerRemoved(info)) => {
println!("We Removed Peer {:?} From The Peer Manager", info);
println!("We Removed Peer {info:?} From The Peer Manager");
Some(IUberMessage::Control(ControlMessage::PeerDisconnected(info)))
}
Either::A(OPeerManagerMessage::PeerDisconnect(info)) => {
println!("Peer {:?} Disconnected From Us", info);
println!("Peer {info:?} Disconnected From Us");
Some(IUberMessage::Control(ControlMessage::PeerDisconnected(info)))
}
Either::A(OPeerManagerMessage::PeerError(info, error)) => {
println!("Peer {:?} Disconnected With Error: {:?}", info, error);
println!("Peer {info:?} Disconnected With Error: {error:?}");
Some(IUberMessage::Control(ControlMessage::PeerDisconnected(info)))
}
Either::B(_) => Some(IUberMessage::Control(ControlMessage::Tick(Duration::from_millis(100)))),
_ => None,
Either::B(()) => Some(IUberMessage::Control(ControlMessage::Tick(Duration::from_millis(100)))),
Either::A(_) => None,
};

match opt_message {
Expand Down
35 changes: 20 additions & 15 deletions examples/simple_torrent/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ impl<S> Handshaker for LegacyHandshaker<S> where S: Sink<SinkItem=InitiateMessag
const MAX_PENDING_BLOCKS: usize = 50;

// Some enum to store our selection state updates
#[allow(dead_code)]
#[derive(Debug)]
enum SelectState {
Choke(PeerInfo),
Expand All @@ -84,9 +85,11 @@ enum SelectState {
TorrentAdded,
}

#[allow(clippy::too_many_lines)]
fn main() {
// Command line argument parsing
let matches = clap_app!(myapp =>

(version: "1.0")
(author: "Andrew <[email protected]>")
(about: "Simple torrent downloading")
Expand Down Expand Up @@ -130,7 +133,7 @@ fn main() {
// block when we reach our max peers). Setting these to low
// values so we don't have more than 2 unused tcp connections.
.with_config(HandshakerConfig::default().with_wait_buffer_size(0).with_done_buffer_size(0))
.build::<TcpTransport>(TcpTransport, core.handle()) // Will handshake over TCP (could swap this for UTP in the future)
.build::<TcpTransport>(TcpTransport, &core.handle()) // Will handshake over TCP (could swap this for UTP in the future)
.unwrap()
.into_parts();
// Create a peer manager that will hold our peers and heartbeat/send messages to them
Expand All @@ -146,7 +149,7 @@ fn main() {
let map_peer_manager_send = peer_manager_send.clone().sink_map_err(|_| ());
core.handle().spawn(
handshaker_recv
.map_err(|_| ())
.map_err(|()| ())
.map(|complete_msg| {
// Our handshaker finished handshaking some peer, get
// the peer info as well as the peer itself (socket)
Expand All @@ -173,7 +176,7 @@ fn main() {

// Map out the errors for these sinks so they match
let map_select_send = select_send.clone().sink_map_err(|_| ());
let map_disk_manager_send = disk_manager_send.clone().sink_map_err(|_| ());
let map_disk_manager_send = disk_manager_send.clone().sink_map_err(|()| ());

// Hook up a future that receives messages from the peer manager, and forwards request to the disk manager or selection manager (using loop fn
// here because we need to be able to access state, like request_map and a different future combinator wouldn't let us keep it around to access)
Expand Down Expand Up @@ -241,15 +244,15 @@ fn main() {
OPeerManagerMessage::PeerAdded(info) => Some(Either::A(SelectState::NewPeer(info))),
OPeerManagerMessage::SentMessage(_, _) => None,
OPeerManagerMessage::PeerRemoved(info) => {
println!("We Removed Peer {:?} From The Peer Manager", info);
println!("We Removed Peer {info:?} From The Peer Manager");
Some(Either::A(SelectState::RemovedPeer(info)))
}
OPeerManagerMessage::PeerDisconnect(info) => {
println!("Peer {:?} Disconnected From Us", info);
println!("Peer {info:?} Disconnected From Us");
Some(Either::A(SelectState::RemovedPeer(info)))
}
OPeerManagerMessage::PeerError(info, error) => {
println!("Peer {:?} Disconnected With Error: {:?}", info, error);
println!("Peer {info:?} Disconnected With Error: {error:?}");
Some(Either::A(SelectState::RemovedPeer(info)))
}
};
Expand Down Expand Up @@ -305,6 +308,7 @@ fn main() {
let peer_info = peer_list.remove(1);

// Pack up our block into a peer wire protocol message and send it off to the peer
#[allow(clippy::cast_possible_truncation)]
let piece =
PieceMessage::new(metadata.piece_index() as u32, metadata.block_offset() as u32, block.freeze());
let pwp_message = PeerWireProtocolMessage::Piece(piece);
Expand Down Expand Up @@ -360,13 +364,13 @@ fn main() {
match opt_item.unwrap() {
// Disk manager identified a good piece already downloaded
SelectState::GoodPiece(index) => {
piece_requests.retain(|req| req.piece_index() != index as u32);
piece_requests.retain(|req| u64::from(req.piece_index()) != index);
Loop::Continue((select_recv, piece_requests, cur_pieces + 1))
}
// Disk manager is finished identifying good pieces, torrent has been added
SelectState::TorrentAdded => Loop::Break((select_recv, piece_requests, cur_pieces)),
// Shouldn't be receiving any other messages...
message => panic!("Unexpected Message Received In Selection Receiver: {:?}", message),
message => panic!("Unexpected Message Received In Selection Receiver: {message:?}"),
}
})
.map_err(|_| ())
Expand Down Expand Up @@ -467,14 +471,14 @@ fn main() {
vec![IPeerManagerMessage::SendMessage(
peer,
0,
PeerWireProtocolMessage::Have(HaveMessage::new(piece as u32)),
PeerWireProtocolMessage::Have(HaveMessage::new(piece.try_into().unwrap())),
)]
} else {
vec![]
}
}
// Decided not to handle these two cases here
SelectState::RemovedPeer(info) => panic!("Peer {:?} Got Disconnected", info),
SelectState::RemovedPeer(info) => panic!("Peer {info:?} Got Disconnected"),
SelectState::BadPiece(_) => panic!("Peer Gave Us Bad Piece"),
_ => vec![],
};
Expand Down Expand Up @@ -507,11 +511,11 @@ fn main() {
Box::new(
map_peer_manager_send
.send_all(stream::iter_result(send_messages.into_iter().map(Ok::<_, ()>)))
.map_err(|_| ())
.map_err(|()| ())
.and_then(|(map_peer_manager_send, _)| {
map_peer_manager_send.send_all(stream::iter_result(next_piece_requests))
})
.map_err(|_| ())
.map_err(|()| ())
.map(move |(map_peer_manager_send, _)| {
Loop::Continue((
select_recv,
Expand Down Expand Up @@ -567,6 +571,7 @@ fn generate_requests(info: &Info, block_size: usize) -> Vec<RequestMessage> {
for block_index in 0..whole_blocks {
let block_offset = block_index * block_size as u64;

#[allow(clippy::cast_possible_truncation)]
requests.push(RequestMessage::new(piece_index as u32, block_offset as u32, block_size));
}

Expand All @@ -576,9 +581,9 @@ fn generate_requests(info: &Info, block_size: usize) -> Vec<RequestMessage> {
let block_offset = whole_blocks * block_size as u64;

requests.push(RequestMessage::new(
piece_index as u32,
block_offset as u32,
partial_block_length as usize,
piece_index.try_into().unwrap(),
block_offset.try_into().unwrap(),
partial_block_length.try_into().unwrap(),
));
}

Expand Down
4 changes: 2 additions & 2 deletions packages/bencode/src/access/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub trait BDictAccess<K, V> {

impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> {
fn to_list(&self) -> Vec<(&&'a [u8], &V)> {
self.iter().map(|(k, v)| (k, v)).collect()
self.iter().collect()
}

fn lookup(&self, key: &[u8]) -> Option<&V> {
Expand All @@ -43,7 +43,7 @@ impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> {

impl<'a, V> BDictAccess<Cow<'a, [u8]>, V> for BTreeMap<Cow<'a, [u8]>, V> {
fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> {
self.iter().map(|(k, v)| (k, v)).collect()
self.iter().collect()
}

fn lookup(&self, key: &[u8]) -> Option<&V> {
Expand Down
2 changes: 1 addition & 1 deletion packages/bencode/src/reference/decode_opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl BDecodeOpt {
///
/// It may be useful to disable this if for example, the input bencode is prepended to
/// some payload and you would like to disassociate it. In this case, to find where the
/// rest of the payload starts that wasn't decoded, get the bencode buffer, and call len().
/// rest of the payload starts that wasn't decoded, get the bencode buffer, and call `len()`.
#[must_use]
pub fn enforce_full_decode(&self) -> bool {
self.enforce_full_decode
Expand Down
4 changes: 2 additions & 2 deletions packages/dht/examples/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl HandshakerTrait for SimpleHandshaker {
}

/// Send the given Metadata back to the client.
fn metadata(&mut self, _: Self::MetadataEnvelope) {}
fn metadata(&mut self, (): Self::MetadataEnvelope) {}
}

fn main() {
Expand All @@ -80,7 +80,7 @@ fn main() {
let events = dht.events();
thread::spawn(move || {
for event in events {
println!("\nReceived Dht Event {:?}", event);
println!("\nReceived Dht Event {event:?}");
}
});

Expand Down
5 changes: 5 additions & 0 deletions packages/dht/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ impl Drop for MainlineDht {
// ----------------------------------------------------------------------------//

/// Stores information for initializing a DHT.
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Debug)]
pub struct DhtBuilder {
nodes: HashSet<SocketAddr>,
Expand Down Expand Up @@ -193,6 +194,10 @@ impl DhtBuilder {
}

/// Start a mainline DHT with the current configuration.
///
/// # Errors
///
/// It would return error if unable to build from the handshaker.
pub fn start_mainline<H>(self, handshaker: H) -> io::Result<MainlineDht>
where
H: HandshakerTrait + 'static,
Expand Down
15 changes: 14 additions & 1 deletion packages/dht/src/message/announce_peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub enum ConnectPort {
Explicit(u16),
}

#[allow(clippy::module_name_repetitions)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct AnnouncePeerRequest<'a> {
trans_id: &'a [u8],
Expand Down Expand Up @@ -46,6 +47,11 @@ impl<'a> AnnouncePeerRequest<'a> {
}
}

/// Generate a `AnnouncePeerRequest` from parts
///
/// # Errors
///
/// This function will return an error unable to get bytes unable do lookup.
pub fn from_parts<B>(rqst_root: &'a dyn BDictAccess<B::BKey, B>, trans_id: &'a [u8]) -> DhtResult<AnnouncePeerRequest<'a>>
where
B: BRefAccess,
Expand All @@ -67,7 +73,8 @@ impl<'a> AnnouncePeerRequest<'a> {
Some(Some(n)) if n != 0 => ConnectPort::Implied,
_ => {
// If we hit this, the port either was not provided or it was of the wrong bencode type
let port_number = port? as u16;
#[allow(clippy::cast_possible_truncation)]
let port_number = (port?).unsigned_abs() as u16;
ConnectPort::Explicit(port_number)
}
};
Expand Down Expand Up @@ -126,6 +133,7 @@ impl<'a> AnnouncePeerRequest<'a> {
}
}

#[allow(clippy::module_name_repetitions)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct AnnouncePeerResponse<'a> {
trans_id: &'a [u8],
Expand All @@ -138,6 +146,11 @@ impl<'a> AnnouncePeerResponse<'a> {
AnnouncePeerResponse { trans_id, node_id }
}

/// Generate a `AnnouncePeerResponse` from parts
///
/// # Errors
///
/// This function will return an error unable to get bytes or unable to validate the node id.
pub fn from_parts<B>(rqst_root: &dyn BDictAccess<B::BKey, B>, trans_id: &'a [u8]) -> DhtResult<AnnouncePeerResponse<'a>>
where
B: BRefAccess,
Expand Down
Loading

0 comments on commit 67ad620

Please sign in to comment.