#![feature(maybe_uninit_slice)]
use libc::{c_char, c_void, size_t};
use std::mem::MaybeUninit;
use std::vec::Vec;
pub trait TxBuffer {
fn len(&self) -> usize;
fn as_c_void(&self) -> (*const c_void, size_t);
fn as_c_char(&self) -> (*const c_char, size_t);
}
impl TxBuffer for Vec<u8> {
fn len(&self) -> usize {
self.len()
}
fn as_c_void(&self) -> (*const c_void, size_t) {
(self.as_ptr() as *mut c_void, self.len())
}
fn as_c_char(&self) -> (*const c_char, size_t) {
(self.as_ptr() as *mut c_char, self.len())
}
}
impl<const N: usize> TxBuffer for [u8; N] {
fn len(&self) -> usize {
N
}
fn as_c_void(&self) -> (*const c_void, size_t) {
(self.as_ptr() as *mut c_void, self.len())
}
fn as_c_char(&self) -> (*const c_char, size_t) {
(self.as_ptr() as *mut c_char, self.len())
}
}
pub trait RxBuffer {
fn capacity(&self) -> usize;
fn as_c_void(&mut self) -> (*mut c_void, size_t);
fn as_c_char(&mut self) -> (*mut c_char, size_t);
unsafe fn done(&mut self, len: size_t) -> &mut [u8];
#[inline]
fn can_set_capacity(&mut self) -> Option<&mut dyn ResizeableBuffer> {
None
}
}
impl RxBuffer for Vec<u8> {
fn capacity(&self) -> usize {
self.capacity()
}
fn as_c_void(&mut self) -> (*mut c_void, size_t) {
(self.as_mut_ptr() as *mut c_void, self.capacity())
}
fn as_c_char(&mut self) -> (*mut c_char, size_t) {
(self.as_mut_ptr() as *mut c_char, self.capacity())
}
unsafe fn done(&mut self, len: usize) -> &mut [u8] {
assert!(len <= self.capacity());
self.set_len(len);
&mut self[..len]
}
#[inline]
fn can_set_capacity(&mut self) -> Option<&mut dyn ResizeableBuffer> {
Some(self)
}
}
impl<const N: usize> RxBuffer for [u8; N] {
fn capacity(&self) -> usize {
N
}
fn as_c_void(&mut self) -> (*mut c_void, size_t) {
(self.as_mut_ptr() as *mut c_void, N)
}
fn as_c_char(&mut self) -> (*mut c_char, size_t) {
(self.as_mut_ptr() as *mut c_char, N)
}
unsafe fn done(&mut self, len: usize) -> &mut [u8] {
&mut self[..len]
}
}
impl<const N: usize> RxBuffer for [MaybeUninit<u8>; N] {
fn capacity(&self) -> usize {
N
}
fn as_c_void(&mut self) -> (*mut c_void, size_t) {
(self.as_mut_ptr() as *mut c_void, N)
}
fn as_c_char(&mut self) -> (*mut c_char, size_t) {
(self.as_mut_ptr() as *mut c_char, N)
}
unsafe fn done(&mut self, len: usize) -> &mut [u8] {
MaybeUninit::slice_assume_init_mut(&mut self[..len])
}
}
pub trait ResizeableBuffer {
fn set_capacity(&mut self, len: usize);
}
impl ResizeableBuffer for Vec<u8> {
fn set_capacity(&mut self, len: usize) {
if self.capacity() < len {
self.reserve(len - self.len());
};
}
}