#![doc = include_str!("docs.md")]
#![deny(missing_docs)]
#![no_std]
extern crate alloc;
use core::mem::ManuallyDrop;
use core::ops::DerefMut;
use alloc::vec::Vec;
enum Allocation<D> {
Native,
Foreign(D),
}
pub struct ForeignVec<D, T> {
data: ManuallyDrop<Vec<T>>,
allocation: Allocation<D>,
}
impl<D, T> ForeignVec<D, T> {
#[inline]
pub unsafe fn from_foreign(ptr: *const T, length: usize, owner: D) -> Self {
assert!(!ptr.is_null());
let data = Vec::from_raw_parts(ptr as *mut T, length, length);
let data = ManuallyDrop::new(data);
Self {
data,
allocation: Allocation::Foreign(owner),
}
}
pub fn get_vec(&mut self) -> Option<&mut Vec<T>> {
match &self.allocation {
Allocation::Foreign(_) => None,
Allocation::Native => Some(self.data.deref_mut()),
}
}
}
impl<D, T> Drop for ForeignVec<D, T> {
#[inline]
fn drop(&mut self) {
match self.allocation {
Allocation::Foreign(_) => {
}
Allocation::Native => {
let data = core::mem::take(&mut self.data);
let _ = ManuallyDrop::into_inner(data);
}
}
}
}
impl<D, T> core::ops::Deref for ForeignVec<D, T> {
type Target = [T];
#[inline]
fn deref(&self) -> &[T] {
&self.data
}
}
impl<D, T: core::fmt::Debug> core::fmt::Debug for ForeignVec<D, T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
core::fmt::Debug::fmt(&**self, f)
}
}
impl<D, T> From<Vec<T>> for ForeignVec<D, T> {
#[inline]
fn from(data: Vec<T>) -> Self {
Self {
data: ManuallyDrop::new(data),
allocation: Allocation::Native,
}
}
}