Skip to main content

cyo_mimalloc/
api.rs

1//! Statistics, options, the version and process information.
2
3use crate::MiMalloc;
4use core::ffi::{c_long, c_void};
5use core::fmt;
6use cyo_mimalloc_sys::mi_option_t;
7
8/// Tells mimalloc that the current thread is a worker of a thread pool.
9///
10/// mimalloc then does not move pages that other threads abandoned into this
11/// thread. Call it on each worker thread of a thread pool of your own.
12/// Calling it again has no further effect.
13#[inline]
14pub fn set_current_thread_in_threadpool() {
15    // SAFETY: `mi_thread_set_in_threadpool` has no preconditions.
16    unsafe { cyo_mimalloc_sys::mi_thread_set_in_threadpool() }
17}
18
19/// The time and memory use of the process, from [`MiMalloc::process_info`].
20#[derive(Debug, Clone, Copy, Default)]
21pub struct ProcessInfo {
22    /// The wall-clock time in milliseconds since the process started.
23    pub elapsed_msecs: usize,
24    /// The CPU time in milliseconds that the process spent in user mode.
25    pub user_msecs: usize,
26    /// The CPU time in milliseconds that the process spent in the kernel.
27    pub system_msecs: usize,
28    /// The current resident set size in bytes.
29    ///
30    /// On Linux, mimalloc cannot read this value, and reports the memory it
31    /// has committed instead.
32    pub current_rss: usize,
33    /// The largest resident set size in bytes that the process has had.
34    pub peak_rss: usize,
35    /// The number of bytes that mimalloc has committed.
36    pub current_commit: usize,
37    /// The largest number of bytes that mimalloc has had committed.
38    pub peak_commit: usize,
39    /// The number of page faults that the process has had. On Linux, this is
40    /// the number of major faults.
41    pub page_faults: usize,
42}
43
44impl MiMalloc {
45    /// Returns the mimalloc version as `major * 10000 + minor * 100 + patch`,
46    /// for example 30503 for v3.5.3.
47    #[inline]
48    pub fn version() -> i32 {
49        // SAFETY: `mi_version` has no preconditions.
50        unsafe { cyo_mimalloc_sys::mi_version() }
51    }
52
53    /// Returns memory that the current thread no longer uses.
54    ///
55    /// With `force`, mimalloc also purges unused memory immediately, instead
56    /// of after `mi_option_purge_delay`.
57    #[inline]
58    pub fn collect(force: bool) {
59        // SAFETY: `mi_collect` has no preconditions.
60        unsafe { cyo_mimalloc_sys::mi_collect(force) }
61    }
62
63    /// Returns the usable size in bytes of the block at `ptr`.
64    ///
65    /// The usable size can be larger than the size that was requested.
66    ///
67    /// # Safety
68    ///
69    /// `ptr` must be a block that mimalloc allocated and that you have not
70    /// freed.
71    #[inline]
72    pub unsafe fn usable_size(ptr: *const u8) -> usize {
73        // SAFETY: the caller guarantees that `ptr` is a live mimalloc block.
74        unsafe { cyo_mimalloc_sys::mi_usable_size(ptr as *const c_void) }
75    }
76
77    /// Returns the time and memory use of the process.
78    pub fn process_info() -> ProcessInfo {
79        let mut info = ProcessInfo::default();
80        // SAFETY: every argument points to a field of `info`, which is valid
81        // for writes.
82        unsafe {
83            cyo_mimalloc_sys::mi_process_info(
84                &mut info.elapsed_msecs,
85                &mut info.user_msecs,
86                &mut info.system_msecs,
87                &mut info.current_rss,
88                &mut info.peak_rss,
89                &mut info.current_commit,
90                &mut info.peak_commit,
91                &mut info.page_faults,
92            );
93        }
94        info
95    }
96
97    // ── Stats ───────────────────────────────────────────────────────────────
98
99    /// Writes the allocation statistics to `out` as JSON.
100    ///
101    /// # Errors
102    ///
103    /// Returns [`fmt::Error`] if mimalloc cannot produce the statistics, or if
104    /// `out` returns an error.
105    pub fn stats_json(out: &mut (impl fmt::Write + ?Sized)) -> fmt::Result {
106        // SAFETY: with a null buffer, `mi_stats_get_json` returns a string
107        // that mimalloc allocated and that the caller owns, or null.
108        unsafe {
109            crate::ffi::write_owned_c_string(
110                out,
111                cyo_mimalloc_sys::mi_stats_get_json(0, core::ptr::null_mut()),
112            )
113        }
114    }
115
116    /// Writes the allocation statistics to `out` as mimalloc's text table.
117    ///
118    /// # Errors
119    ///
120    /// Returns [`fmt::Error`] if `out` returns an error.
121    pub fn stats_print(out: &mut dyn fmt::Write) -> fmt::Result {
122        // SAFETY: `write_output` passes a callback and an argument that stay
123        // valid for the call.
124        crate::ffi::write_output(out, |out, arg| unsafe {
125            cyo_mimalloc_sys::mi_stats_print_out(out, arg);
126        })
127    }
128
129    /// Resets the allocation statistics to zero.
130    #[inline]
131    pub fn stats_reset() {
132        // SAFETY: `mi_stats_reset` has no preconditions.
133        unsafe { cyo_mimalloc_sys::mi_stats_reset() }
134    }
135
136    /// Writes the time and memory use of the process to `out` as mimalloc's
137    /// text table.
138    ///
139    /// # Errors
140    ///
141    /// Returns [`fmt::Error`] if `out` returns an error.
142    pub fn process_info_print(out: &mut dyn fmt::Write) -> fmt::Result {
143        // SAFETY: `write_output` passes a callback and an argument that stay
144        // valid for the call.
145        crate::ffi::write_output(out, |out, arg| unsafe {
146            cyo_mimalloc_sys::mi_process_info_print_out(out, arg);
147        })
148    }
149
150    // ── Options ─────────────────────────────────────────────────────────────
151    //
152    // The crate documentation describes how options are set, and
153    // `mi_option_t` describes each option and when mimalloc reads it.
154
155    /// Returns whether an option is enabled, which means its value is not 0.
156    #[inline]
157    pub fn option_is_enabled(option: mi_option_t) -> bool {
158        // SAFETY: `mi_option_is_enabled` has no preconditions.
159        unsafe { cyo_mimalloc_sys::mi_option_is_enabled(option) }
160    }
161
162    /// Returns the current value of an option.
163    ///
164    /// For an option measured in KiB, the value is in KiB. To get it in bytes,
165    /// call [`option_get_size`](Self::option_get_size).
166    #[inline]
167    pub fn option_get(option: mi_option_t) -> c_long {
168        // SAFETY: `mi_option_get` has no preconditions.
169        unsafe { cyo_mimalloc_sys::mi_option_get(option) }
170    }
171
172    /// Returns the current value in bytes of an option measured in KiB.
173    #[inline]
174    pub fn option_get_size(option: mi_option_t) -> usize {
175        // SAFETY: `mi_option_get_size` has no preconditions.
176        unsafe { cyo_mimalloc_sys::mi_option_get_size(option) }
177    }
178
179    /// Sets an option to `value`. For an option measured in KiB, `value` is in
180    /// KiB.
181    ///
182    /// The value overrides the build-time default and the `MIMALLOC_*`
183    /// environment variable. It only has an effect if mimalloc reads the option
184    /// again afterwards. mimalloc reads some options only at startup, before
185    /// `main` runs. [`mi_option_t`] marks them, and the crate documentation
186    /// describes how to set them.
187    ///
188    /// ```rust
189    /// use cyo_mimalloc::{MiMalloc, mi_option_t};
190    ///
191    /// // Return unused memory to the OS immediately.
192    /// MiMalloc::option_set(mi_option_t::mi_option_purge_delay, 0);
193    /// ```
194    #[inline]
195    pub fn option_set(option: mi_option_t, value: c_long) {
196        // SAFETY: `mi_option_set` has no preconditions.
197        unsafe { cyo_mimalloc_sys::mi_option_set(option, value) }
198    }
199
200    /// Sets an option to 1, as [`option_set`](Self::option_set) does.
201    #[inline]
202    pub fn option_enable(option: mi_option_t) {
203        // SAFETY: `mi_option_enable` has no preconditions.
204        unsafe { cyo_mimalloc_sys::mi_option_enable(option) }
205    }
206
207    /// Sets an option to 0, as [`option_set`](Self::option_set) does.
208    #[inline]
209    pub fn option_disable(option: mi_option_t) {
210        // SAFETY: `mi_option_disable` has no preconditions.
211        unsafe { cyo_mimalloc_sys::mi_option_disable(option) }
212    }
213}
214
215// ── Tests ───────────────────────────────────────────────────────────────────
216
217#[cfg(test)]
218mod tests {
219    use super::*;
220    use std::string::String;
221
222    #[test]
223    fn version_is_v3() {
224        assert!(MiMalloc::version() >= 30502, "expected >= v3.5.2");
225    }
226
227    #[test]
228    fn stats_json_not_empty() {
229        let mut json = String::new();
230        MiMalloc::stats_json(&mut json).unwrap();
231        assert!(json.starts_with('{'));
232    }
233
234    #[test]
235    fn stats_print_not_empty() {
236        let mut stats = String::new();
237        MiMalloc::stats_print(&mut stats).unwrap();
238        assert!(!stats.is_empty());
239    }
240
241    #[test]
242    fn stats_print_propagates_writer_errors() {
243        struct Failing;
244        impl fmt::Write for Failing {
245            fn write_str(&mut self, _: &str) -> fmt::Result {
246                Err(fmt::Error)
247            }
248        }
249        assert!(MiMalloc::stats_print(&mut Failing).is_err());
250        assert!(MiMalloc::stats_json(&mut Failing).is_err());
251    }
252
253    #[test]
254    fn stats_reset_smoke() {
255        MiMalloc::stats_reset();
256    }
257
258    #[test]
259    fn process_info_print_not_empty() {
260        let mut info = String::new();
261        MiMalloc::process_info_print(&mut info).unwrap();
262        assert!(!info.is_empty());
263    }
264
265    #[test]
266    fn option_roundtrip() {
267        let option = mi_option_t::mi_option_purge_delay;
268        let original = MiMalloc::option_get(option);
269        MiMalloc::option_set(option, original + 7);
270        assert_eq!(MiMalloc::option_get(option), original + 7);
271        MiMalloc::option_set(option, original);
272        assert_eq!(MiMalloc::option_get(option), original);
273
274        let _ = MiMalloc::option_is_enabled(mi_option_t::mi_option_show_errors);
275    }
276
277    #[test]
278    fn process_info_smoke() {
279        let info = MiMalloc::process_info();
280        let _ = info;
281    }
282
283    #[test]
284    fn set_current_thread_in_threadpool_smoke() {
285        set_current_thread_in_threadpool();
286        set_current_thread_in_threadpool();
287    }
288
289    #[test]
290    fn usable_size_at_least_requested() {
291        unsafe {
292            let ptr = cyo_mimalloc_sys::mi_malloc(64);
293            assert!(MiMalloc::usable_size(ptr as *const u8) >= 64);
294            cyo_mimalloc_sys::mi_free(ptr);
295        }
296    }
297}