GitHub project page

 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

use libc::c_void;
use libc::funcs::c95::stdlib::free;
use std::slice;
use std::mem::transmute;

/// Horrible kludge to free memory allocated by lodepng
pub struct CVec<T> {
    elements: usize,
    ptr: *mut T,
}

impl<T> CVec<T> {
    pub unsafe fn new(ptr: *mut T, elements: usize) -> CVec<T> {
        CVec {ptr:ptr, elements:elements}
    }

    /// Number of elements (pixels for pixel type, bytes for u8 type only)
    pub fn len(&self) -> usize {
        self.elements
    }

    /// *Copies* elements into a Vec
    pub fn to_vec(&self) -> Vec<T> {
        unsafe {
            Vec::from_raw_buf(self.ptr, self.elements)
        }
    }

    /// Exposes memory as slice without copying
    pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
        unsafe {
            slice::from_raw_mut_buf(&mut self.ptr, self.elements)
        }
    }
    /// Exposes memory as raw bytes slice without copying
    pub fn as_u8_slice<'a>(&'a self) -> &'a [u8] {
        unsafe {
            slice::from_raw_buf(transmute(&self.ptr), self.elements * ::std::mem::size_of::<T>())
        }
    }
}

impl<T> AsSlice<T> for CVec<T> {
    /// Exposes pixel's memory as slice without copying
    fn as_slice(&self) -> &[T] {
        unsafe {
            slice::from_raw_buf(transmute(&self.ptr), self.elements)
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for CVec<T> {
    fn drop(&mut self) {
        unsafe {
            free(self.ptr as *mut c_void);
        }
    }
}