Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no_std support and improved mallocs #3

Merged
merged 4 commits into from
May 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
- Compatible with ENet 1.3.18
- Refine some trait requirements and derives
- Reduce allocations introduced by Rust port ([#1](https://github.com/jabuwu/rusty_enet/issues/1))
- Reduce `enet_malloc` overhead
- Adjust `Socket::receive` interface to one which takes a pre-allocated buffer
- Add `#![no_std]` support (by disabling `std` feature)
- Add `MTU_MAX` constant (an alias of `ENET_PROTOCOL_MAXIMUM_MTU`)
- Add functions:
- [`Host::mtu`]
Expand Down
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ exclude = [
"/examples",
]

[features]
default = ["std"]
std = []

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3.69"

Expand Down
1 change: 1 addition & 0 deletions ci/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ edition = "2021"
anyhow = "1.0.70"
xshell = "0.2"
bitflags = "2.0"
itertools = "0.10"
15 changes: 11 additions & 4 deletions ci/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ fn main() -> anyhow::Result<()> {

let sh = Shell::new()?;
if what_to_run.contains(Check::CHECK) {
check(&sh, Target::Default)?;
check(&sh, Target::Default, Features(&["std"]))?;
}
if what_to_run.contains(Check::WASM_CHECK) {
check(&sh, Target::Wasm)?;
check(&sh, Target::Wasm, Features(&["std"]))?;
}
if what_to_run.contains(Check::EXAMPLE_CHECK) {
example_check(&sh)?;
Expand All @@ -75,9 +75,16 @@ fn main() -> anyhow::Result<()> {
Ok(())
}

fn check(sh: &Shell, target: Target) -> anyhow::Result<()> {
fn check(sh: &Shell, target: Target, features: Features) -> anyhow::Result<()> {
let target_flags = &target.flags();
cmd!(sh, "cargo rustc {target_flags...} -- -D warnings").run()?;
let feature_combination_flags = features.combination_flags();
for feature_flags in feature_combination_flags.iter() {
cmd!(
sh,
"cargo rustc {target_flags...} {feature_flags...} -- -D warnings"
)
.run()?;
}
Ok(())
}

Expand Down
27 changes: 27 additions & 0 deletions ci/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use itertools::Itertools;

pub enum Target {
Default,
Wasm,
Expand All @@ -11,3 +13,28 @@ impl Target {
}
}
}

pub struct Features(pub &'static [&'static str]);

impl Features {
pub fn combination_flags(&self) -> Vec<Vec<String>> {
let mut feature_combinations: Vec<Vec<String>> =
vec![vec!["--no-default-features".to_owned()]];
for k in 1..=self.0.len() {
feature_combinations.extend::<Vec<_>>(
self.0
.iter()
.combinations(k)
.map(|features| {
vec![
"--no-default-features".to_owned(),
"--features".to_owned(),
features.iter().join(","),
]
})
.collect::<Vec<_>>(),
);
}
feature_combinations
}
}
2 changes: 1 addition & 1 deletion src/address.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::net::SocketAddr;
use core::net::SocketAddr;

/// An address type, for use with the [`Socket`](`crate::Socket`) trait.
pub trait Address: Sized + Clone {
Expand Down
10 changes: 5 additions & 5 deletions src/c.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ptr::NonNull;
use core::ptr::NonNull;

use crate::Socket;

Expand Down Expand Up @@ -78,15 +78,15 @@ pub(crate) unsafe fn enet_time_get<S: Socket>(host: *mut ENetHost<S>) -> u32 {
}
pub unsafe fn from_raw_parts_or_empty<'a, T>(data: *const T, len: usize) -> &'a [T] {
if len == 0 {
std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0)
core::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0)
} else {
std::slice::from_raw_parts(data, len)
core::slice::from_raw_parts(data, len)
}
}
pub unsafe fn from_raw_parts_or_empty_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
if len == 0 {
std::slice::from_raw_parts_mut(NonNull::dangling().as_mut(), 0)
core::slice::from_raw_parts_mut(NonNull::dangling().as_mut(), 0)
} else {
std::slice::from_raw_parts_mut(data, len)
core::slice::from_raw_parts_mut(data, len)
}
}
7 changes: 3 additions & 4 deletions src/c/compress.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{cmp::Ordering, ptr::NonNull};
use core::{alloc::Layout, cmp::Ordering, ptr::NonNull};

use crate::{enet_free, enet_malloc, ENetBuffer};

Expand Down Expand Up @@ -29,16 +29,15 @@ pub(crate) const ENET_SUBCONTEXT_ESCAPE_DELTA: u32 = 5;
pub(crate) const ENET_CONTEXT_SYMBOL_DELTA: u32 = 3;
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();
let range_coder: *mut ENetRangeCoder = enet_malloc(Layout::new::<ENetRangeCoder>()).cast();
range_coder.cast()
}
pub(crate) unsafe fn enet_range_coder_destroy(context: *mut u8) {
let range_coder: *mut ENetRangeCoder = context.cast();
if range_coder.is_null() {
return;
}
enet_free(range_coder.cast());
enet_free(range_coder.cast(), Layout::new::<ENetRangeCoder>());
}
unsafe fn enet_symbol_rescale(mut symbol: *mut ENetSymbol) -> u16 {
let mut total: u16 = 0_i32 as u16;
Expand Down
31 changes: 16 additions & 15 deletions src/c/host.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::{mem::MaybeUninit, ptr::write_bytes, time::Duration};
use core::{alloc::Layout, mem::MaybeUninit, ptr::write_bytes, time::Duration};

use crate::{
consts::*, enet_free, enet_list_clear, enet_malloc, enet_packet_destroy,
enet_peer_queue_outgoing_command, enet_peer_reset, enet_peer_send, enet_time_get, Compressor,
ENetBuffer, ENetChannel, ENetList, ENetPacket, ENetPeer, ENetProtocol,
enet_peer_queue_outgoing_command, enet_peer_reset, enet_peer_send, enet_time_get, Box,
Compressor, ENetBuffer, ENetChannel, ENetList, ENetPacket, ENetPeer, ENetProtocol,
ENetProtocolCommandHeader, Socket, SocketOptions, ENET_PEER_STATE_CONNECTED,
ENET_PEER_STATE_CONNECTING, ENET_PEER_STATE_DISCONNECTED, ENET_PEER_STATE_DISCONNECT_LATER,
ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT, ENET_PROTOCOL_COMMAND_CONNECT,
Expand Down Expand Up @@ -58,11 +58,9 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
seed: Option<u32>,
) -> Result<*mut ENetHost<S>, S::Error> {
let mut current_peer: *mut ENetPeer<S>;
// note: allocations cannot be null, see enet_malloc docs
let host: *mut ENetHost<S> = enet_malloc(::core::mem::size_of::<ENetHost<S>>()).cast();
let host: *mut ENetHost<S> = enet_malloc(Layout::new::<ENetHost<S>>()).cast();
write_bytes(host, 0, 1);
(*host).peers =
enet_malloc(peer_count.wrapping_mul(::core::mem::size_of::<ENetPeer<S>>())).cast();
(*host).peers = enet_malloc(Layout::array::<ENetPeer<S>>(peer_count).unwrap()).cast();
write_bytes((*host).peers, 0, peer_count);
socket.init(SocketOptions {
receive_buffer: HOST_RECEIVE_BUFFER_SIZE as usize,
Expand Down Expand Up @@ -94,7 +92,7 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
(*host).buffer_count = 0_i32 as usize;
(*host).checksum.write(None);
(*host).received_address.write(None);
(*host).received_data = std::ptr::null_mut();
(*host).received_data = core::ptr::null_mut();
(*host).received_data_length = 0_i32 as usize;
(*host).total_sent_data = 0_i32 as u32;
(*host).total_sent_packets = 0_i32 as u32;
Expand All @@ -115,7 +113,7 @@ pub(crate) unsafe fn enet_host_create<S: Socket>(
(*current_peer).incoming_session_id = 0xff_i32 as u8;
(*current_peer).outgoing_session_id = (*current_peer).incoming_session_id;
(*current_peer).address.write(None);
(*current_peer).data = std::ptr::null_mut();
(*current_peer).data = core::ptr::null_mut();
enet_list_clear(&mut (*current_peer).acknowledgements);
enet_list_clear(&mut (*current_peer).sent_reliable_commands);
enet_list_clear(&mut (*current_peer).outgoing_commands);
Expand All @@ -142,8 +140,11 @@ pub(crate) unsafe fn enet_host_destroy<S: Socket>(host: *mut ENetHost<S>) {
(*host).time.assume_init_drop();
(*host).compressor.assume_init_drop();
(*host).received_address.assume_init_drop();
enet_free((*host).peers.cast());
enet_free(host.cast());
enet_free(
(*host).peers.cast(),
Layout::array::<ENetPeer<S>>((*host).peer_count).unwrap(),
);
enet_free(host.cast(), Layout::new::<ENetHost<S>>());
}
pub(crate) unsafe fn enet_host_random<S: Socket>(host: *mut ENetHost<S>) -> u32 {
(*host).random_seed = (*host).random_seed.wrapping_add(0x6d2b79f5_u32);
Expand Down Expand Up @@ -180,10 +181,10 @@ pub(crate) unsafe fn enet_host_connect<S: Socket>(
current_peer = current_peer.offset(1);
}
if current_peer >= ((*host).peers).add((*host).peer_count) {
return std::ptr::null_mut();
return core::ptr::null_mut();
}
(*current_peer).channels =
enet_malloc(channel_count.wrapping_mul(::core::mem::size_of::<ENetChannel>())).cast();
enet_malloc(Layout::array::<ENetChannel>(channel_count).unwrap()).cast();
(*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 @@ -234,7 +235,7 @@ pub(crate) unsafe fn enet_host_connect<S: Socket>(
enet_peer_queue_outgoing_command(
current_peer,
&command,
std::ptr::null_mut(),
core::ptr::null_mut(),
0_i32 as u32,
0_i32 as u16,
);
Expand Down Expand Up @@ -439,7 +440,7 @@ pub(crate) unsafe fn enet_host_bandwidth_throttle<S: Socket>(host: *mut ENetHost
enet_peer_queue_outgoing_command(
peer,
&command,
std::ptr::null_mut(),
core::ptr::null_mut(),
0_i32 as u32,
0_i32 as u16,
);
Expand Down
72 changes: 12 additions & 60 deletions src/c/malloc.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,18 @@
use std::{
alloc::{handle_alloc_error, Layout},
collections::HashMap,
sync::{Arc, Mutex, Once},
};
use core::alloc::Layout;

#[derive(Default)]
struct Allocator {
allocations: HashMap<*const u8, Layout>,
}

impl Allocator {
fn singleton() -> Arc<Mutex<Allocator>> {
static START: Once = Once::new();
static mut INSTANCE: Option<Arc<Mutex<Allocator>>> = None;
START.call_once(|| unsafe {
INSTANCE = Some(Arc::new(Mutex::new(Allocator::default())));
});
unsafe {
let singleton = INSTANCE.as_ref().unwrap();
singleton.clone()
}
}

fn malloc(&mut self, size: usize) -> *mut u8 {
if size > 0 {
let layout = std::alloc::Layout::array::<u8>(size)
.unwrap()
.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 {
std::ptr::null_mut()
}
}
#[cfg(not(feature = "std"))]
use alloc::alloc::{alloc, dealloc, handle_alloc_error};
#[cfg(feature = "std")]
use std::alloc::{alloc, dealloc, handle_alloc_error};

unsafe fn free(&mut self, ptr: *const u8) {
if !ptr.is_null() {
let layout = self.allocations.remove(&ptr).unwrap();
unsafe { std::alloc::dealloc(ptr.cast_mut(), layout) };
}
pub(crate) unsafe fn enet_malloc(layout: Layout) -> *mut u8 {
let ptr = unsafe { alloc(layout) };
if ptr.is_null() {
handle_alloc_error(layout);
}
ptr
}

/// 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();
allocator.malloc(size)
}

pub(crate) unsafe fn enet_free(ptr: *mut u8) {
if !ptr.is_null() && ptr as usize != 1 {
let singleton = Allocator::singleton();
let mut allocator = singleton.lock().unwrap();
allocator.free(ptr);
}
pub(crate) unsafe fn enet_free(ptr: *mut u8, layout: Layout) {
dealloc(ptr, layout);
}
19 changes: 9 additions & 10 deletions src/c/packet.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ptr::copy_nonoverlapping;
use core::{alloc::Layout, ptr::copy_nonoverlapping};

use crate::{enet_free, enet_malloc, ENET_PACKET_FLAG_NO_ALLOCATE};

Expand All @@ -15,17 +15,13 @@ pub(crate) unsafe fn enet_packet_create(
data_length: usize,
flags: u32,
) -> *mut ENetPacket {
let packet: *mut ENetPacket = enet_malloc(::core::mem::size_of::<ENetPacket>()).cast();
let packet: *mut ENetPacket = enet_malloc(Layout::new::<ENetPacket>()).cast();
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 {
(*packet).data = std::ptr::null_mut();
(*packet).data = core::ptr::null_mut();
} else {
(*packet).data = enet_malloc(data_length);
if ((*packet).data).is_null() {
enet_free(packet.cast());
return std::ptr::null_mut();
}
(*packet).data = enet_malloc(Layout::array::<u8>(data_length).unwrap());
if !data.is_null() {
copy_nonoverlapping(data, (*packet).data, data_length);
}
Expand All @@ -42,7 +38,10 @@ pub(crate) unsafe fn enet_packet_destroy(packet: *mut ENetPacket) {
if (*packet).flags & ENET_PACKET_FLAG_NO_ALLOCATE as i32 as u32 == 0
&& !((*packet).data).is_null()
{
enet_free((*packet).data);
enet_free(
(*packet).data,
Layout::array::<u8>((*packet).data_length).unwrap(),
);
}
enet_free(packet.cast());
enet_free(packet.cast(), Layout::new::<ENetPacket>());
}
Loading
Loading