Skip to content

Commit

Permalink
add test and some api improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
jabuwu committed Dec 11, 2023
1 parent 28a0c75 commit 2e4b4eb
Show file tree
Hide file tree
Showing 6 changed files with 408 additions and 20 deletions.
2 changes: 2 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ impl<'a, S: Socket> Event<'a, S> {
}

/// An ENet event, like [`Event`], but without peer references.
///
/// Acquired with [`Event::no_ref`].
#[derive(Debug, Clone)]
pub enum EventNoRef {
/// A new peer has connected.
Expand Down
13 changes: 10 additions & 3 deletions src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub struct HostSettings {
/// A custom time function to use, or [`None`] to use the default one. Should return an
/// an accurate, incrementally increasing [`Duration`].
pub time: Option<Box<dyn Fn() -> Duration>>,
/// Seed the host with a specific random seed, or set to [`None`] to use a random seed.
pub seed: Option<u32>,
}

impl Default for HostSettings {
Expand All @@ -45,6 +47,7 @@ impl Default for HostSettings {
compressor: None,
checksum: None,
time: None,
seed: None,
}
}
}
Expand Down Expand Up @@ -85,6 +88,13 @@ impl<S: Socket> Host<S> {
settings.channel_limit,
settings.incoming_bandwidth_limit.unwrap_or(0),
settings.outgoing_bandwidth_limit.unwrap_or(0),
settings.time.unwrap_or(Box::new(|| {
use wasm_timer::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
})),
settings.seed,
);
let mut peers = vec![];
for peer_index in 0..(*host).peerCount {
Expand All @@ -96,9 +106,6 @@ impl<S: Socket> Host<S> {
if let Some(checksum) = settings.checksum {
*(*host).checksum.assume_init_mut() = Some(checksum);
}
if let Some(time) = settings.time {
*(*host).time.assume_init_mut() = Some(time);
}
if !host.is_null() {
Ok(Self { host, peers })
} else {
Expand Down
31 changes: 16 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ pub use version::*;
pub mod consts;
use consts::*;

#[cfg(test)]
mod test;

/// A [`Result`](`core::result::Result`) type alias with this crate's [`Error`] type.
pub type Result<T> = core::result::Result<T, Error>;

Expand Down Expand Up @@ -390,7 +393,7 @@ pub(crate) struct _ENetHost<S: Socket> {
pub(crate) buffers: [ENetBuffer; 65],
pub(crate) bufferCount: size_t,
pub(crate) checksum: MaybeUninit<Option<Box<dyn Fn(Vec<&[u8]>) -> u32>>>,
pub(crate) time: MaybeUninit<Option<Box<dyn Fn() -> Duration>>>,
pub(crate) time: MaybeUninit<Box<dyn Fn() -> Duration>>,
pub(crate) compressor: MaybeUninit<Option<Box<dyn Compressor>>>,
pub(crate) packetData: [[enet_uint8; 4096]; 2],
pub(crate) receivedAddress: MaybeUninit<Option<S::PeerAddress>>,
Expand Down Expand Up @@ -1756,6 +1759,8 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
mut channelLimit: size_t,
mut incomingBandwidth: enet_uint32,
mut outgoingBandwidth: enet_uint32,
time: Box<dyn Fn() -> Duration>,
seed: Option<u32>,
) -> *mut ENetHost<S> {
let mut host: *mut ENetHost<S> = 0 as *mut ENetHost<S>;
let mut currentPeer: *mut ENetPeer<S> = 0 as *mut ENetPeer<S>;
Expand Down Expand Up @@ -1793,10 +1798,15 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
} else if channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT as c_int as size_t {
channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT as c_int as size_t;
}
(*host).randomSeed = host as size_t as enet_uint32;
(*host).randomSeed = ((*host).randomSeed as c_uint).wrapping_add(enet_time_get(host))
as enet_uint32 as enet_uint32;
(*host).randomSeed = (*host).randomSeed << 16 as c_int | (*host).randomSeed >> 16 as c_int;
(*host).time.write(time);
if let Some(seed) = seed {
(*host).randomSeed = seed;
} else {
(*host).randomSeed = host as size_t as enet_uint32;
(*host).randomSeed = ((*host).randomSeed as c_uint).wrapping_add(enet_time_get(host))
as enet_uint32 as enet_uint32;
(*host).randomSeed = (*host).randomSeed << 16 as c_int | (*host).randomSeed >> 16 as c_int;
}
(*host).channelLimit = channelLimit;
(*host).incomingBandwidth = incomingBandwidth;
(*host).outgoingBandwidth = outgoingBandwidth;
Expand All @@ -1807,7 +1817,6 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
(*host).commandCount = 0 as c_int as size_t;
(*host).bufferCount = 0 as c_int as size_t;
(*host).checksum.write(None);
(*host).time.write(None);
(*host).receivedAddress.write(None);
(*host).receivedData = 0 as *mut enet_uint8;
(*host).receivedDataLength = 0 as c_int as size_t;
Expand Down Expand Up @@ -6739,13 +6748,5 @@ pub(crate) unsafe fn enet_host_random_seed<S: Socket>(host: *mut ENetHost<S>) ->
enet_time_get(host)
}
pub(crate) unsafe fn enet_time_get<S: Socket>(host: *mut ENetHost<S>) -> enet_uint32 {
let duration = if let Some(time) = (*host).time.assume_init_ref() {
time()
} else {
use wasm_timer::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
};
(duration.as_millis() % u32::MAX as u128) as enet_uint32
((*host).time.assume_init_ref()().as_millis() % u32::MAX as u128) as enet_uint32
}
16 changes: 14 additions & 2 deletions src/packet.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::slice;
use std::{fmt::Debug, slice};

use crate::{
c_void, enet_packet_create, enet_packet_destroy, size_t, ENetPacket, ENET_PACKET_FLAG_RELIABLE,
Expand Down Expand Up @@ -37,7 +37,6 @@ pub enum PacketKind {
/// See [`Fragmentation and Reassembly`](`crate#fragmentation-and-reassembly`).
///
/// For more information on the kinds of ENet packets, see [`PacketKind`].
#[derive(Debug)]
pub struct Packet {
pub(crate) packet: *mut ENetPacket,
}
Expand Down Expand Up @@ -154,3 +153,16 @@ impl Drop for Packet {
}
}
}

impl Debug for Packet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let packet = unsafe { &(*self.packet) };
f.debug_struct("Packet")
.field("data", &packet.data)
.field("dataLength", &packet.dataLength)
.field("userData", &packet.userData)
.field("flags", &packet.flags)
.field("kind", &self.kind())
.finish()
}
}
56 changes: 56 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use std::time::Duration;

use crate as enet;

mod network;
use network::*;

#[test]
fn events() {
let mut network = Network::new();
let mut host1 = network.create_host(enet::HostSettings {
peer_limit: 1,
..Default::default()
});
let mut host2 = network.create_host(enet::HostSettings {
peer_limit: 1,
..Default::default()
});

network.connect(host1, host2, 255, 5);
network.update(Duration::from_millis(10));
let events = network.update(Duration::from_millis(10));
assert_eq!(events.len(), 2);
assert!(events[0].is_connect_and(|event| event.to == host1
&& event.from == host2
&& event.peer == enet::PeerID(0)
&& event.data == 0));
assert!(events[1].is_connect_and(|event| event.to == host2
&& event.from == host1
&& event.peer == enet::PeerID(0)
&& event.data == 5));

network.send(
host1,
host2,
0,
enet::Packet::reliable("hello world".as_bytes()),
);
let events = network.update(Duration::from_millis(10));
assert_eq!(events.len(), 1);
assert!(events[0].is_receive_and(|event| event.from == host1
&& event.to == host2
&& event.channel_id == 0
&& event.packet.data().len() == 11
&& event.packet.kind() == enet::PacketKind::Reliable));

network.disconnect(host1, host2, 10);
let events = network.update(Duration::from_millis(10));
assert_eq!(events.len(), 1);
assert!(events[0]
.is_disconnect_and(|event| event.from == host1 && event.to == host2 && event.data == 10));
let events = network.update(Duration::from_millis(10));
assert_eq!(events.len(), 1);
assert!(events[0]
.is_disconnect_and(|event| event.from == host2 && event.to == host1 && event.data == 0));
}
Loading

0 comments on commit 2e4b4eb

Please sign in to comment.