use std::ptr;
use bytesbuf::BytesBuf;
use bytesbuf::mem::GlobalPool;
const LUCKY_NUMBER: usize = 8888;
const FAVORITE_COLOR: &[u8] = b"octarine";
fn main() {
let memory = GlobalPool::new();
let capacity_required = LUCKY_NUMBER * FAVORITE_COLOR.len();
let mut buf = memory.reserve(capacity_required);
for _ in 0..LUCKY_NUMBER {
emit_favorite_color(&mut buf);
}
let message = buf.consume_all();
println!(
"Emitted favorite color {LUCKY_NUMBER} times, resulting in a message of {} bytes.",
message.len()
);
}
fn emit_favorite_color(buf: &mut BytesBuf) {
assert!(
buf.remaining_capacity() >= FAVORITE_COLOR.len(),
"insufficient remaining capacity in buffer"
);
let mut payload_to_write = FAVORITE_COLOR;
while !payload_to_write.is_empty() {
let slice = buf.first_unfilled_slice();
let bytes_to_write = slice.len().min(payload_to_write.len());
let slice_to_write = &payload_to_write[..bytes_to_write];
unsafe {
ptr::copy_nonoverlapping(slice_to_write.as_ptr(), slice.as_mut_ptr().cast(), bytes_to_write);
}
unsafe {
buf.advance(bytes_to_write);
}
payload_to_write = &payload_to_write[bytes_to_write..];
}
}