Skip to content

Commit

Permalink
Merge #95
Browse files Browse the repository at this point in the history
95: Add improved public api and exports r=TimonPost,LucioFranco a=LucioFranco

Related to #75 

Co-authored-by: Lucio Franco <[email protected]>
  • Loading branch information
bors[bot] and LucioFranco committed Nov 11, 2018
2 parents 46899b4 + 3654a36 commit 42ede66
Show file tree
Hide file tree
Showing 14 changed files with 137 additions and 114 deletions.
4 changes: 3 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ rust:

before_script:
- rustup component add clippy-preview
- export PATH=$PATH:/home/travis/.cargo/bin
- export RUSTFLAGS="-D warnings"

os:
- linux
Expand Down Expand Up @@ -39,7 +41,7 @@ addons:
- libiberty-dev

script:
- cargo clippy -- -D warnings
- cargo clippy --all --all-features -- -D warnings
- cargo test --verbose --all --all-features

after_success: |
Expand Down
6 changes: 5 additions & 1 deletion examples/server_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ extern crate laminar;

use std::io::stdin;

use laminar::{error::Result, NetworkConfig, Packet, UdpSocket};
use laminar::{
error::Result,
net::{NetworkConfig, UdpSocket},
Packet,
};

const SERVER: &str = "localhost:12351";

Expand Down
17 changes: 9 additions & 8 deletions examples/simple_udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
extern crate bincode;
extern crate laminar;

#[macro_use]
extern crate serde_derive;
extern crate serde;

use laminar::net::{NetworkConfig, UdpSocket};
use laminar::packet::Packet;
extern crate serde_derive;

use bincode::{deserialize, serialize};
use laminar::{
net::{NetworkConfig, UdpSocket},
Packet,
};
use serde_derive::{Deserialize, Serialize};
use std::net::SocketAddr;
use std::{thread, time};

Expand Down Expand Up @@ -157,7 +157,7 @@ impl Client {
let mut udp_socket = UdpSocket::bind(client_address(), config).unwrap();

// next we could specify if or socket should block the current thread when receiving data or not (default = false)

udp_socket.set_nonblocking(false);

Client { udp_socket }
Expand All @@ -169,7 +169,8 @@ impl Client {

match serialized {
Ok(raw_data) => {
self.udp_socket.send(&Packet::reliable_unordered(server_address(), raw_data));
self.udp_socket
.send(&Packet::reliable_unordered(server_address(), raw_data));
}
Err(e) => println!("Some error occurred: {:?}", e),
}
Expand Down
6 changes: 4 additions & 2 deletions examples/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
extern crate laminar;

use laminar::net::{NetworkConfig, UdpSocket};
use laminar::packet::Packet;
use laminar::{
net::{NetworkConfig, UdpSocket},
Packet,
};

use std::net::SocketAddr;

Expand Down
12 changes: 7 additions & 5 deletions src/bin/laminar-tester.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ use std::time::{Duration, Instant};

use clap::App;

use laminar::infrastructure::DeliveryMethod;
use laminar::net;
use laminar::packet::Packet;
use laminar::{net, DeliveryMethod, Packet};

fn main() {
let yaml = load_yaml!("cli.yml");
Expand Down Expand Up @@ -108,7 +106,9 @@ fn run_client(test_name: &str, destination: &str, endpoint: &str, pps: &str, tes
}
};

client.set_nonblocking(true);
client
.set_nonblocking(true)
.expect("Unable to set nonblocking");

// See which test we want to run
match test_name {
Expand Down Expand Up @@ -140,7 +140,9 @@ fn test_steady_stream(client: &mut net::UdpSocket, target: &str, pps: &str, test
let start_time = Instant::now();
let mut packets_sent = 0;
loop {
client.send(&test_packet.clone());
client
.send(&test_packet.clone())
.expect("Unable to send a client packet");
packets_sent += 1;
let now = Instant::now();
let d = now - start_time;
Expand Down
40 changes: 25 additions & 15 deletions src/infrastructure/channels/reliable_channel.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use super::Channel;

use net::{LocalAckRecord, ExternalAcks, NetworkConfig, NetworkQuality, RttMeasurer};
use packet::header::{HeaderParser, HeaderReader, AckedPacketHeader, StandardHeader};
use sequence_buffer::{SequenceBuffer, CongestionData};
use error::{NetworkResult, PacketErrorKind};
use infrastructure::{DeliveryMethod, Fragmentation};
use error::{PacketErrorKind,NetworkResult};
use packet::{PacketData,PacketTypeId};
use net::{ExternalAcks, LocalAckRecord, NetworkConfig, NetworkQuality, RttMeasurer};
use packet::header::{AckedPacketHeader, HeaderParser, HeaderReader, StandardHeader};
use packet::{PacketData, PacketTypeId};
use sequence_buffer::{CongestionData, SequenceBuffer};

use std::io::{Cursor};
use std::time::Instant;
use std::sync::Arc;
use log::error;
use std::io::Cursor;
use std::sync::Arc;
use std::time::Instant;

/// This channel should be used for processing packets reliable. All packets will be sent and received, ordering depends on given 'ordering' parameter.
///
Expand Down Expand Up @@ -63,6 +63,7 @@ impl ReliableChannel {
}

/// Checks if channel is ordered or not
#[allow(dead_code)]
pub fn is_ordered(&self) -> bool {
self.ordered
}
Expand Down Expand Up @@ -98,7 +99,11 @@ impl Channel for ReliableChannel {
/// 1. Add congestion data entry so that it can be monitored.
/// 2. Queue new packet in acknowledgement system.
/// 3. Fragmentation of the payload.
fn process_outgoing(&mut self, payload: &[u8], delivery_method: DeliveryMethod) -> NetworkResult<PacketData> {
fn process_outgoing(
&mut self,
payload: &[u8],
delivery_method: DeliveryMethod,
) -> NetworkResult<PacketData> {
if payload.len() > self.config.max_packet_size {
error!(
"Packet too large: Attempting to send {}, max={}",
Expand All @@ -120,7 +125,8 @@ impl Channel for ReliableChannel {
// calculate size for our packet data.
// safe cast because max packet size is u16
let payload_length = payload.len() as u16;
let packet_data_size = Fragmentation::total_fragments_needed(payload_length, self.config.fragment_size);
let packet_data_size =
Fragmentation::total_fragments_needed(payload_length, self.config.fragment_size);
let mut packet_data = PacketData::with_capacity(packet_data_size as usize);

let packet_type = if packet_data_size > 1 {
Expand All @@ -130,7 +136,12 @@ impl Channel for ReliableChannel {
};

// create our reliable header and write it to an buffer.
let header = AckedPacketHeader::new(StandardHeader::new(delivery_method, packet_type), self.seq_num, self.their_acks.last_seq, self.their_acks.field);
let header = AckedPacketHeader::new(
StandardHeader::new(delivery_method, packet_type),
self.seq_num,
self.their_acks.last_seq,
self.their_acks.field,
);
let mut buffer = Vec::with_capacity(header.size() as usize);
header.parse(&mut buffer)?;

Expand All @@ -153,8 +164,7 @@ impl Channel for ReliableChannel {
/// 2. Update acknowledgement data.
/// 3. Calculate RTT time.
/// 4. Update dropped packets.
fn process_incoming<'d>(&mut self, buffer: &'d[u8]) -> NetworkResult<&'d[u8]> {

fn process_incoming<'d>(&mut self, buffer: &'d [u8]) -> NetworkResult<&'d [u8]> {
let mut cursor = Cursor::new(buffer);
let acked_header = AckedPacketHeader::read(&mut cursor)?;

Expand All @@ -171,6 +181,6 @@ impl Channel for ReliableChannel {

self.dropped_packets = dropped_packets.into_iter().map(|(_, p)| p).collect();

Ok(&buffer[acked_header.size() as usize .. buffer.len()])
Ok(&buffer[acked_header.size() as usize..buffer.len()])
}
}
}
22 changes: 13 additions & 9 deletions src/infrastructure/channels/unreliable_channel.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use super::Channel;

use error::NetworkResult;
use infrastructure::DeliveryMethod;
use net::constants::STANDARD_HEADER_SIZE;
use packet::header::{HeaderParser, HeaderReader, StandardHeader};
use infrastructure::DeliveryMethod;
use packet::{PacketData, PacketTypeId};
use error::NetworkResult;

/// This channel should be used for unreliable processing of packets.
///
Expand All @@ -16,8 +16,7 @@ use error::NetworkResult;
///
/// Basically just bare UDP, free to be dropped, used for very unnecessary data, great for 'general' position updates.
/// Ordering depends on given 'ordering' parameter.
pub struct UnreliableChannel
{
pub struct UnreliableChannel {
ordered: bool,
}

Expand All @@ -28,6 +27,7 @@ impl UnreliableChannel {
}

/// Returns if a channel is ordered or not
#[allow(dead_code)]
pub fn is_ordered(&self) -> bool {
self.ordered
}
Expand All @@ -39,9 +39,13 @@ impl Channel for UnreliableChannel {
/// 1. Generate default header.
/// 2. Append payload.
/// 3. Return the final data.
fn process_outgoing(&mut self, payload: &[u8], delivery_method: DeliveryMethod) -> NetworkResult<PacketData> {
fn process_outgoing(
&mut self,
payload: &[u8],
delivery_method: DeliveryMethod,
) -> NetworkResult<PacketData> {
let header = StandardHeader::new(delivery_method, PacketTypeId::Packet);
let mut buffer= Vec::with_capacity(header.size() as usize);
let mut buffer = Vec::with_capacity(header.size() as usize);
header.parse(&mut buffer)?;

let mut packet_data = PacketData::with_capacity(payload.len());
Expand All @@ -52,7 +56,7 @@ impl Channel for UnreliableChannel {
/// Process a packet on receive.
///
/// This will not do anything it will only return the bytes as they are received.
fn process_incoming<'d>(&mut self, buffer: &'d[u8]) -> NetworkResult<&'d[u8]> {
Ok(&buffer[STANDARD_HEADER_SIZE as usize .. buffer.len()])
fn process_incoming<'d>(&mut self, buffer: &'d [u8]) -> NetworkResult<&'d [u8]> {
Ok(&buffer[STANDARD_HEADER_SIZE as usize..buffer.len()])
}
}
}
32 changes: 15 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
//! ```rust
//! extern crate laminar;
//!
//! use laminar::{UdpSocket, NetworkConfig};
//! use laminar::Packet;
//! use laminar::{Packet, net::{UdpSocket, NetworkConfig}};
//!
//! use std::net::Ipv4Addr;
//!
Expand All @@ -48,26 +47,25 @@
extern crate bincode;
extern crate byteorder;
extern crate crc;
extern crate lazy_static;
extern crate serde;
extern crate log;
extern crate failure;
extern crate failure_derive;
extern crate lazy_static;
extern crate log;
extern crate rand;
extern crate serde;

mod events;
mod infrastructure;
mod packet;
mod protocol_version;
mod sequence_buffer;

/// Contains network specific errors
/// All internal error handling logic
pub mod error;
/// Contains events we feed back up to the application
pub mod events;
/// Contains code related to the piping needed for shuffling packets to and fro
pub mod infrastructure;
/// Network specific code and configuration
/// Networking modules
pub mod net;
/// Packet specific code and configuration
pub mod packet;
/// Protocol specific code and configuration
pub mod protocol_version;
mod sequence_buffer;

pub use net::{NetworkConfig, UdpSocket};
pub use events::Event;
pub use infrastructure::DeliveryMethod;
pub use packet::Packet;
pub use protocol_version::ProtocolVersion;
8 changes: 4 additions & 4 deletions src/packet/header/acked_packet_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ impl AckedPacketHeader {
}

/// Get the sequence number from this packet.
#[allow(dead_code)]
pub fn sequence(&self) -> u16 {
self.seq
}
Expand Down Expand Up @@ -88,7 +89,7 @@ impl HeaderReader for AckedPacketHeader {

#[cfg(test)]
mod tests {
use packet::header::{HeaderParser, HeaderReader, AckedPacketHeader, StandardHeader};
use packet::header::{AckedPacketHeader, HeaderParser, HeaderReader, StandardHeader};
use std::io::Cursor;

#[test]
Expand All @@ -105,9 +106,8 @@ mod tests {
assert_eq!(packet_deserialized.seq, 1);
assert_eq!(packet_deserialized.ack_seq, 1);
assert_eq!(packet_deserialized.ack_field, 5421);
},
Err(e) => { println!("{:?}", e)},
}
Err(e) => println!("{:?}", e),
}

}
}
19 changes: 8 additions & 11 deletions src/packet/packet_type.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
use packet::header::{AckedPacketHeader, FragmentHeader};

/// These are the different packets that could be send by te user.
pub enum PacketType
{
#[allow(dead_code)]
pub enum PacketType {
/// Packet header containing packet information.
Normal(AckedPacketHeader),
/// Part of an packet also called 'fragment' containing fragment info.
Fragment(FragmentHeader),
/// Packet to keep the connection alive.
HeartBeat { /* fields ... */ },
HeartBeat {/* fields ... */},
/// Disconnect request
Disconnect { /* fields ... */ }
Disconnect {/* fields ... */},
}

#[derive(Copy, Clone, Debug, PartialOrd, PartialEq)]
/// Id to identify an certain packet type.
pub enum PacketTypeId
{
pub enum PacketTypeId {
/// Full packet that is not fragmented
Packet = 0,
/// Fragment of a full packet
Expand All @@ -29,11 +28,9 @@ pub enum PacketTypeId
Unknown = 255,
}

impl PacketTypeId
{
impl PacketTypeId {
/// Get integer value from `PacketTypeId` enum.
pub fn get_id(packet_type: PacketTypeId) -> u8
{
pub fn get_id(packet_type: PacketTypeId) -> u8 {
packet_type as u8
}

Expand All @@ -44,7 +41,7 @@ impl PacketTypeId
1 => PacketTypeId::Fragment,
2 => PacketTypeId::HeartBeat,
3 => PacketTypeId::Disconnect,
_ => PacketTypeId::Unknown
_ => PacketTypeId::Unknown,
}
}
}
Loading

0 comments on commit 42ede66

Please sign in to comment.