1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::{
ptr, slice, marker::PhantomData, os::raw::c_void,
ops::{ Deref, DerefMut }
};
mod vec_impl {
use super::*;
pub unsafe extern "C" fn dealloc<T>(array: *mut Array<T>) {
if let Some(array) = array.as_mut() {
if !array.object.is_null() {
let _vec = Box::from_raw(array.object);
array.object = ptr::null_mut();
}
}
}
pub unsafe extern "C" fn len<T>(array: *const Array<T>) -> usize {
array.as_ref().expect("Unexpected NULL pointer")
.object.cast::<Vec<T>>().as_ref().expect("Unexpected NULL pointer")
.len()
}
pub unsafe extern "C" fn data<T>(array: *const Array<T>) -> *const T {
array.as_ref().expect("Unexpected NULL pointer")
.object.cast::<Vec<T>>().as_ref().expect("Unexpected NULL pointer")
.as_ptr()
}
pub unsafe extern "C" fn data_mut<T>(array: *mut Array<T>) -> *mut T {
array.as_mut().expect("Unexpected NULL pointer")
.object.cast::<Vec<T>>().as_mut().expect("Unexpected NULL pointer")
.as_mut_ptr()
}
}
#[repr(C)]
pub struct Array<T> {
pub dealloc: unsafe extern "C" fn(*mut Self),
pub len: unsafe extern "C" fn(*const Self) -> usize,
pub data: unsafe extern "C" fn(*const Self) -> *const T,
pub data_mut: unsafe extern "C" fn(*mut Self) -> *mut T,
pub object: *mut c_void,
_type: PhantomData<T>
}
impl<T> Array<T> {
pub fn len(&self) -> usize {
unsafe{ (self.len)(self) }
}
}
impl<T> Deref for Array<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
let len = self.len();
let data = unsafe{ (self.data)(self) };
unsafe{ slice::from_raw_parts(data, len) }
}
}
impl<T> DerefMut for Array<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
let len = self.len();
let data = unsafe{ (self.data_mut)(self) };
unsafe{ slice::from_raw_parts_mut(data, len) }
}
}
impl<T> From<Vec<T>> for Array<T> {
fn from(vec: Vec<T>) -> Self {
Self {
dealloc: vec_impl::dealloc::<T>,
len: vec_impl::len::<T>,
data: vec_impl::data::<T>,
data_mut: vec_impl::data_mut::<T>,
object: Box::into_raw(Box::new(vec)) as *mut c_void,
_type: PhantomData
}
}
}
impl<T> Drop for Array<T> {
fn drop(&mut self) {
unsafe{ (self.dealloc)(self) }
}
}