Skip to content

Commit 803f4d2

Browse files
committed
use cfg_select! to streamline allocation logic
1 parent 151bb4a commit 803f4d2

File tree

1 file changed

+36
-25
lines changed

1 file changed

+36
-25
lines changed

lib/common/allocations.rs

Lines changed: 36 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use core::ptr;
22

3+
use crate::cfg_select;
34
use crate::lib::zstd::ZSTD_customMem;
45

56
#[inline]
@@ -15,15 +16,20 @@ pub(crate) unsafe fn ZSTD_customMalloc(
1516
return f(customMem.opaque, size);
1617
}
1718

18-
#[allow(unreachable_code)]
19-
{
20-
#[cfg(feature = "rust-allocator")]
21-
return std::alloc::alloc(core::alloc::Layout::from_size_align_unchecked(size, 16)).cast();
22-
23-
#[cfg(feature = "c-allocator")]
24-
return libc::malloc(size);
19+
cfg_select! {
20+
feature = "rust-allocator" => {
21+
let layout = core::alloc::Layout::from_size_align_unchecked(size, 16);
22+
std::alloc::alloc(layout).cast()
23+
}
24+
feature = "c-allocator" => {
25+
libc::malloc(size)
26+
}
27+
_ => {
28+
panic!("no allocator specified");
29+
}
2530
}
2631
}
32+
2733
#[inline]
2834
pub(crate) unsafe fn ZSTD_customCalloc(
2935
size: usize,
@@ -39,16 +45,20 @@ pub(crate) unsafe fn ZSTD_customCalloc(
3945
return ptr;
4046
}
4147

42-
#[allow(unreachable_code)]
43-
{
44-
#[cfg(feature = "rust-allocator")]
45-
return std::alloc::alloc_zeroed(core::alloc::Layout::from_size_align_unchecked(size, 16))
46-
.cast();
47-
48-
#[cfg(feature = "c-allocator")]
49-
return libc::calloc(1, size);
48+
cfg_select! {
49+
feature = "rust-allocator" => {
50+
let layout = core::alloc::Layout::from_size_align_unchecked(size, 16);
51+
std::alloc::alloc_zeroed(layout).cast()
52+
}
53+
feature = "c-allocator" => {
54+
libc::calloc(1, size)
55+
}
56+
_ => {
57+
panic!("no allocator specified");
58+
}
5059
}
5160
}
61+
5262
#[inline]
5363
pub(crate) unsafe fn ZSTD_customFree(
5464
ptr: *mut core::ffi::c_void,
@@ -60,16 +70,17 @@ pub(crate) unsafe fn ZSTD_customFree(
6070
return f(customMem.opaque, ptr);
6171
}
6272

63-
#[allow(unreachable_code)]
64-
{
65-
#[cfg(feature = "rust-allocator")]
66-
return std::alloc::dealloc(
67-
ptr.cast(),
68-
core::alloc::Layout::from_size_align_unchecked(_size, 16),
69-
);
70-
71-
#[cfg(feature = "c-allocator")]
72-
return libc::free(ptr);
73+
cfg_select! {
74+
feature = "rust-allocator" => {
75+
let layout = core::alloc::Layout::from_size_align_unchecked(_size, 16);
76+
std::alloc::dealloc(ptr.cast(), layout)
77+
}
78+
feature = "c-allocator" => {
79+
libc::free(ptr);
80+
}
81+
_ => {
82+
panic!("no allocator specified");
83+
}
7384
}
7485
}
7586
}

0 commit comments

Comments
 (0)