malloc_array/
alloc.rs

1use std::{
2    ffi::c_void,
3    error,
4    fmt,
5};
6use crate::{
7    ptr::{self,VoidPointer,},
8};
9
10#[derive(Debug)]
11pub struct Error;
12
13impl error::Error for Error{}
14impl fmt::Display for Error
15{
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
17    {
18	write!(f, "Allocation failed.")
19    }
20}
21
22#[inline]
23unsafe fn malloc_internal(sz: libc::size_t) -> *mut c_void
24{
25    #[cfg(feature="jemalloc")]
26    return jemalloc_sys::malloc(sz);
27    #[cfg(not(feature="jemalloc"))]
28    return libc::malloc(sz);
29}
30#[inline]
31unsafe fn calloc_internal(nm: libc::size_t, sz: libc::size_t) -> *mut c_void
32{
33    #[cfg(feature="jemalloc")]
34    return jemalloc_sys::calloc(nm,sz);
35    #[cfg(not(feature="jemalloc"))]
36    return libc::calloc(nm,sz);
37}
38#[inline]
39unsafe fn free_internal(ptr: *mut c_void)
40{
41    #[cfg(feature="jemalloc")]
42    return jemalloc_sys::free(ptr);
43    #[cfg(not(feature="jemalloc"))]
44    return libc::free(ptr);
45}
46#[inline]
47unsafe fn realloc_internal(ptr: *mut c_void, sz: libc::size_t) -> *mut c_void
48{
49    #[cfg(feature="jemalloc")]
50    return jemalloc_sys::realloc(ptr,sz);
51    #[cfg(not(feature="jemalloc"))]
52    return libc::realloc(ptr,sz);
53}
54
55const NULL_PTR: *mut c_void = 0 as *mut c_void;
56
57pub unsafe fn malloc(sz: usize) -> Result<VoidPointer,Error>
58{
59    #[cfg(feature="zst_noalloc")]
60    if sz == 0 {
61	return Ok(ptr::NULL_PTR);
62    }
63    
64    match malloc_internal(sz as libc::size_t)
65    {
66	null if null == NULL_PTR => Err(Error),
67	ptr => Ok(ptr as VoidPointer),
68    }
69}
70
71pub unsafe fn calloc(nm: usize, sz: usize) -> Result<VoidPointer, Error>
72{
73    #[cfg(feature="zst_noalloc")]
74    if (nm*sz) == 0 {
75	return Ok(ptr::NULL_PTR);
76    }
77    
78    match calloc_internal(nm as libc::size_t, sz as libc::size_t)
79    {
80	null if null == NULL_PTR => Err(Error),
81	ptr => Ok(ptr as VoidPointer),
82    }
83}
84
85pub unsafe fn free(ptr: VoidPointer)
86{
87    if ptr != crate::ptr::NULL_PTR {
88	free_internal(ptr as *mut c_void);
89    }
90}
91
92pub unsafe fn realloc(ptr: VoidPointer, sz: usize) -> Result<VoidPointer, Error>
93{
94    #[cfg(feature="zst_noalloc")]
95    if sz == 0 {
96	free(ptr);
97	return Ok(crate::ptr::NULL_PTR);
98    }
99
100    if ptr == crate::ptr::NULL_PTR {
101	return malloc(sz);
102    }
103    
104    match realloc_internal(ptr as *mut c_void, sz as libc::size_t)
105    {
106	null if null == NULL_PTR => Err(Error),
107	ptr => Ok(ptr as VoidPointer),
108    }
109}