Skip to content

Commit 45d0180

Browse files
sisciagavrie
authored andcommitted
cleaner way to use redis allocator
1 parent 1428bea commit 45d0180

File tree

2 files changed

+14
-18
lines changed

2 files changed

+14
-18
lines changed

src/alloc.rs

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::alloc::{GlobalAlloc, Layout, System};
1+
use std::alloc::{GlobalAlloc, Layout};
22
use std::os::raw::c_void;
33
use std::sync::atomic::{AtomicBool, Ordering::SeqCst};
44

@@ -10,21 +10,12 @@ static USE_REDIS_ALLOC: AtomicBool = AtomicBool::new(false);
1010

1111
unsafe impl GlobalAlloc for RedisAlloc {
1212
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
13-
let use_redis = USE_REDIS_ALLOC.load(SeqCst);
14-
if use_redis {
15-
// complete the requested size to be aligned with the requested layout.align()
16-
let size = (layout.size() + layout.align() - 1) & (!(layout.align() - 1));
17-
return raw::RedisModule_Alloc.unwrap()(size) as *mut u8;
18-
}
19-
System.alloc(layout)
13+
let size = (layout.size() + layout.align() - 1) & (!(layout.align() - 1));
14+
return raw::RedisModule_Alloc.unwrap()(size) as *mut u8;
2015
}
2116

22-
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
23-
let use_redis = USE_REDIS_ALLOC.load(SeqCst);
24-
if use_redis {
25-
return raw::RedisModule_Free.unwrap()(ptr as *mut c_void);
26-
}
27-
System.dealloc(ptr, layout);
17+
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
18+
return raw::RedisModule_Free.unwrap()(ptr as *mut c_void);
2819
}
2920
}
3021

src/macros.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,19 +87,24 @@ macro_rules! redis_module {
8787
_argv: *mut *mut raw::RedisModuleString,
8888
_argc: c_int,
8989
) -> c_int {
90-
{
90+
let mut name_buffer = [0; 64];
91+
let mut dest = name_buffer.as_mut_ptr();
92+
for byte in $module_name.chars() {
93+
unsafe {
94+
*dest = byte as i8;
95+
dest = dest.add(1);
96+
}
97+
}
9198
// We use an explicit block here to make sure all memory allocated before we
9299
// switch to the Redis allocator will be out of scope and thus deallocated.
93-
let module_name = CString::new($module_name).unwrap();
94100
let module_version = $module_version as c_int;
95101

96102
if unsafe { raw::Export_RedisModule_Init(
97103
ctx,
98-
module_name.as_ptr(),
104+
name_buffer.as_ptr() as *const std::os::raw::c_char,
99105
module_version,
100106
raw::REDISMODULE_APIVER_1 as c_int,
101107
) } == raw::Status::Err as c_int { return raw::Status::Err as c_int; }
102-
}
103108

104109
if true {
105110
redis_module::alloc::use_redis_alloc();

0 commit comments

Comments
 (0)