use bytesbuf::mem::{CallbackMemory, HasMemory, Memory, MemoryShared};
use bytesbuf::{BytesBuf, BytesView};
use thread_aware::ThreadAware;
fn main() {
let io_context = IoContext::new();
let mut connection = UdpConnection::new(io_context);
let mut buf = connection.memory().reserve(1 + 8 + 16);
buf.put_byte(42);
buf.put_num_be(43_u64);
buf.put_num_be(44_u128);
let packet = buf.consume_all();
connection.write(packet);
}
#[derive(Debug)]
struct UdpConnection {
io_context: IoContext,
}
impl UdpConnection {
pub(crate) const fn new(io_context: IoContext) -> Self {
Self { io_context }
}
#[expect(
clippy::needless_pass_by_ref_mut,
clippy::unused_self,
clippy::needless_pass_by_value,
reason = "for example realism"
)]
pub(crate) fn write(&mut self, packet: BytesView) {
println!("Sending packet of length: {}", packet.len());
}
}
const UDP_CONNECTION_OPTIMAL_MEMORY_CONFIGURATION: MemoryConfiguration = MemoryConfiguration {
requires_page_alignment: false,
zero_memory_on_release: false,
requires_registered_memory: true,
};
impl HasMemory for UdpConnection {
fn memory(&self) -> impl MemoryShared {
let io_memory = self.io_context.io_memory();
CallbackMemory::new(io_memory, |io_memory, min_len| {
io_memory.reserve_with_config(min_len, &UDP_CONNECTION_OPTIMAL_MEMORY_CONFIGURATION)
})
}
}
#[derive(Clone, Debug)]
struct IoContext;
impl IoContext {
pub(crate) const fn new() -> Self {
Self {}
}
#[expect(clippy::unused_self, reason = "for example realism")]
pub(crate) fn io_memory(&self) -> IoMemory {
IoMemory
}
}
#[derive(Clone, Debug, ThreadAware)]
struct IoMemory;
impl IoMemory {
#[expect(clippy::unused_self, reason = "for example realism")]
fn reserve_with_config(&self, min_len: usize, _memory_configuration: &MemoryConfiguration) -> BytesBuf {
let memory = bytesbuf::mem::testing::TransparentMemory::new();
memory.reserve(min_len)
}
}
impl Memory for IoMemory {
fn reserve(&self, min_bytes: usize) -> BytesBuf {
self.reserve_with_config(
min_bytes,
&MemoryConfiguration {
requires_page_alignment: false,
zero_memory_on_release: false,
requires_registered_memory: false,
},
)
}
}
#[expect(dead_code, reason = "just an example, fields unused")]
struct MemoryConfiguration {
requires_page_alignment: bool,
zero_memory_on_release: bool,
requires_registered_memory: bool,
}