Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-python/src/c_api/allocator.rs
7889 views
1
#[cfg(all(
2
not(feature = "default_alloc"),
3
target_family = "unix",
4
not(target_os = "emscripten"),
5
))]
6
#[global_allocator]
7
static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
8
9
#[cfg(all(
10
not(feature = "default_alloc"),
11
any(not(target_family = "unix"), target_os = "emscripten"),
12
))]
13
#[global_allocator]
14
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
15
16
use std::alloc::Layout;
17
use std::ffi::{c_char, c_void};
18
19
use pyo3::ffi::PyCapsule_New;
20
use pyo3::{Bound, PyAny, PyResult, Python};
21
22
unsafe extern "C" fn alloc(size: usize, align: usize) -> *mut u8 {
23
unsafe { std::alloc::alloc(Layout::from_size_align_unchecked(size, align)) }
24
}
25
26
unsafe extern "C" fn dealloc(ptr: *mut u8, size: usize, align: usize) {
27
unsafe { std::alloc::dealloc(ptr, Layout::from_size_align_unchecked(size, align)) }
28
}
29
30
unsafe extern "C" fn alloc_zeroed(size: usize, align: usize) -> *mut u8 {
31
unsafe { std::alloc::alloc_zeroed(Layout::from_size_align_unchecked(size, align)) }
32
}
33
34
unsafe extern "C" fn realloc(ptr: *mut u8, size: usize, align: usize, new_size: usize) -> *mut u8 {
35
unsafe {
36
std::alloc::realloc(
37
ptr,
38
Layout::from_size_align_unchecked(size, align),
39
new_size,
40
)
41
}
42
}
43
44
#[repr(C)]
45
struct AllocatorCapsule {
46
alloc: unsafe extern "C" fn(usize, usize) -> *mut u8,
47
dealloc: unsafe extern "C" fn(*mut u8, usize, usize),
48
alloc_zeroed: unsafe extern "C" fn(usize, usize) -> *mut u8,
49
realloc: unsafe extern "C" fn(*mut u8, usize, usize, usize) -> *mut u8,
50
}
51
52
static ALLOCATOR_CAPSULE: AllocatorCapsule = AllocatorCapsule {
53
alloc,
54
alloc_zeroed,
55
dealloc,
56
realloc,
57
};
58
59
static ALLOCATOR_CAPSULE_NAME: &[u8] = b"polars.polars._allocator\0";
60
61
pub fn create_allocator_capsule(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
62
unsafe {
63
Bound::from_owned_ptr_or_err(
64
py,
65
PyCapsule_New(
66
&ALLOCATOR_CAPSULE as *const AllocatorCapsule
67
// Users of this capsule is not allowed to modify it.
68
as *mut c_void,
69
ALLOCATOR_CAPSULE_NAME.as_ptr() as *const c_char,
70
None,
71
),
72
)
73
}
74
}
75
76