I'm writing a wrapper for a C library and I'm stuck writing tons of types like CVecOf<anything>
:
#[repr(C)]
pub struct CVecOfPoint {
pub array: *mut Point2i,
pub size: usize,
}
impl CVecOfPoint {
pub fn rustify(&self) -> Vec<Point2i> {
(0..self.size)
.map(|i| unsafe { *(self.array.offset(i as isize)) })
.collect::<Vec<_>>()
}
}
#[repr(C)]
pub struct CVecOfPoints {
pub array: *mut CVecOfPoint,
pub size: usize,
}
impl CVecOfPoints {
pub fn rustify(&self) -> Vec<Vec<Point2i>> {
(0..self.size)
.map(|i| unsafe {
let vec = &*self.array.offset(i as isize);
vec.rustify()
})
.collect::<Vec<_>>()
}
}
pub struct CVecOfPointsOfPoints;
pub struct CVecOfPointsOfPointsOfPoints;
pub struct CVecOfPointsOfPointsOfPointsOfPoints;
I'd like to write just CVec<T>
with following mapping rules:
rustify :=
T -> T
CVec<T> -> Vec<T>
Thus CVecOfPointsOfPointsOfPointsOfPoints
is just CVec<CVec<CVec<CVec<Cvec<Point>>>>>
.
Thanks to @red75prime, I have written the following, but it requires an unstable feature:
#![feature(specialization)]
#![deny(trivial_casts)]
use std::fmt::Debug;
use std::mem;
#[repr(C)]
#[derive(Debug)]
pub struct CVec<T: Sized> {
array: *mut T,
size: usize,
}
unsafe fn unpack_unsafe<T, R>(v: &CVec<T>) -> Vec<R> {
(0..v.size)
.map(|i| mem::transmute_copy(&*v.array.offset(i as isize)))
.collect()
}
pub fn unpack<T, U, F>(v: &CVec<T>, mut f: F) -> Vec<U>
where
F: FnMut(&T) -> U,
{
(0..v.size)
.map(|i| unsafe { f(&*v.array.offset(i as isize)) })
.collect()
}
trait Unpack {
type R: Debug;
fn unpack(&self) -> Vec<Self::R>;
}
impl<T: Debug> Unpack for CVec<T> {
default type R = T;
default fn unpack(&self) -> Vec<Self::R> {
unsafe { unpack_unsafe(self) }
}
}
impl<T: Unpack + Debug> Unpack for CVec<T> {
type R = Vec<T::R>;
fn unpack(&self) -> Vec<Self::R> {
unpack(self, |v| v.unpack())
}
}
fn main() {
let mut vs = [1, 2, 3];
let mut v1 = CVec {
array: vs.as_mut_ptr(),
size: vs.len(),
};
let mut v2 = CVec {
array: &mut v1 as *mut _,
size: 1,
};
let mut v3 = CVec {
array: &mut v2 as *mut _,
size: 1,
};
let v4 = CVec {
array: &mut v3 as *mut _,
size: 1,
};
let v = v4.unpack();
println!("{:?}", v);
let ptr: *mut () = &mut v3 as *mut _ as *mut _;
}
Is it possible to rewrite it with the stable compiler?
Important note: CVec<T>
implements Drop
because it must free allocated array
memory so it cannot be Copy
.