kanameshiki/
lib.rs

1#![no_std]
2
3use core::alloc::{GlobalAlloc, Layout};
4
5use kanameshiki_sys::{
6    KanameShiki_Align, KanameShiki_Alloc, KanameShiki_Free, KanameShiki_ReAlloc,
7};
8
9pub struct KanameShiki;
10
11unsafe impl GlobalAlloc for KanameShiki {
12    #[inline]
13    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
14        if layout.align() == 1 {
15            return KanameShiki_Alloc(layout.size().try_into().unwrap()) as _;
16        }
17        KanameShiki_Align(
18            layout.align().try_into().unwrap(),
19            layout.size().try_into().unwrap(),
20        ) as _
21    }
22
23    #[inline]
24    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
25        KanameShiki_Free(ptr as _)
26    }
27
28    #[inline]
29    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
30        unimplemented!("zeroed allocated blocks are not implemented")
31    }
32
33    #[inline]
34    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
35        KanameShiki_ReAlloc(ptr as _, new_size.try_into().unwrap()) as _
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use core::{i128, mem::forget};
42
43    use alloc::{borrow::Cow, boxed::Box, rc::Rc, string::String, sync::Arc, vec::Vec};
44
45    extern crate alloc;
46
47    use super::*;
48
49    #[global_allocator]
50    static GLOBAL: KanameShiki = KanameShiki;
51
52    #[test]
53    fn vec_alloc() {
54        let mut v: Vec<u8> = Vec::new();
55        v.push(1);
56        v.push(2);
57        v.push(3);
58        v.push(4);
59        v.push(5);
60    }
61
62    #[test]
63    fn rc_alloc() {
64        let mut rc: Rc<i128> = Rc::new(12345678910);
65    }
66
67    #[test]
68    fn arc_alloc() {
69        let mut arc: Arc<i128> = Arc::new(12345678910);
70    }
71
72    #[test]
73    fn string_alloc() {
74        String::from("The KanameShiki Memory Allocator is a fast, general purpose allocator with a lot of additional features.");
75    }
76
77    #[test]
78    fn box_alloc() {
79        let bbox: Box<i128> = Box::new(12345678910);
80    }
81
82    /*#[test]
83    fn hashtable_alloc() {
84    let dict: Has<u128, u128> = HashMap::new();
85    dict.insert(4124651, -9187517915);
86    }*/
87
88    #[test]
89    fn cow_alloc() {
90        let mut cow = Cow::Borrowed("borrowed cow using KanameShiki");
91        cow += "z";
92    }
93}