Skip to content

Commit

Permalink
improve errors and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
jabuwu committed May 14, 2024
1 parent 16d0a1e commit 6dd666c
Show file tree
Hide file tree
Showing 17 changed files with 306 additions and 266 deletions.
10 changes: 5 additions & 5 deletions examples/read_write.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::time::Duration;
use std::{convert::Infallible, time::Duration};

use rusty_enet as enet;

fn main() {
let mut host1 = enet::Host::new(
enet::ReadWrite::<(), enet::Error>::new(),
enet::ReadWrite::<(), Infallible>::new(),
enet::HostSettings::default(),
)
.unwrap();
let mut host2 = enet::Host::new(
enet::ReadWrite::<(), enet::Error>::new(),
enet::ReadWrite::<(), Infallible>::new(),
enet::HostSettings::default(),
)
.unwrap();
Expand Down Expand Up @@ -42,8 +42,8 @@ fn main() {

fn update_host(
name: &str,
host: &mut enet::Host<enet::ReadWrite<(), enet::Error>>,
other_host: &mut enet::Host<enet::ReadWrite<(), enet::Error>>,
host: &mut enet::Host<enet::ReadWrite<(), Infallible>>,
other_host: &mut enet::Host<enet::ReadWrite<(), Infallible>>,
) {
while let Some(event) = host.service().unwrap() {
match event {
Expand Down
3 changes: 0 additions & 3 deletions src/c/compress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ pub(crate) const ENET_RANGE_CODER_TOP: u32 = 16777216;
pub(crate) unsafe fn enet_range_coder_create() -> *mut u8 {
let range_coder: *mut ENetRangeCoder =
enet_malloc(::core::mem::size_of::<ENetRangeCoder>()).cast();
if range_coder.is_null() {
return std::ptr::null_mut();
}
range_coder.cast()
}
pub(crate) unsafe fn enet_range_coder_destroy(context: *mut u8) {
Expand Down
25 changes: 7 additions & 18 deletions src/c/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,27 +56,18 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
outgoing_bandwidth: u32,
time: Box<dyn Fn() -> Duration>,
seed: Option<u32>,
) -> *mut ENetHost<S> {
) -> Result<*mut ENetHost<S>, S::Error> {
let mut current_peer: *mut ENetPeer<S>;
if peer_count > ENET_PROTOCOL_MAXIMUM_PEER_ID as i32 as usize {
return std::ptr::null_mut();
}
// note: allocations cannot be null, see enet_malloc docs
let host: *mut ENetHost<S> = enet_malloc(::core::mem::size_of::<ENetHost<S>>()).cast();
if host.is_null() {
return std::ptr::null_mut();
}
write_bytes(host, 0, 1);
(*host).peers =
enet_malloc(peer_count.wrapping_mul(::core::mem::size_of::<ENetPeer<S>>())).cast();
if ((*host).peers).is_null() {
enet_free(host.cast());
return std::ptr::null_mut();
}
write_bytes((*host).peers, 0, peer_count);
_ = socket.init(SocketOptions {
socket.init(SocketOptions {
receive_buffer: ENET_HOST_RECEIVE_BUFFER_SIZE as usize,
send_buffer: ENET_HOST_SEND_BUFFER_SIZE as usize,
});
})?;
(*host).socket.write(socket);
if channel_limit == 0 || channel_limit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT as i32 as usize {
channel_limit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT as i32 as usize;
Expand Down Expand Up @@ -133,7 +124,7 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
enet_peer_reset(current_peer);
current_peer = current_peer.offset(1);
}
host
Ok(host)
}
pub(crate) unsafe fn enet_host_destroy<S: Socket>(host: *mut ENetHost<S>) {
let mut current_peer: *mut ENetPeer<S>;
Expand Down Expand Up @@ -193,9 +184,6 @@ pub(crate) unsafe fn enet_host_connect<S: Socket>(
}
(*current_peer).channels =
enet_malloc(channel_count.wrapping_mul(::core::mem::size_of::<ENetChannel>())).cast();
if ((*current_peer).channels).is_null() {
return std::ptr::null_mut();
}
(*current_peer).channel_count = channel_count;
(*current_peer).state = ENET_PEER_STATE_CONNECTING;
*(*current_peer).address.assume_init_mut() = Some(address);
Expand Down Expand Up @@ -261,7 +249,8 @@ pub(crate) unsafe fn enet_host_broadcast<S: Socket>(
current_peer = (*host).peers;
while current_peer < ((*host).peers).add((*host).peer_count) {
if (*current_peer).state == ENET_PEER_STATE_CONNECTED as i32 as u32 {
enet_peer_send(current_peer, channel_id, packet);
// TODO: do we really want to ignore the result type here?
_ = enet_peer_send(current_peer, channel_id, packet);
}
current_peer = current_peer.offset(1);
}
Expand Down
9 changes: 8 additions & 1 deletion src/c/malloc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
alloc::Layout,
alloc::{handle_alloc_error, Layout},
collections::HashMap,
sync::{Arc, Mutex, Once},
};
Expand Down Expand Up @@ -29,6 +29,9 @@ impl Allocator {
.align_to(8)
.unwrap();
let ptr = unsafe { std::alloc::alloc(layout) };
if ptr.is_null() {
handle_alloc_error(layout);
}
self.allocations.insert(ptr.cast_const(), layout);
ptr.cast::<u8>()
} else {
Expand All @@ -44,6 +47,10 @@ impl Allocator {
}
}

/// Mimics `malloc` for the transpiled C code.
/// Returns `null` if the `size` provided is 0.
/// Panics (with [`handle_alloc_error`]) if allocation failed.
/// Callers can safely assume a valid allocation if `size` > 0.
pub(crate) unsafe fn enet_malloc(size: usize) -> *mut u8 {
let singleton = Allocator::singleton();
let mut allocator = singleton.lock().unwrap();
Expand Down
3 changes: 0 additions & 3 deletions src/c/packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ pub(crate) unsafe fn enet_packet_create(
flags: u32,
) -> *mut ENetPacket {
let packet: *mut ENetPacket = enet_malloc(::core::mem::size_of::<ENetPacket>()).cast();
if packet.is_null() {
return std::ptr::null_mut();
}
if flags & ENET_PACKET_FLAG_NO_ALLOCATE as i32 as u32 != 0 {
(*packet).data = data.cast_mut();
} else if data_length <= 0_i32 as usize {
Expand Down
36 changes: 16 additions & 20 deletions src/c/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use std::{
use crate::{
consts::*, enet_free, enet_host_flush, enet_list_clear, enet_list_insert, enet_list_move,
enet_list_remove, enet_malloc, enet_packet_create, enet_packet_destroy,
enet_protocol_command_size, ENetAcknowledgement, ENetChannel, ENetIncomingCommand, ENetList,
ENetListIterator, ENetListNode, ENetOutgoingCommand, ENetPacket, ENetProtocol,
ENetProtocolAcknowledge, ENetProtocolCommandHeader, ENetProtocolHeader,
enet_protocol_command_size, error::PeerSendError, ENetAcknowledgement, ENetChannel,
ENetIncomingCommand, ENetList, ENetListIterator, ENetListNode, ENetOutgoingCommand, ENetPacket,
ENetProtocol, ENetProtocolAcknowledge, ENetProtocolCommandHeader, ENetProtocolHeader,
ENetProtocolSendFragment, Socket, ENET_PACKET_FLAG_RELIABLE,
ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, ENET_PACKET_FLAG_UNSEQUENCED,
ENET_PROTOCOL_COMMAND_DISCONNECT, ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE,
Expand Down Expand Up @@ -158,7 +158,7 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
peer: *mut ENetPeer<S>,
channel_id: u8,
packet: *mut ENetPacket,
) -> i32 {
) -> Result<(), PeerSendError> {
let mut command: ENetProtocol = ENetProtocol {
header: ENetProtocolCommandHeader {
command: 0,
Expand All @@ -167,11 +167,14 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
},
};
let mut fragment_length: usize;
if (*peer).state != ENET_PEER_STATE_CONNECTED as i32 as u32
|| channel_id as usize >= (*peer).channel_count
|| (*packet).data_length > (*(*peer).host).maximum_packet_size
{
return -1_i32;
if (*peer).state != ENET_PEER_STATE_CONNECTED as i32 as u32 {
return Err(PeerSendError::NotConnected);
}
if channel_id as usize >= (*peer).channel_count {
return Err(PeerSendError::InvalidChannel);
}
if (*packet).data_length > (*(*peer).host).maximum_packet_size {
return Err(PeerSendError::PacketTooLarge);
}
let channel = ((*peer).channels).offset(channel_id as isize);
fragment_length = ((*peer).mtu as usize)
Expand All @@ -198,7 +201,7 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
};
let mut fragment: *mut ENetOutgoingCommand;
if fragment_count > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT as i32 as u32 {
return -1_i32;
return Err(PeerSendError::FragmentsExceeded);
}
if (*packet).flags
& (ENET_PACKET_FLAG_RELIABLE as i32 | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT as i32)
Expand All @@ -223,13 +226,6 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
fragment_length = ((*packet).data_length).wrapping_sub(fragment_offset as usize);
}
fragment = enet_malloc(::core::mem::size_of::<ENetOutgoingCommand>()).cast();
if fragment.is_null() {
while fragments.sentinel.next != std::ptr::addr_of_mut!(fragments.sentinel) {
fragment = enet_list_remove(fragments.sentinel.next).cast();
enet_free(fragment.cast());
}
return -1_i32;
}
(*fragment).fragment_offset = fragment_offset;
(*fragment).fragment_length = fragment_length as u16;
(*fragment).packet = packet;
Expand All @@ -251,7 +247,7 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
fragment = enet_list_remove(fragments.sentinel.next).cast();
enet_peer_setup_outgoing_command(peer, fragment);
}
return 0_i32;
return Ok(());
}
command.header.channel_id = channel_id;
if (*packet).flags
Expand Down Expand Up @@ -280,9 +276,9 @@ pub(crate) unsafe fn enet_peer_send<S: Socket>(
))
.is_null()
{
return -1_i32;
return Err(PeerSendError::FailedToQueue);
}
0_i32
Ok(())
}
pub(crate) unsafe fn enet_peer_receive<S: Socket>(
peer: *mut ENetPeer<S>,
Expand Down
Loading

0 comments on commit 6dd666c

Please sign in to comment.