microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
alex/katas-update

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

allocator/src/mimalloc.rs

79lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use core::alloc::{GlobalAlloc, Layout};
5use core::ffi::c_void;
6
7use mimalloc_sys::{mi_free, mi_malloc_aligned, mi_realloc_aligned, mi_zalloc_aligned};
8
9pub struct Mimalloc;
10
11unsafe impl GlobalAlloc for Mimalloc {
12 #[inline]
13 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
14 debug_assert!(layout.align() < mimalloc_sys::MI_ALIGNMENT_MAX);
15 mi_malloc_aligned(layout.size(), layout.align()).cast::<u8>()
16 }
17
18 #[inline]
19 unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
20 mi_free(ptr.cast::<c_void>());
21 }
22
23 #[inline]
24 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
25 debug_assert!(layout.align() < mimalloc_sys::MI_ALIGNMENT_MAX);
26 mi_zalloc_aligned(layout.size(), layout.align()).cast::<u8>()
27 }
28
29 #[inline]
30 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
31 debug_assert!(layout.align() < mimalloc_sys::MI_ALIGNMENT_MAX);
32 mi_realloc_aligned(ptr.cast::<c_void>(), new_size, layout.align()).cast::<u8>()
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39 use std::error::Error;
40
41 #[test]
42 fn memory_can_be_allocated_and_freed() -> Result<(), Box<dyn Error>> {
43 let layout = Layout::from_size_align(8, 8)?;
44 let alloc = Mimalloc;
45
46 unsafe {
47 let ptr = alloc.alloc(layout);
48 assert!(!ptr.cast::<c_void>().is_null());
49 alloc.dealloc(ptr, layout);
50 }
51 Ok(())
52 }
53
54 #[test]
55 fn memory_can_be_alloc_zeroed_and_freed() -> Result<(), Box<dyn Error>> {
56 let layout = Layout::from_size_align(8, 8)?;
57 let alloc = Mimalloc;
58
59 unsafe {
60 let ptr = alloc.alloc_zeroed(layout);
61 assert!(!ptr.cast::<c_void>().is_null());
62 alloc.dealloc(ptr, layout);
63 }
64 Ok(())
65 }
66
67 #[test]
68 fn large_chunks_of_memory_can_be_allocated_and_freed() -> Result<(), Box<dyn Error>> {
69 let layout = Layout::from_size_align(2 * 1024 * 1024 * 1024, 8)?;
70 let alloc = Mimalloc;
71
72 unsafe {
73 let ptr = alloc.alloc(layout);
74 assert!(!ptr.cast::<c_void>().is_null());
75 alloc.dealloc(ptr, layout);
76 }
77 Ok(())
78 }
79}
80