jpegxl_sys\common/memory_manager.rs
1/*
2This file is part of jpegxl-sys.
3
4jpegxl-sys is free software: you can redistribute it and/or modify
5it under the terms of the GNU General Public License as published by
6the Free Software Foundation, either version 3 of the License, or
7(at your option) any later version.
8
9jpegxl-sys is distributed in the hope that it will be useful,
10but WITHOUT ANY WARRANTY; without even the implied warranty of
11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12GNU General Public License for more details.
13
14You should have received a copy of the GNU General Public License
15along with jpegxl-sys. If not, see <https://www.gnu.org/licenses/>.
16*/
17
18//! Abstraction functions used by JPEG XL to allocate memory.
19
20use std::ffi::c_void;
21
22/// Allocating function for a memory region of a given size.
23///
24/// Allocates a contiguous memory region of size `size` bytes. The returned
25/// memory may not be aligned to a specific size or initialized at all.
26///
27/// # Parameters
28/// - `opaque`: custom memory manager handle provided by the caller.
29/// - `size`: size in bytes of the requested memory region.
30///
31/// # Returns
32/// - `NULL` if the memory cannot be allocated.
33/// - Pointer to the memory otherwise.
34pub type JpegxlAllocFunc =
35 unsafe extern "C-unwind" fn(opaque: *mut c_void, size: usize) -> *mut c_void;
36
37/// Deallocating function pointer type.
38///
39/// This function **MUST** do nothing if `address` is `NULL`.
40///
41/// # Parameters
42/// - `opaque`: custom memory manager handle provided by the caller.
43/// - `address`: memory region pointer returned by [`JpegxlAllocFunc`], or `NULL`.
44pub type JpegxlFreeFunc = unsafe extern "C-unwind" fn(opaque: *mut c_void, address: *mut c_void);
45
46/// Memory Manager struct.
47/// These functions, when provided by the caller, will be used to handle memory
48/// allocations.
49#[repr(C)]
50#[derive(Debug, Clone)]
51pub struct JxlMemoryManager {
52 /// The opaque pointer that will be passed as the first parameter to all the
53 /// functions in this struct.
54 pub opaque: *mut c_void,
55
56 /// Memory allocation function. This can be NULL if and only if also the
57 /// [`Self::free`] member in this class is NULL. All dynamic memory will be allocated
58 /// and freed with these functions if they are not NULL, otherwise with the
59 /// standard malloc/free.
60 pub alloc: Option<JpegxlAllocFunc>,
61
62 /// Free function matching the [`Self::alloc`] member.
63 pub free: Option<JpegxlFreeFunc>,
64}