use core::fmt;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use crate::meta::PacketMeta;
pub struct RawDriverBuf {
pub free: unsafe fn(NonNull<RawDriverBuf>),
pub pool: *const (),
pub data: NonNull<u8>,
pub capacity: usize,
pub headroom: usize,
pub len: usize,
pub meta: PacketMeta,
}
pub struct DriverBuf {
raw: NonNull<RawDriverBuf>,
}
unsafe impl Send for DriverBuf {}
unsafe impl Sync for DriverBuf {}
impl DriverBuf {
pub unsafe fn from_raw(raw: NonNull<RawDriverBuf>) -> Self {
Self { raw }
}
#[inline]
fn raw(&self) -> &RawDriverBuf {
unsafe { self.raw.as_ref() }
}
#[inline]
fn raw_mut(&mut self) -> &mut RawDriverBuf {
unsafe { self.raw.as_mut() }
}
#[inline]
fn storage(&self) -> &[u8] {
let raw = self.raw();
unsafe { core::slice::from_raw_parts(raw.data.as_ptr(), raw.capacity) }
}
pub fn pool(&self) -> *const () {
self.raw().pool
}
pub fn meta(&self) -> PacketMeta {
self.raw().meta
}
pub fn meta_mut(&mut self) -> &mut PacketMeta {
&mut self.raw_mut().meta
}
pub fn set_meta(&mut self, meta: PacketMeta) {
self.raw_mut().meta = meta;
}
pub fn capacity(&self) -> usize {
self.raw().capacity
}
pub fn headroom(&self) -> usize {
self.raw().headroom
}
pub fn len(&self) -> usize {
self.raw().len
}
pub fn is_empty(&self) -> bool {
self.raw().len == 0
}
pub fn tailroom(&self) -> usize {
self.capacity() - self.headroom() - self.len()
}
pub fn reserve(&mut self, headroom: usize) {
assert!(headroom <= self.capacity());
let raw = self.raw_mut();
raw.headroom = headroom;
raw.len = 0;
}
pub fn push_front(&mut self, n: usize) {
assert!(n <= self.headroom());
let raw = self.raw_mut();
raw.headroom -= n;
raw.len += n;
}
pub fn pull_front(&mut self, n: usize) {
assert!(n <= self.len());
let raw = self.raw_mut();
raw.headroom += n;
raw.len -= n;
}
pub fn ensure_headroom(&mut self, headroom: usize) -> bool {
if self.headroom() >= headroom {
return true;
}
let len = self.len();
if headroom + len > self.capacity() {
return false;
}
let old = self.headroom();
self.storage_mut().copy_within(old..old + len, headroom);
self.raw_mut().headroom = headroom;
true
}
pub fn set_len(&mut self, len: usize) {
assert!(self.headroom() + len <= self.capacity());
self.raw_mut().len = len;
}
pub fn storage_mut(&mut self) -> &mut [u8] {
let raw = self.raw_mut();
unsafe { core::slice::from_raw_parts_mut(raw.data.as_ptr(), raw.capacity) }
}
}
impl Drop for DriverBuf {
#[inline(never)] fn drop(&mut self) {
let free = self.raw().free;
unsafe { free(self.raw) }
}
}
impl Deref for DriverBuf {
type Target = [u8];
fn deref(&self) -> &Self::Target {
let raw = self.raw();
let start = raw.headroom;
let len = raw.len;
unsafe { self.storage().get_unchecked(start..start + len) }
}
}
impl DerefMut for DriverBuf {
fn deref_mut(&mut self) -> &mut Self::Target {
let raw = self.raw();
let start = raw.headroom;
let len = raw.len;
unsafe { self.storage_mut().get_unchecked_mut(start..start + len) }
}
}
impl fmt::Debug for DriverBuf {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DriverBuf")
.field("headroom", &self.headroom())
.field("len", &self.len())
.finish()
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for DriverBuf {
fn format(&self, f: defmt::Formatter<'_>) {
defmt::write!(f, "DriverBuf {{ headroom: {}, len: {} }}", self.headroom(), self.len());
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::mem::MaybeUninit;
use std::boxed::Box;
use std::sync::Mutex;
const SIZE: usize = 256;
struct TestPool {
out: Mutex<usize>,
}
#[repr(C)]
struct TestBuf {
raw: MaybeUninit<RawDriverBuf>,
data: [u8; SIZE],
}
impl TestPool {
fn alloc(&'static self) -> Option<DriverBuf> {
*self.out.lock().unwrap() += 1;
let buf = Box::leak(Box::new(TestBuf {
raw: MaybeUninit::uninit(),
data: [0xa5; SIZE],
}));
let raw = buf.raw.write(RawDriverBuf {
free,
pool: (self as *const TestPool).cast(),
data: NonNull::from(&mut buf.data).cast(),
capacity: SIZE,
headroom: 0,
len: 0,
meta: PacketMeta::default(),
});
Some(unsafe { DriverBuf::from_raw(NonNull::from(raw)) })
}
}
unsafe fn free(raw: NonNull<RawDriverBuf>) {
unsafe {
let pool = &*raw.as_ref().pool.cast::<TestPool>();
drop(Box::from_raw(raw.cast::<TestBuf>().as_ptr()));
*pool.out.lock().unwrap() -= 1;
}
}
fn pool() -> &'static TestPool {
Box::leak(Box::new(TestPool { out: Mutex::new(0) }))
}
#[test]
fn push_pull() {
let mut buf = pool().alloc().unwrap();
assert_eq!(buf.len(), 0);
assert_eq!(buf.headroom(), 0);
assert_eq!(buf.capacity(), SIZE);
assert_eq!(buf.tailroom(), SIZE);
buf.reserve(42);
assert_eq!(buf.headroom(), 42);
buf.set_len(100);
assert_eq!(buf.len(), 100);
assert_eq!(buf.tailroom(), SIZE - 142);
buf.fill(0xaa);
buf.push_front(20);
assert_eq!(buf.headroom(), 22);
assert_eq!(buf.len(), 120);
assert_eq!(buf[20], 0xaa);
buf.pull_front(20);
assert_eq!(buf.headroom(), 42);
assert_eq!(buf.len(), 100);
assert_eq!(buf[0], 0xaa);
}
#[test]
fn ensure_headroom() {
let mut buf = pool().alloc().unwrap();
buf.reserve(10);
buf.set_len(4);
buf.copy_from_slice(&[1, 2, 3, 4]);
assert!(buf.ensure_headroom(4));
assert_eq!(buf.headroom(), 10);
assert_eq!(&*buf, &[1, 2, 3, 4]);
assert!(buf.ensure_headroom(20));
assert_eq!(buf.headroom(), 20);
assert_eq!(buf.len(), 4);
assert_eq!(&*buf, &[1, 2, 3, 4]);
assert!(buf.ensure_headroom(22));
assert_eq!(&*buf, &[1, 2, 3, 4]);
assert!(!buf.ensure_headroom(SIZE - 3));
assert_eq!(buf.headroom(), 22);
assert_eq!(&*buf, &[1, 2, 3, 4]);
assert!(buf.ensure_headroom(SIZE - 4));
assert_eq!(&*buf, &[1, 2, 3, 4]);
}
#[test]
#[should_panic]
fn push_beyond_headroom() {
let mut buf = pool().alloc().unwrap();
buf.push_front(1);
}
#[test]
fn drop_releases_to_its_pool() {
let a = pool();
let b = pool();
let buf_a = a.alloc().unwrap();
let buf_b = b.alloc().unwrap();
assert_eq!(*a.out.lock().unwrap(), 1);
assert_eq!(*b.out.lock().unwrap(), 1);
drop(buf_a);
assert_eq!(*a.out.lock().unwrap(), 0);
assert_eq!(*b.out.lock().unwrap(), 1);
drop(buf_b);
assert_eq!(*b.out.lock().unwrap(), 0);
}
#[cfg(feature = "packetmeta-id")]
#[test]
fn meta_travels_with_the_buffer() {
let mut buf = pool().alloc().unwrap();
assert_eq!(buf.meta(), PacketMeta::default());
buf.meta_mut().id = 0xdead_beef;
buf.reserve(20);
buf.set_len(10);
buf.push_front(20);
buf.pull_front(4);
assert_eq!(buf.meta().id, 0xdead_beef);
buf.set_meta(PacketMeta::default());
assert_eq!(buf.meta().id, 0);
}
}