1 extern crate tikv_jemalloc_sys as ffi;
2 
3 use std::mem;
4 use std::ptr;
5 
6 use libc::{c_char, c_void};
7 use tikv_jemallocator::Jemalloc;
8 
9 #[global_allocator]
10 static A: Jemalloc = Jemalloc;
11 
12 #[test]
test_basic_alloc()13 fn test_basic_alloc() {
14     unsafe {
15         let exp_size = ffi::nallocx(100, 0);
16         assert!(exp_size >= 100);
17 
18         let mut ptr = ffi::mallocx(100, 0);
19         assert!(!ptr.is_null());
20         assert_eq!(exp_size, ffi::malloc_usable_size(ptr));
21         ptr = ffi::rallocx(ptr, 50, 0);
22         let size = ffi::xallocx(ptr, 30, 20, 0);
23         assert!(size >= 50);
24         ffi::sdallocx(ptr, 50, 0);
25     }
26 }
27 
28 #[test]
test_mallctl()29 fn test_mallctl() {
30     let ptr = unsafe { ffi::mallocx(100, 0) };
31     let mut allocated: usize = 0;
32     let mut val_len = mem::size_of_val(&allocated);
33     let field = "stats.allocated\0";
34     let mut code;
35     code = unsafe {
36         ffi::mallctl(
37             field.as_ptr() as *const _,
38             &mut allocated as *mut _ as *mut c_void,
39             &mut val_len,
40             ptr::null_mut(),
41             0,
42         )
43     };
44     assert_eq!(code, 0);
45     assert!(allocated > 0);
46 
47     let mut mib = [0, 0];
48     let mut mib_len = 2;
49     code = unsafe {
50         ffi::mallctlnametomib(field.as_ptr() as *const _, mib.as_mut_ptr(), &mut mib_len)
51     };
52     assert_eq!(code, 0);
53     let mut allocated_by_mib = 0;
54     let code = unsafe {
55         ffi::mallctlbymib(
56             mib.as_ptr(),
57             mib_len,
58             &mut allocated_by_mib as *mut _ as *mut c_void,
59             &mut val_len,
60             ptr::null_mut(),
61             0,
62         )
63     };
64     assert_eq!(code, 0);
65     assert_eq!(allocated_by_mib, allocated);
66 
67     unsafe { ffi::sdallocx(ptr, 100, 0) };
68 }
69 
70 #[test]
test_stats()71 fn test_stats() {
72     struct PrintCtx {
73         called_times: usize,
74     }
75 
76     extern "C" fn write_cb(ctx: *mut c_void, _: *const c_char) {
77         let print_ctx = unsafe { &mut *(ctx as *mut PrintCtx) };
78         print_ctx.called_times += 1;
79     }
80 
81     let mut ctx = PrintCtx { called_times: 0 };
82     unsafe {
83         ffi::malloc_stats_print(
84             Some(write_cb),
85             &mut ctx as *mut _ as *mut c_void,
86             ptr::null(),
87         );
88     }
89     assert_ne!(
90         ctx.called_times, 0,
91         "print should be triggered at lease once."
92     );
93 }
94