use bytesbuf::mem::{CallbackMemory, HasMemory, Memory, MemoryShared};
use bytesbuf::{BytesBuf, BytesView};
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 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 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 {
CallbackMemory::new({
let io_context = self.io_context.clone();
move |min_len| io_context.reserve_io_memory(min_len, UDP_CONNECTION_OPTIMAL_MEMORY_CONFIGURATION)
})
}
}
#[derive(Clone, Debug)]
struct IoContext;
impl IoContext {
pub const fn new() -> Self {
Self {}
}
#[expect(clippy::unused_self, reason = "for example realism")]
pub fn reserve_io_memory(&self, min_len: usize, _memory_configuration: MemoryConfiguration) -> BytesBuf {
let memory = bytesbuf::mem::testing::TransparentMemory::new();
memory.reserve(min_len)
}
}
#[expect(dead_code, reason = "just an example, fields unused")]
struct MemoryConfiguration {
requires_page_alignment: bool,
zero_memory_on_release: bool,
requires_registered_memory: bool,
}