c_ffi/
memory.rs

1//! Memory related utilities
2//!
3//!## Required features:
4//!
5//! - `memory`
6
7///Wrapper for `libc::free`
8pub struct FreeFn;
9
10impl smart_ptr::Deleter for FreeFn {
11    fn delete<T>(&mut self, ptr: *mut u8) {
12        unsafe {
13            libc::free(ptr as *mut _);
14        }
15    }
16}
17
18///Alias to unique ptr, suitable for malloc
19pub type Box = smart_ptr::Unique<libc::c_void, FreeFn>;
20
21///Extension to Unique for use with malloc
22pub trait Malloc: Sized {
23    ///Creates new memory using `malloc`
24    ///
25    ///# Panics:
26    ///
27    ///- When `malloc` returns 0
28    fn malloc(size: usize) -> Self;
29}
30
31impl Malloc for Box {
32    fn malloc(size: usize) -> Self {
33        let ptr = unsafe {
34            libc::malloc(size)
35        };
36
37        if ptr.is_null() {
38            panic!("libc::malloc failed");
39        }
40
41
42        unsafe {
43            Self::new(ptr, FreeFn)
44        }
45    }
46}