diff --git a/README.md b/README.md index c6875f0b..bc761aaf 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,8 @@ [s6]: https://tokei.rs/b1/github/amethyst/laminar?category=code [s7]: https://codecov.io/gh/amethyst/laminar/branch/master/graphs/badge.svg -Laminar is a semi-reliable UDP-based protocol for multiplayer games. This library implements wrappers around the UDP-protocol, -and provides a lightweight, message-based interface which provides certain guarantees like reliability and ordering. +Laminar is an application-level transport protocol which provides configurable reliability and ordering guarantees built on top of UDP. +It focuses on fast-paced fps-games and provides a lightweight, message-based interface. Laminar was designed to be used within the [Amethyst][amethyst] game engine but is usable without it. @@ -103,25 +103,25 @@ _Send packets_ ```rust use laminar::{Socket, Packet}; -// create the socket +// Creates the socket let mut socket = Socket::bind("127.0.0.1:12345")?; let packet_sender = socket.get_packet_sender(); -// this will start the socket, which will start a poll mechanism to receive and send messages. +// Starts the socket, which will start a poll mechanism to receive and send messages. let _thread = thread::spawn(move || socket.start_polling()); -// our data +// Bytes to sent let bytes = vec![...]; -// You can create packets with different reliabilities +// Creates packets with different reliabilities let unreliable = Packet::unreliable(destination, bytes); let reliable = Packet::reliable_unordered(destination, bytes); -// We can specify on which stream and how to order our packets, checkout our book and documentation for more information +// Specifies on which stream and how to order our packets, checkout our book and documentation for more information let unreliable = Packet::unreliable_sequenced(destination, bytes, Some(1)); let reliable_sequenced = Packet::reliable_sequenced(destination, bytes, Some(2)); let reliable_ordered = Packet::reliable_ordered(destination, bytes, Some(3)); -// send the created packets +// Sends the created packets packet_sender.send(unreliable_sequenced).unwrap(); packet_sender.send(reliable).unwrap(); packet_sender.send(unreliable_sequenced).unwrap(); @@ -133,13 +133,13 @@ _Receive Packets_ ```rust use laminar::{SocketEvent, Socket}; -// create the socket +// Creates the socket let socket = Socket::bind("127.0.0.1:12346")?; let event_receiver = socket.get_event_receiver(); -// this will start the socket, which will start a poll mechanism to receive and send messages. +// Starts the socket, which will start a poll mechanism to receive and send messages. let _thread = thread::spawn(move || socket.start_polling()); -// wait until a socket event occurs +// Waits until a socket event occurs let result = event_receiver.recv(); match result { diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 1756e8b9..0b66d0c8 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -34,6 +34,10 @@ Some code guidelines to keep in mind when contributing to laminar or amethyst-ne - Keep comments small - Don’t create unnecessary comments. They must add value - Comments should explain the “why” not the “what” + - All `///` comments should start capitilized and end with an 'dot'. + - Function comments should be plural like: 'Returns', 'Creates', 'Instantiates' etc. + - All `//` explain code 'in' functions should have no capital letter and not 'dot' + - Referenced types, functions, variables should be put inside '`code markup`'. 2. Hard Coding - Don't hard code values anywhere - Use the ‘NetworkConfig’ type for common network settings, use consts or parameter input @@ -41,3 +45,35 @@ Some code guidelines to keep in mind when contributing to laminar or amethyst-ne 3. Code markup - Keep files small. Better have small files with small pieces of logic than having one file with 1000 lines of logic with multiple types/structs etc. Note that I speak of logic, tests not included - No panics/unwraps in the main codebase, but they are accepted in tests + +## Import Reordering +All imports are semantically grouped and ordered. The order is: + +- standard library (`use std::...`) +- external crates (`use rand::...`) +- current crate (`use crate::...`) +- parent module (`use super::..`) +- current module (`use self::...`) +- module declaration (`mod ...`) + +There must be an empty line between groups. An example: + +```rust +use crossterm_utils::{csi, write_cout, Result}; + +use crate::sys::{get_cursor_position, show_cursor}; + +use super::Cursor; +``` + +#### CLion Tips + +The CLion IDE does this for you (_Menu_ -> _Code_ -> _Optimize Imports_). Be aware that the CLion sorts +imports in a group in a different way when compared to the `rustfmt`. It's effectively two steps operation +to get proper grouping & sorting: + +* _Menu_ -> _Code_ -> _Optimize Imports_ - group & semantically order imports +* `cargo fmt` - fix ordering within the group + +Second step can be automated via _CLion_ -> _Preferences_ -> +_Languages & Frameworks_ -> _Rust_ -> _Rustfmt_ -> _Run rustfmt on save_. \ No newline at end of file diff --git a/docs/md_book/src/reliability/reliability.md b/docs/md_book/src/reliability/reliability.md index eecf79a2..299e1d11 100644 --- a/docs/md_book/src/reliability/reliability.md +++ b/docs/md_book/src/reliability/reliability.md @@ -100,11 +100,11 @@ Basically this is almost TCP-like but then sequencing instead of ordering. ```rust use laminar::Packet; -// You can create packets with different reliabilities +// Creates packets with different reliabilities let unreliable = Packet::unreliable(destination, bytes); let reliable = Packet::reliable_unordered(destination, bytes); -// We can specify on which stream and how to order our packets, checkout our book and documentation for more information +// Specifies on which stream and how to order our packets, checkout our book and documentation for more information let unreliable = Packet::unreliable_sequenced(destination, bytes, Some(1)); let reliable_sequenced = Packet::reliable_sequenced(destination, bytes, Some(2)); let reliable_ordered = Packet::reliable_ordered(destination, bytes, Some(3)); diff --git a/src/bin/laminar-tester.rs b/src/bin/laminar-tester.rs index bb48ede4..c9f078a9 100644 --- a/src/bin/laminar-tester.rs +++ b/src/bin/laminar-tester.rs @@ -149,7 +149,7 @@ fn run_server(server_config: ServerConfiguration) -> Result<()> { fn run_client(config: ClientConfiguration) -> Result<()> { let socket = Socket::bind(config.listen_host)?; - // See which test we want to run + // see which test we want to run match config.test_name.as_str() { "steady-stream" => { test_steady_stream(config, socket); diff --git a/src/config.rs b/src/config.rs index 43750153..10e6c8b3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -7,14 +7,14 @@ use crate::net::constants::{DEFAULT_MTU, FRAGMENT_SIZE_DEFAULT, MAX_FRAGMENTS_DE pub struct Config { /// Make the underlying UDP socket block when true, otherwise non-blocking. pub blocking_mode: bool, - /// Value which can specify the amount of time that can pass without hearing from a client before considering them disconnected + /// Value which can specify the amount of time that can pass without hearing from a client before considering them disconnected. pub idle_connection_timeout: Duration, /// Value which specifies at which interval (if at all) a heartbeat should be sent, if no other packet was sent in the meantime. /// If None, no heartbeats will be sent (the default). pub heartbeat_interval: Option, /// Value which can specify the maximum size a packet can be in bytes. This value is inclusive of fragmenting; if a packet is fragmented, the total size of the fragments cannot exceed this value. /// - /// Recommended value: 16384 + /// Recommended value: 16384. pub max_packet_size: usize, /// Value which can specify the maximal allowed fragments. /// @@ -28,7 +28,7 @@ pub struct Config { /// /// This is the maximum size of each fragment. It defaults to `1450` bytes, due to the default MTU on most network devices being `1500`. pub fragment_size: u16, - /// Value which can specify the size of the buffer that queues up fragments ready to be reassembled once all fragments have arrived.``` + /// Value which can specify the size of the buffer that queues up fragments ready to be reassembled once all fragments have arrived. pub fragment_reassembly_buffer_size: u16, /// Value that specifies the size of the buffer the UDP data will be read into. Defaults to `1450` bytes. pub receive_buffer_max_size: usize, @@ -53,7 +53,7 @@ pub struct Config { /// connection. /// /// When we send a reliable packet, it is stored locally until an acknowledgement comes back to - /// us, if that store grows to a size + /// us, if that store grows to a size. pub max_packets_in_flight: u16, } diff --git a/src/infrastructure/acknowledgment.rs b/src/infrastructure/acknowledgment.rs index a3c830d2..5df069d7 100644 --- a/src/infrastructure/acknowledgment.rs +++ b/src/infrastructure/acknowledgment.rs @@ -8,15 +8,15 @@ const DEFAULT_SEND_PACKETS_SIZE: usize = 256; /// Responsible for handling the acknowledgment of packets. pub struct AcknowledgmentHandler { - // Local sequence number which we'll bump each time we send a new packet over the network + // Local sequence number which we'll bump each time we send a new packet over the network. sequence_number: SequenceNumber, // The last acked sequence number of the packets we've sent to the remote host. remote_ack_sequence_num: SequenceNumber, - // Using a Hashmap to track every packet we send out so we can ensure that we can resend when + // Using a `Hashmap` to track every packet we send out so we can ensure that we can resend when // dropped. sent_packets: HashMap, - // However, we can only reasonably ack up to REDUNDANT_PACKET_ACKS_SIZE + 1 packets on each - // message we send so this should be that large + // However, we can only reasonably ack up to `REDUNDANT_PACKET_ACKS_SIZE + 1` packets on each + // message we send so this should be that large. received_packets: SequenceBuffer, } @@ -31,7 +31,7 @@ impl AcknowledgmentHandler { } } - /// Get the current number of not yet acknowledged packets + /// Returns the current number of not yet acknowledged packets pub fn packets_in_flight(&self) -> u16 { self.sent_packets.len() as u16 } @@ -46,14 +46,14 @@ impl AcknowledgmentHandler { self.received_packets.sequence_num().wrapping_sub(1) } - /// Returns the ack_bitfield corresponding to which of the past 32 packets we've + /// Returns the `ack_bitfield` corresponding to which of the past 32 packets we've /// successfully received. pub fn ack_bitfield(&self) -> u32 { let most_recent_remote_seq_num: u16 = self.remote_sequence_num(); let mut ack_bitfield: u32 = 0; let mut mask: u32 = 1; - // Iterate the past REDUNDANT_PACKET_ACKS_SIZE received packets and set the corresponding + // iterate the past `REDUNDANT_PACKET_ACKS_SIZE` received packets and set the corresponding // bit for each packet which exists in the buffer. for i in 1..=REDUNDANT_PACKET_ACKS_SIZE { let sequence = most_recent_remote_seq_num.wrapping_sub(i); @@ -76,7 +76,7 @@ impl AcknowledgmentHandler { remote_ack_seq: u16, mut remote_ack_field: u32, ) { - // We must ensure that self.remote_ack_sequence_num is always increasing (with wrapping) + // ensure that `self.remote_ack_sequence_num` is always increasing (with wrapping) if sequence_greater_than(remote_ack_seq, self.remote_ack_sequence_num) { self.remote_ack_sequence_num = remote_ack_seq; } @@ -84,10 +84,10 @@ impl AcknowledgmentHandler { self.received_packets .insert(remote_seq_num, ReceivedPacket {}); - // The current remote_ack_seq was (clearly) received so we should remove it. + // the current `remote_ack_seq` was (clearly) received so we should remove it self.sent_packets.remove(&remote_ack_seq); - // The remote_ack_field is going to include whether or not the past 32 packets have been + // The `remote_ack_field` is going to include whether or not the past 32 packets have been // received successfully. If so, we have no need to resend old packets. for i in 1..=REDUNDANT_PACKET_ACKS_SIZE { let ack_sequence = remote_ack_seq.wrapping_sub(i); @@ -98,7 +98,7 @@ impl AcknowledgmentHandler { } } - /// Enqueue the outgoing packet for acknowledgment. + /// Enqueues the outgoing packet for acknowledgment. pub fn process_outgoing( &mut self, packet_type: PacketType, @@ -116,7 +116,7 @@ impl AcknowledgmentHandler { }, ); - // Bump the local sequence number for the next outgoing packet. + // bump the local sequence number for the next outgoing packet self.sequence_number = self.sequence_number.wrapping_add(1); } diff --git a/src/infrastructure/arranging/ordering.rs b/src/infrastructure/arranging/ordering.rs index 3a1d960d..34fa6ccb 100644 --- a/src/infrastructure/arranging/ordering.rs +++ b/src/infrastructure/arranging/ordering.rs @@ -130,12 +130,12 @@ impl<'a, T> ArrangingSystem for OrderingSystem { /// # Remarks /// - See [super-module](../index.html) for more information about streams. pub struct OrderingStream { - // the id of this stream. + // The id of this stream. _stream_id: u8, - // the storage for items that are waiting for older items to arrive. - // the items will be stored by key and value where the key is the incoming index and the value is the item value. + // Storage with items that are waiting for older items to arrive. + // Items are stored by key and value where the key is the incoming index and the value is the item value. storage: HashMap, - // the next expected item index. + // Next expected item index. expected_index: u16, // unique identifier which should be used for ordering on a different stream e.g. the remote endpoint. unique_item_identifier: u16, @@ -220,15 +220,14 @@ impl OrderingStream { } fn is_u16_within_half_window_from_start(start: u16, incoming: u16) -> bool { - // Check (with wrapping) if the incoming value lies within the next u16::max_value()/2 from - // start. + // check (with wrapping) if the incoming value lies within the `next u16::max_value()/2` from start incoming.wrapping_sub(start) <= u16::max_value() / 2 + 1 } impl Arranging for OrderingStream { type ArrangingItem = T; - /// Will order the given item based on the ordering algorithm. + /// Orders the given item based on the ordering algorithm. /// /// With every ordering operation an `incoming_index` is given. We also keep a local record of the `expected_index`. /// diff --git a/src/infrastructure/arranging/sequencing.rs b/src/infrastructure/arranging/sequencing.rs index 7a097991..02fa16bb 100644 --- a/src/infrastructure/arranging/sequencing.rs +++ b/src/infrastructure/arranging/sequencing.rs @@ -43,7 +43,7 @@ impl ArrangingSystem for SequencingSystem { self.streams.len() } - /// Try to get an [`SequencingStream`](./struct.SequencingStream.html) by `stream_id`. + /// Tries to get an [`SequencingStream`](./struct.SequencingStream.html) by `stream_id`. /// When the stream does not exist, it will be inserted by the given `stream_id` and returned. fn get_or_create_stream(&mut self, stream_id: u8) -> &mut Self::Stream { self.streams @@ -73,7 +73,7 @@ pub struct SequencingStream { _stream_id: u8, // the highest seen item index. top_index: u16, - // I need `PhantomData`, otherwise, I can't use a generic in the `Arranging` implementation because `T` is not constrained. + // Needs `PhantomData`, otherwise, it can't use a generic in the `Arranging` implementation because `T` is not constrained. phantom: PhantomData, // unique identifier which should be used for ordering on an other stream e.g. the remote endpoint. unique_item_identifier: u16, @@ -107,7 +107,7 @@ impl SequencingStream { } fn is_u16_within_half_window_from_start(start: u16, incoming: u16) -> bool { - // Check (with wrapping) if the incoming value lies within the next u16::max_value()/2 from + // check (with wrapping) if the incoming value lies within the next u16::max_value()/2 from // start. incoming.wrapping_sub(start) <= u16::max_value() / 2 + 1 } @@ -115,7 +115,7 @@ fn is_u16_within_half_window_from_start(start: u16, incoming: u16) -> bool { impl Arranging for SequencingStream { type ArrangingItem = T; - /// Will arrange the given item based on a sequencing algorithm. + /// Arranges the given item based on a sequencing algorithm. /// /// With every sequencing operation an `top_index` is given. /// diff --git a/src/infrastructure/congestion.rs b/src/infrastructure/congestion.rs index f3cdcf01..20ea0033 100644 --- a/src/infrastructure/congestion.rs +++ b/src/infrastructure/congestion.rs @@ -6,7 +6,7 @@ use crate::{ Config, }; -/// Type that is responsible for keeping track of congestion information. +/// Keeps track of congestion information. pub struct CongestionHandler { rtt_measurer: RttMeasurer, congestion_data: SequenceBuffer, @@ -23,7 +23,7 @@ impl CongestionHandler { } } - /// Process incoming sequence number. + /// Processes incoming sequence number. /// /// This will calculate the RTT-time and smooth down the RTT-value to prevent uge RTT-spikes. pub fn process_incoming(&mut self, incoming_seq: u16) { @@ -31,7 +31,7 @@ impl CongestionHandler { self.rtt_measurer.calculate_rrt(congestion_data); } - /// Process outgoing sequence number. + /// Processes outgoing sequence number. /// /// This will insert an entry which is used for keeping track of the sending time. /// Once we process incoming sequence numbers we can calculate the `RTT` time. diff --git a/src/infrastructure/fragmenter.rs b/src/infrastructure/fragmenter.rs index af67f593..80a0c030 100644 --- a/src/infrastructure/fragmenter.rs +++ b/src/infrastructure/fragmenter.rs @@ -8,7 +8,7 @@ use crate::{ sequence_buffer::{ReassemblyData, SequenceBuffer}, }; -/// Type that will manage fragmentation of packets. +/// Manages fragmentation of packets. pub struct Fragmentation { fragments: SequenceBuffer, config: Config, @@ -23,7 +23,7 @@ impl Fragmentation { } } - /// This functions checks how many times a number fits into another number and will round up. + /// Checks how many times a number fits into another number and will round up. /// /// For example we have two numbers: /// - number 1 = 4000; @@ -61,7 +61,7 @@ impl Fragmentation { ((payload_length / fragment_size) + remainder) } - /// Split the given payload into fragments and write those fragments to the passed packet data. + /// Splits the given payload into fragments and write those fragments to the passed packet data. pub fn spit_into_fragments<'a>(payload: &'a [u8], config: &Config) -> Result> { let mut fragments = Vec::new(); @@ -93,7 +93,7 @@ impl Fragmentation { Ok(fragments) } - /// This will read fragment data and return the complete packet when all fragments are received. + /// Reads fragment data and return the complete packet when all fragments are received. pub fn handle_fragment( &mut self, fragment_header: FragmentHeader, @@ -116,7 +116,7 @@ impl Fragmentation { None => return Err(FragmentErrorKind::CouldNotFindFragmentById.into()), }; - // Got the data + // got the data if reassembly_data.num_fragments_total != fragment_header.fragment_count() { return Err(FragmentErrorKind::FragmentWithUnevenNumberOfFragments.into()); } @@ -129,7 +129,7 @@ impl Fragmentation { return Err(FragmentErrorKind::AlreadyProcessedFragment.into()); } - // increase number of received fragments and set the specific fragment to received. + // increase number of received fragments and set the specific fragment to received reassembly_data.num_fragments_received += 1; reassembly_data.fragments_received[usize::from(fragment_header.id())] = true; diff --git a/src/lib.rs b/src/lib.rs index a68bec8d..e5c99fbf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ -//! Laminar is a semi-reliable UDP-based protocol for multiplayer games. This library implements wrappers around the UDP-protocol, -//! and provides a lightweight, message-based interface which provides certain guarantees like reliability and ordering. +//! Laminar is an application-level transport protocol which provides configurable reliability and ordering guarantees built on top of UDP. +//! It focuses on fast-paced fps-games and provides a lightweight, message-based interface. //! //! Laminar was designed to be used within the [Amethyst][amethyst] game engine but is usable without it. //! diff --git a/src/net/connection_impl.rs b/src/net/connection_impl.rs index b283f2e5..4cc0ebc9 100644 --- a/src/net/connection_impl.rs +++ b/src/net/connection_impl.rs @@ -12,7 +12,7 @@ use super::{ /// Required by `ConnectionManager` to properly handle connection event. impl ConnectionEventAddress for SocketEvent { - /// Returns event address + /// Returns event address. fn address(&self) -> SocketAddr { match self { SocketEvent::Packet(packet) => packet.addr(), @@ -24,7 +24,7 @@ impl ConnectionEventAddress for SocketEvent { /// Required by `ConnectionManager` to properly handle user event. impl ConnectionEventAddress for Packet { - /// Returns event address + /// Returns event address. fn address(&self) -> SocketAddr { self.addr() } @@ -46,7 +46,7 @@ impl Connection for VirtualConnection { time: Instant, initial_data: Option<&[u8]>, ) -> VirtualConnection { - // Emit connect event if this is initiated by the remote host. + // emit connect event if this is initiated by the remote host. if initial_data.is_some() { messenger.send_event(&address, SocketEvent::Connect(address)); } @@ -125,15 +125,15 @@ impl Connection for VirtualConnection { messenger: &mut impl ConnectionMessenger, time: Instant, ) { - // Resend dropped packets + // resend dropped packets for dropped in self.gather_dropped_packets() { let packets = self.process_outgoing( PacketInfo { packet_type: dropped.packet_type, payload: &dropped.payload, - // Because a delivery guarantee is only sent with reliable packets + // because a delivery guarantee is only sent with reliable packets delivery: DeliveryGuarantee::Reliable, - // This is stored with the dropped packet because they could be mixed + // this is stored with the dropped packet because they could be mixed ordering: dropped.ordering_guarantee, }, dropped.item_identifier, @@ -142,7 +142,7 @@ impl Connection for VirtualConnection { send_packets(messenger, &self.remote_address, packets, "dropped packets"); } - // Send heartbeat packets if required + // send heartbeat packets if required if let Some(heartbeat_interval) = messenger.config().heartbeat_interval { let addr = self.remote_address; if self.last_sent(time) >= heartbeat_interval { diff --git a/src/net/connection_manager.rs b/src/net/connection_manager.rs index a0158f1c..60adef47 100644 --- a/src/net/connection_manager.rs +++ b/src/net/connection_manager.rs @@ -22,7 +22,7 @@ pub trait DatagramSocket: Debug { /// Returns the socket address that this socket was created from. fn local_addr(&self) -> Result; - /// Returns whether socket operates in blocking or nonblocking mode. + /// Returns whether socket operates in blocking or non-blocking mode. fn is_blocking_mode(&self) -> bool; } @@ -73,9 +73,7 @@ pub struct ConnectionManager { receive_buffer: Vec, user_event_receiver: Receiver, messenger: SocketEventSenderAndConfig, - // Stores event receiver, so that user can clone it. event_receiver: Receiver, - // Stores event sender, so that user can clone it. user_event_sender: Sender, } @@ -94,12 +92,12 @@ impl ConnectionManager ConnectionManager ConnectionManager ConnectionManager| { for id in 0..100 { @@ -803,7 +801,7 @@ mod tests { set.len() }; - // The first chatting sequence sends packets 0..100 from the client to the server. After + // the first chatting sequence sends packets 0..100 from the client to the server. After // this we just chat with a value of 255 so we don't accidentally overlap those chatting // packets with the packets we want to ack. send_many_packets(None); @@ -882,7 +880,7 @@ mod tests { .unwrap(); server.manual_poll(time); assert![client.recv().is_some()]; - // If the last iteration returns None here, it indicates we just received a re-sent + // If the last iteration returns `None` here, it indicates we just received a re-sent // fragment, because `manual_poll` only processes a single incoming UDP packet per // `manual_poll` if and only if the socket is in blocking mode. // diff --git a/src/net/quality.rs b/src/net/quality.rs index 15f16d15..adf73668 100644 --- a/src/net/quality.rs +++ b/src/net/quality.rs @@ -6,9 +6,9 @@ use crate::sequence_buffer::CongestionData; /// Represents the quality of a network. #[allow(dead_code)] pub enum NetworkQuality { - /// Connection is generally good, minimal packet loss or latency + /// Connection is generally good, minimal packet loss or latency. Good, - /// Connection is generally bad, having an impact on game performance + /// Connection is generally bad, having an impact on game performance. Bad, } @@ -20,7 +20,7 @@ pub struct RttMeasurer { } impl RttMeasurer { - /// Creates and returns a new RttMeasurer + /// Creates and returns a new RttMeasurer. pub fn new(config: &Config) -> RttMeasurer { RttMeasurer { config: config.clone(), @@ -28,8 +28,8 @@ impl RttMeasurer { } } - /// This will calculate the round trip time (rtt) from the given acknowledgment. - /// Where after it updates the rtt from the given connection. + /// Calculates the round trip time (rtt) from the given acknowledgment. + /// Whereafter it updates the rtt from the given connection. pub fn calculate_rrt(&mut self, congestion_data: Option<&mut CongestionData>) { self.rtt = self.get_smoothed_rtt(congestion_data); } @@ -62,7 +62,7 @@ impl RttMeasurer { (1000 * 1000 * 1000 * duration.as_secs() + nanos) / (1000 * 1000) } - /// Smooth out round trip time (rtt) value by the specified smoothing factor. + /// Smooths out round trip time (rtt) value by the specified smoothing factor. /// /// First we subtract the max allowed rtt. /// This way we can see by how many we are off from the max allowed rtt. diff --git a/src/net/socket.rs b/src/net/socket.rs index 530beea0..77281477 100644 --- a/src/net/socket.rs +++ b/src/net/socket.rs @@ -16,7 +16,7 @@ use crate::{ packet::Packet, }; -// Wrap `LinkConditioner` and `UdpSocket` together. LinkConditioner is enabled when building with a "tester" feature. +// Wraps `LinkConditioner` and `UdpSocket` together. LinkConditioner is enabled when building with a "tester" feature. #[derive(Debug)] struct SocketWithConditioner { is_blocking_mode: bool, @@ -42,7 +42,7 @@ impl SocketWithConditioner { /// Provides a `DatagramSocket` implementation for `SocketWithConditioner` impl DatagramSocket for SocketWithConditioner { - // When `LinkConditioner` is enabled, it will determine whether packet will be sent or not. + // Determinate whether packet will be sent or not based on `LinkConditioner` if enabled. fn send_packet(&mut self, addr: &SocketAddr, payload: &[u8]) -> std::io::Result { if cfg!(feature = "tester") { if let Some(ref mut link) = &mut self.link_conditioner { @@ -54,7 +54,7 @@ impl DatagramSocket for SocketWithConditioner { self.socket.send_to(payload, addr) } - /// Receive a single packet from UDP socket. + /// Receives a single packet from UDP socket. fn receive_packet<'a>( &mut self, buffer: &'a mut [u8], @@ -69,7 +69,7 @@ impl DatagramSocket for SocketWithConditioner { self.socket.local_addr() } - /// Returns whether socket operates in blocking or nonblocking mode. + /// Returns whether socket operates in blocking or non-blocking mode. fn is_blocking_mode(&self) -> bool { self.is_blocking_mode } @@ -89,12 +89,12 @@ impl Socket { Self::bind_with_config(addresses, Config::default()) } - /// Bind to any local port on the system, if available + /// Binds to any local port on the system, if available pub fn bind_any() -> Result { Self::bind_any_with_config(Config::default()) } - /// Bind to any local port on the system, if available, with a given config + /// Binds to any local port on the system, if available, with a given config pub fn bind_any_with_config(config: Config) -> Result { let loopback = Ipv4Addr::new(127, 0, 0, 1); let address = SocketAddrV4::new(loopback, 0); @@ -135,7 +135,7 @@ impl Socket { self.handler.event_receiver().clone() } - /// Send a packet + /// Sends a single packet pub fn send(&mut self, packet: Packet) -> Result<()> { self.handler .event_sender() @@ -144,7 +144,7 @@ impl Socket { Ok(()) } - /// Receive a packet + /// Receives a single packet pub fn recv(&mut self) -> Option { match self.handler.event_receiver().try_recv() { Ok(pkt) => Some(pkt), @@ -153,18 +153,18 @@ impl Socket { } } - /// Entry point to the run loop. This should run in a spawned thread since calls to `poll.poll` - /// are blocking. We will default this to sleeping for 1ms. + /// Runs the polling loop with the default '1ms' sleep duration. This should run in a spawned thread + /// since calls to `self.manual_poll` are blocking. pub fn start_polling(&mut self) { self.start_polling_with_duration(Some(Duration::from_millis(1))) } - /// Run the polling loop with a specified sleep duration. This should run in a spawned thread - /// since calls to `poll.poll` are blocking. + /// Runs the polling loop with a specified sleep duration. This should run in a spawned thread + /// since calls to `self.manual_poll` are blocking. pub fn start_polling_with_duration(&mut self, sleep_duration: Option) { - // Nothing should break out of this loop! + // nothing should break out of this loop! loop { - self.handler.manual_poll(Instant::now()); + self.manual_poll(Instant::now()); match sleep_duration { None => yield_now(), Some(duration) => sleep(duration), @@ -172,7 +172,7 @@ impl Socket { } } - /// Process any inbound/outbound packets and handle idle clients + /// Processes any inbound/outbound packets and handle idle clients pub fn manual_poll(&mut self, time: Instant) { self.handler.manual_poll(time); } @@ -182,7 +182,7 @@ impl Socket { Ok(self.handler.socket().local_addr()?) } - /// Set the link conditioner for this socket. See [LinkConditioner] for further details. + /// Sets the link conditioner for this socket. See [LinkConditioner] for further details. #[cfg(feature = "tester")] pub fn set_link_conditioner(&mut self, link_conditioner: Option) { self.handler diff --git a/src/net/virtual_connection.rs b/src/net/virtual_connection.rs index 0742e15b..0f363a11 100644 --- a/src/net/virtual_connection.rs +++ b/src/net/virtual_connection.rs @@ -60,19 +60,19 @@ impl VirtualConnection { /// Returns a [Duration] representing the interval since we last heard from the client pub fn last_heard(&self, time: Instant) -> Duration { - // TODO: Replace with saturating_duration_since once it becomes stable. - // This function panics if the user supplies a time instant earlier than last_heard. + // TODO: Replace with `saturating_duration_since` once it becomes stable. + // this function panics if the user supplies a time instant earlier than last_heard time.duration_since(self.last_heard) } /// Returns a [Duration] representing the interval since we last sent to the client pub fn last_sent(&self, time: Instant) -> Duration { - // TODO: Replace with saturating_duration_since once it becomes stable. - // This function panics if the user supplies a time instant earlier than last_heard. + // TODO: Replace with `saturating_duration_since` once it becomes stable. + // this function panics if the user supplies a time instant earlier than last_heard time.duration_since(self.last_sent) } - /// This will pre-process the given buffer to be sent over the network. + /// Pre-processes the given buffer to be sent over the network. pub fn process_outgoing<'a>( &mut self, packet: PacketInfo<'a>, @@ -84,7 +84,6 @@ impl VirtualConnection { DeliveryGuarantee::Unreliable => { if packet.payload.len() <= self.config.receive_buffer_max_size { if packet.packet_type == PacketType::Heartbeat { - // TODO (bug?) is this really required here? self.congestion_handler .process_outgoing(self.acknowledge_handler.local_sequence_num(), time); } @@ -218,7 +217,7 @@ impl VirtualConnection { } } - /// This processes the incoming data and returns a packet if the data is complete. + /// Processes the incoming data and returns a packet once the data is complete. pub fn process_incoming( &mut self, received_data: &[u8], @@ -235,8 +234,8 @@ impl VirtualConnection { } if header.is_heartbeat() { - // Heartbeat packets are unreliable, unordered and empty packets. - // We already updated our `self.last_heard` time, nothing else to be done. + // heartbeat packets are unreliable, unordered and empty packets. + // we already updated our `self.last_heard` time, nothing else to be done. return Ok(IncomingPackets::zero()); } @@ -399,7 +398,7 @@ impl VirtualConnection { Ok(IncomingPackets::zero()) } - /// This will gather dropped packets from the acknowledgment handler. + /// Gathers dropped packets from the acknowledgment handler. /// /// Note that after requesting dropped packets the dropped packets will be removed from this client. pub fn gather_dropped_packets(&mut self) -> Vec { diff --git a/src/packet/enums.rs b/src/packet/enums.rs index 86ee296c..f6b8fc34 100644 --- a/src/packet/enums.rs +++ b/src/packet/enums.rs @@ -17,7 +17,7 @@ pub enum DeliveryGuarantee { impl EnumConverter for DeliveryGuarantee { type Enum = DeliveryGuarantee; - /// Get integer value from `DeliveryGuarantee` enum. + /// Returns an integer value from `DeliveryGuarantee` enum. fn to_u8(&self) -> u8 { *self as u8 } @@ -25,7 +25,7 @@ impl EnumConverter for DeliveryGuarantee { impl TryFrom for DeliveryGuarantee { type Error = ErrorKind; - /// Get `DeliveryGuarantee` enum instance from integer value. + /// Gets the `DeliveryGuarantee` enum instance from integer value. fn try_from(value: u8) -> Result { match value { 0 => Ok(DeliveryGuarantee::Unreliable), @@ -57,7 +57,7 @@ impl Default for OrderingGuarantee { impl EnumConverter for OrderingGuarantee { type Enum = OrderingGuarantee; - /// Get integer value from `OrderingGuarantee` enum. + /// Returns the integer value from `OrderingGuarantee` enum. fn to_u8(&self) -> u8 { match self { OrderingGuarantee::None => 0, @@ -69,7 +69,7 @@ impl EnumConverter for OrderingGuarantee { impl TryFrom for OrderingGuarantee { type Error = ErrorKind; - /// Get `OrderingGuarantee` enum instance from integer value. + /// Returns the `OrderingGuarantee` enum instance from integer value. fn try_from(value: u8) -> Result { match value { 0 => Ok(OrderingGuarantee::None), diff --git a/src/packet/header/acked_packet_header.rs b/src/packet/header/acked_packet_header.rs index b4a538fc..9e807313 100644 --- a/src/packet/header/acked_packet_header.rs +++ b/src/packet/header/acked_packet_header.rs @@ -8,13 +8,13 @@ use crate::net::constants::ACKED_PACKET_HEADER; use super::{HeaderReader, HeaderWriter}; #[derive(Copy, Clone, Debug)] -/// This header providing reliability information. +/// This header provides reliability information. pub struct AckedPacketHeader { - /// this is the sequence number so that we can know where in the sequence of packages this packet belongs. + /// This is the sequence number so that we can know where in the sequence of packages this packet belongs. pub seq: u16, - // this is the last acknowledged sequence number. + // This is the last acknowledged sequence number. ack_seq: u16, - // this is an bitfield of all last 32 acknowledged packages + // This is an bitfield of all last 32 acknowledged packages ack_field: u32, } @@ -30,18 +30,18 @@ impl AckedPacketHeader { } } - /// Get the sequence number from this packet. + /// Returns the sequence number from this packet. #[allow(dead_code)] pub fn sequence(&self) -> u16 { self.seq } - /// Get bit field of all last 32 acknowledged packages + /// Returns bit field of all last 32 acknowledged packages. pub fn ack_field(&self) -> u32 { self.ack_field } - /// Get last acknowledged sequence number. + /// Returns last acknowledged sequence number. pub fn ack_seq(&self) -> u16 { self.ack_seq } diff --git a/src/packet/header/arranging_header.rs b/src/packet/header/arranging_header.rs index bb133770..35b534a2 100644 --- a/src/packet/header/arranging_header.rs +++ b/src/packet/header/arranging_header.rs @@ -16,7 +16,7 @@ pub struct ArrangingHeader { } impl ArrangingHeader { - /// Create new fragment with the given packet header + /// Creates new fragment with the given packet header pub fn new(arranging_id: SequenceNumber, stream_id: u8) -> Self { ArrangingHeader { arranging_id, @@ -24,12 +24,12 @@ impl ArrangingHeader { } } - /// Get the sequence number from this packet. + /// Returns the sequence number from this packet. pub fn arranging_id(&self) -> SequenceNumber { self.arranging_id } - /// Get the sequence number from this packet. + /// Returns the sequence number from this packet. pub fn stream_id(&self) -> u8 { self.stream_id } @@ -61,7 +61,7 @@ impl HeaderReader for ArrangingHeader { Ok(header) } - /// Get the size of this header. + /// Returns the size of this header. fn size() -> u8 { ARRANGING_PACKET_HEADER } diff --git a/src/packet/header/fragment_header.rs b/src/packet/header/fragment_header.rs index 4e185a5c..02a92e84 100644 --- a/src/packet/header/fragment_header.rs +++ b/src/packet/header/fragment_header.rs @@ -16,7 +16,7 @@ pub struct FragmentHeader { } impl FragmentHeader { - /// Create new fragment with the given packet header + /// Create new fragment with the given packet header. pub fn new(seq: u16, id: u8, num_fragments: u8) -> Self { FragmentHeader { id, @@ -25,17 +25,17 @@ impl FragmentHeader { } } - /// Get the id of this fragment. + /// Returns the id of this fragment. pub fn id(&self) -> u8 { self.id } - /// Get the sequence number from this packet. + /// Returns the sequence number of this fragment. pub fn sequence(&self) -> u16 { self.sequence } - /// Get the total number of fragments in the packet this fragment is part of. + /// Returns the total number of fragments in the packet this fragment is part of. pub fn fragment_count(&self) -> u8 { self.num_fragments } @@ -70,7 +70,7 @@ impl HeaderReader for FragmentHeader { Ok(header) } - /// Get the size of this header. + /// Returns the size of this header. fn size() -> u8 { FRAGMENT_HEADER_SIZE } diff --git a/src/packet/header/header_reader.rs b/src/packet/header/header_reader.rs index 803060e5..c67d701a 100644 --- a/src/packet/header/header_reader.rs +++ b/src/packet/header/header_reader.rs @@ -5,9 +5,9 @@ pub trait HeaderReader { /// Associated type for the HeaderReader, since it reads it from a Header type Header; - /// Read the specified header from the given Cursor. + /// Reads the specified header from the given Cursor. fn read(rdr: &mut Cursor<&[u8]>) -> Self::Header; - /// This will get the size of the header. + /// Returns the size of the header. fn size() -> u8; } diff --git a/src/packet/header/header_writer.rs b/src/packet/header/header_writer.rs index 478c8cf8..e11d165e 100644 --- a/src/packet/header/header_writer.rs +++ b/src/packet/header/header_writer.rs @@ -3,6 +3,6 @@ pub trait HeaderWriter { /// Associated type since we parse the header into an Output type Output; - /// Write the header to the given buffer. + /// Writes the header to the given buffer. fn parse(&self, buffer: &mut Vec) -> Self::Output; } diff --git a/src/packet/header/standard_header.rs b/src/packet/header/standard_header.rs index 25ebfeb8..216c2fa1 100644 --- a/src/packet/header/standard_header.rs +++ b/src/packet/header/standard_header.rs @@ -20,7 +20,7 @@ pub struct StandardHeader { } impl StandardHeader { - /// Create new header. + /// Creates new header. pub fn new( delivery_guarantee: DeliveryGuarantee, ordering_guarantee: OrderingGuarantee, @@ -112,7 +112,7 @@ impl HeaderReader for StandardHeader { Ok(header) } - /// Get the size of this header. + /// Returns the size of this header. fn size() -> u8 { STANDARD_HEADER_SIZE } diff --git a/src/packet/outgoing.rs b/src/packet/outgoing.rs index bc3d6177..356ec73c 100644 --- a/src/packet/outgoing.rs +++ b/src/packet/outgoing.rs @@ -23,7 +23,7 @@ impl<'p> OutgoingPacketBuilder<'p> { } } - /// This will add the `FragmentHeader` to the header. + /// Adds the `FragmentHeader` to the header. pub fn with_fragment_header(mut self, packet_seq: u16, id: u8, num_fragments: u8) -> Self { let header = FragmentHeader::new(packet_seq, id, num_fragments); @@ -34,7 +34,7 @@ impl<'p> OutgoingPacketBuilder<'p> { self } - /// This will add the [`StandardHeader`](./headers/standard_header) to the header. + /// Adds the [`StandardHeader`](./headers/standard_header) to the header. pub fn with_default_header( mut self, packet_type: PacketType, @@ -49,7 +49,7 @@ impl<'p> OutgoingPacketBuilder<'p> { self } - /// This will add the [`AckedPacketHeader`](./headers/acked_packet_header) to the header. + /// Adds the [`AckedPacketHeader`](./headers/acked_packet_header) to the header. pub fn with_acknowledgment_header( mut self, seq_num: u16, @@ -64,7 +64,7 @@ impl<'p> OutgoingPacketBuilder<'p> { self } - /// This will add the [`ArrangingHeader`](./headers/arranging_header) if needed. + /// Adds the [`ArrangingHeader`](./headers/arranging_header) if needed. /// /// - `arranging_id` = identifier for this packet that needs to be sequenced. /// - `stream_id` = stream on which this packet will be sequenced. If `None` than the a default stream will be used. @@ -79,7 +79,7 @@ impl<'p> OutgoingPacketBuilder<'p> { self } - /// This will add the [`ArrangingHeader`](./headers/arranging_header) if needed. + /// Adds the [`ArrangingHeader`](./headers/arranging_header) if needed. /// /// - `arranging_id` = identifier for this packet that needs to be ordered. /// - `stream_id` = stream on which this packet will be ordered. If `None` than the a default stream will be used. @@ -94,7 +94,7 @@ impl<'p> OutgoingPacketBuilder<'p> { self } - /// This will construct a `OutgoingPacket` from the contents constructed with this builder. + /// Constructs an `OutgoingPacket` from the contents constructed with this builder. pub fn build(self) -> OutgoingPacket<'p> { OutgoingPacket { header: self.header, @@ -111,7 +111,7 @@ pub struct OutgoingPacket<'p> { } impl<'p> OutgoingPacket<'p> { - /// This will return the contents of this packet; the content includes the header and payload bytes. + /// Return the contents of this packet; the content includes the header and payload bytes. /// /// # Remark /// - Until here we could use a reference to the outgoing data but here we need to do a hard copy. diff --git a/src/packet/packet_reader.rs b/src/packet/packet_reader.rs index 44a57cf6..ff0d0bbe 100644 --- a/src/packet/packet_reader.rs +++ b/src/packet/packet_reader.rs @@ -25,7 +25,7 @@ impl<'s> PacketReader<'s> { } } - /// Read the `StandardHeader` from the underlying buffer. + /// Reads the `StandardHeader` from the underlying buffer. /// /// # Remark /// - Will change the position to the location of `StandardHeader` @@ -39,7 +39,7 @@ impl<'s> PacketReader<'s> { } } - /// Read the `StandardHeader` from the underlying buffer. + /// Reads the `StandardHeader` from the underlying buffer. /// /// # Remark /// - Will change the position to the location of `StandardHeader` @@ -53,7 +53,7 @@ impl<'s> PacketReader<'s> { } } - /// Read the `AckedPacketHeader` from the underlying buffer. + /// Reads the `AckedPacketHeader` from the underlying buffer. /// /// # Remark /// - Will change the position to the location of `AckedPacketHeader` @@ -70,7 +70,7 @@ impl<'s> PacketReader<'s> { } } - /// Read the `FragmentHeader` and optionally the `AckedPacketHeader` from the underlying buffer. + /// Reads the `FragmentHeader` and optionally the `AckedPacketHeader` from the underlying buffer. /// /// # Remark /// - Notice that this will continue on the position of last read header; @@ -93,7 +93,7 @@ impl<'s> PacketReader<'s> { } } - /// Read the payload` from the underlying buffer. + /// Reads the payload` from the underlying buffer. /// /// # Remark /// - Notice that this will continue on the position of last read header; @@ -105,7 +105,7 @@ impl<'s> PacketReader<'s> { .into_boxed_slice() } - // checks if a given length of bytes could be read with the buffer. + // Checks if a given length of bytes could be read with the buffer. fn can_read(&self, length: u8) -> bool { (self.buffer.len() - self.cursor.position() as usize) >= length as usize } diff --git a/src/packet/packet_structure.rs b/src/packet/packet_structure.rs index a5a06282..b9605ab3 100644 --- a/src/packet/packet_structure.rs +++ b/src/packet/packet_structure.rs @@ -16,18 +16,18 @@ use crate::packet::{DeliveryGuarantee, OrderingGuarantee, PacketType}; /// /// You are able to send packets with the above reliability types. pub struct Packet { - /// the endpoint from where it came + /// The endpoint from where it came. addr: SocketAddr, - /// the raw payload of the packet + /// The raw payload of the packet. payload: Box<[u8]>, - /// defines on how the packet will be delivered. + /// Defines on how the packet will be delivered. delivery: DeliveryGuarantee, - /// defines on how the packet will be ordered. + /// Defines on how the packet will be ordered. ordering: OrderingGuarantee, } impl Packet { - /// Create a new packet by passing the receiver, data, and guarantees on how this packet should be delivered. + /// Creates a new packet by passing the receiver, data, and guarantees on how this packet should be delivered. pub(crate) fn new( addr: SocketAddr, payload: Box<[u8]>, @@ -42,7 +42,7 @@ impl Packet { } } - /// Create a new unreliable packet by passing the receiver, data. + /// Creates a new unreliable packet by passing the receiver, data. /// /// Unreliable: Packets can be dropped, duplicated or arrive without order. /// @@ -62,7 +62,7 @@ impl Packet { } } - /// Create a new unreliable sequenced packet by passing the receiver, data. + /// Creates a new unreliable sequenced packet by passing the receiver, data. /// /// Unreliable Sequenced; Packets can be dropped, but could not be duplicated and arrive in sequence. /// @@ -86,7 +86,7 @@ impl Packet { } } - /// Create a new packet by passing the receiver, data. + /// Creates a new packet by passing the receiver, data. /// Reliable; All packets will be sent and received, but without order. /// /// *Details* @@ -105,7 +105,7 @@ impl Packet { } } - /// Create a new packet by passing the receiver, data and a optional stream on which the ordering will be done. + /// Creates a new packet by passing the receiver, data and a optional stream on which the ordering will be done. /// /// Reliable; All packets will be sent and received, with order. /// @@ -128,7 +128,7 @@ impl Packet { } } - /// Create a new packet by passing the receiver, data and a optional stream on which the sequencing will be done. + /// Creates a new packet by passing the receiver, data and a optional stream on which the sequencing will be done. /// /// Reliable; All packets will be sent and received, but arranged in sequence. /// Which means that only the newest packets will be let through, older packets will be received but they won't get to the user. @@ -180,13 +180,13 @@ impl Packet { /// This packet type has similar properties to `Packet` except that it doesn't own anything, and additionally has `PacketType`. #[derive(Debug)] pub struct PacketInfo<'a> { - /// defines a type of the packet + /// Defines a type of the packet. pub(crate) packet_type: PacketType, - /// the raw payload of the packet + /// The raw payload of the packet. pub(crate) payload: &'a [u8], - /// defines how the packet will be delivered. + /// Defines how the packet will be delivered. pub(crate) delivery: DeliveryGuarantee, - /// defines how the packet will be ordered. + /// Defines how the packet will be ordered. pub(crate) ordering: OrderingGuarantee, } diff --git a/src/packet/process_result.rs b/src/packet/process_result.rs index ed7b4c90..f25ff970 100644 --- a/src/packet/process_result.rs +++ b/src/packet/process_result.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use crate::either::Either; use crate::packet::{OutgoingPacket, Packet, PacketType}; -/// Struct that implements `Iterator`, and is used to return incoming (from bytes to packets) or outgoing (from packet to bytes) packets. +/// Used to return incoming (from bytes to packets) or outgoing (from packet to bytes) packets. /// It is used as optimization in cases, where most of the time there is only one element to iterate, and we don't want to create a vector for it. #[derive(Debug)] pub struct ZeroOrMore { diff --git a/src/protocol_version.rs b/src/protocol_version.rs index d0e2f63e..ad988bda 100644 --- a/src/protocol_version.rs +++ b/src/protocol_version.rs @@ -13,7 +13,7 @@ lazy_static! { pub struct ProtocolVersion; impl ProtocolVersion { - /// Get the current protocol version. + /// Returns the current protocol version. #[inline] #[cfg(test)] pub fn get_version() -> &'static str { diff --git a/src/sequence_buffer.rs b/src/sequence_buffer.rs index 99ed4596..52907103 100644 --- a/src/sequence_buffer.rs +++ b/src/sequence_buffer.rs @@ -17,7 +17,7 @@ pub struct SequenceBuffer { } impl SequenceBuffer { - /// Create a SequenceBuffer with a desired capacity. + /// Creates a SequenceBuffer with a desired capacity. pub fn with_capacity(size: u16) -> Self { Self { sequence_num: 0, @@ -40,10 +40,10 @@ impl SequenceBuffer { None } - /// Insert the entry data into the sequence buffer. If the requested sequence number is "too + /// Inserts the entry data into the sequence buffer. If the requested sequence number is "too /// old", the entry will not be inserted and no reference will be returned. pub fn insert(&mut self, sequence_num: SequenceNumber, entry: T) -> Option<&mut T> { - // Sequence number is too old to insert into the buffer + // sequence number is too old to insert into the buffer if sequence_less_than( sequence_num, self.sequence_num @@ -136,11 +136,11 @@ mod tests { assert!(sequence_greater_than(1, 0)); assert!(sequence_less_than(0, 1)); - // Right around the halfway point is where we cut over. + // right around the halfway point is where we cut over. assert!(sequence_greater_than(32768, 0)); assert!(sequence_less_than(32769, 0)); - // In this case, 0 is greater than u16 max because we're likely at the wrapping case + // in this case, 0 is greater than u16 max because we're likely at the wrapping case assert!(sequence_greater_than(0, u16::max_value())); } @@ -184,16 +184,16 @@ mod tests { fn insert_into_buffer_old_entry_test() { let mut buffer = SequenceBuffer::with_capacity(8); buffer.insert(8, DataStub); - // This entry would overlap with sequence 8 based on the buffer size so we must ensure that + // this entry would overlap with sequence 8 based on the buffer size so we must ensure that // it does not. buffer.insert(0, DataStub); assert!(!buffer.exists(0)); - // However, this one is more recent so it should definitely exist. + // however, this one is more recent so it should definitely exist. buffer.insert(16, DataStub); assert!(buffer.exists(16)); - // Since we are pretty far ahead at this point, there should only be 1 valid entry in here. + // since we are pretty far ahead at this point, there should only be 1 valid entry in here. assert_eq!(count_entries(&buffer), 1); } @@ -217,11 +217,11 @@ mod tests { assert_eq!(buffer.sequence_num(), 11); - // Inserting "older" should fail to insert + // inserting 'older' should fail to insert buffer.insert(2, DataStub); assert!(!buffer.exists(2)); - // Insert respects boundary wrap. Both of these would be earlier than 11 + // insert respects boundary wrap. Both of these would be earlier than 11 buffer.insert(u16::max_value(), DataStub); buffer.insert(0, DataStub); assert!(!buffer.exists(u16::max_value())); diff --git a/src/throughput.rs b/src/throughput.rs index 2fe2e9df..7e5cdd0b 100644 --- a/src/throughput.rs +++ b/src/throughput.rs @@ -9,7 +9,7 @@ struct ThroughputEntry { } impl ThroughputEntry { - /// Construct a new throughput entry. + /// Constructs a new throughput entry. pub fn new(measured_throughput: u32, time: Instant) -> ThroughputEntry { ThroughputEntry { measured_throughput, @@ -32,7 +32,7 @@ pub struct ThroughputMonitoring { } impl ThroughputMonitoring { - /// Construct a new instance of `ThroughputMonitoring` + /// Constructs a new instance of `ThroughputMonitoring`. pub fn new(throughput_duration: Duration) -> ThroughputMonitoring { ThroughputMonitoring { throughput_duration, @@ -42,7 +42,7 @@ impl ThroughputMonitoring { } } - /// This will increase the throughput by one, when the `throughput_duration` has elapsed since the last call, then an throughput entry will be created. + /// Increases the throughput by one, when the `throughput_duration` has elapsed since the last call, then an throughput entry will be created. pub fn tick(&mut self) -> bool { if self.timer.elapsed() >= self.throughput_duration { self.measured_throughput diff --git a/tests/common/client.rs b/tests/common/client.rs index f29f0712..b6c60ea1 100644 --- a/tests/common/client.rs +++ b/tests/common/client.rs @@ -24,7 +24,7 @@ impl Client { } } - /// This will run a specific instance of the client running at the given socket address. + /// Runs a specific instance of the client running at the given socket address. /// This function takes in a closure who constructs a packet which will be sent out to the client. pub fn run_instance(&self, create_packet: F, endpoint: SocketAddr) -> ClientHandle where @@ -74,7 +74,7 @@ impl ClientHandle { } } - /// Wait until the client has sent all of its packets. + /// Waits until the client has sent all of its packets. pub fn wait_until_finished(self) { self.thread_handle.join().unwrap(); }