dim/sdk/rust/src/c_buffer.rs

37 lines
896 B
Rust

#[derive(Debug)]
pub struct CBuffer<'a> {
inner: &'a mut [i8],
count: usize,
capacity: usize
}
#[allow(dead_code)] // rust_analyzer too dumb to see my macro magic
// i hate that macro as much as you do
impl CBuffer<'_> {
pub fn from_raw_parts_mut(buf: *mut i8, capacity: usize) -> Self {
Self {
inner: unsafe {
std::slice::from_raw_parts_mut(buf, capacity)
},
capacity,
count: 0,
}
}
}
impl std::fmt::Write for CBuffer<'_> {
fn write_str(&mut self, buf: &str) -> Result<(), std::fmt::Error> {
for c in buf.as_bytes() {
if self.count >= self.capacity - 1 {
return Ok(());
}
self.inner[self.count] = *c as i8;
self.count += 1;
}
self.inner[self.count] = 0;
Ok(())
}
}