Skip to content

Commit 747cc74

Browse files
committed
Conversions between Result<*mut u8, AllocErr>> and *mut Void
1 parent c957e99 commit 747cc74

File tree

2 files changed

+24
-18
lines changed

2 files changed

+24
-18
lines changed

src/liballoc_system/lib.rs

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -139,22 +139,12 @@ macro_rules! alloc_methods_based_on_global_alloc {
139139
() => {
140140
#[inline]
141141
unsafe fn alloc(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
142-
let ptr = GlobalAlloc::alloc(*self, layout);
143-
if !ptr.is_null() {
144-
Ok(ptr as *mut u8)
145-
} else {
146-
Err(AllocErr)
147-
}
142+
GlobalAlloc::alloc(*self, layout).into()
148143
}
149144

150145
#[inline]
151146
unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<*mut u8, AllocErr> {
152-
let ptr = GlobalAlloc::alloc_zeroed(*self, layout);
153-
if !ptr.is_null() {
154-
Ok(ptr as *mut u8)
155-
} else {
156-
Err(AllocErr)
157-
}
147+
GlobalAlloc::alloc_zeroed(*self, layout).into()
158148
}
159149

160150
#[inline]
@@ -167,12 +157,7 @@ macro_rules! alloc_methods_based_on_global_alloc {
167157
ptr: *mut u8,
168158
old_layout: Layout,
169159
new_size: usize) -> Result<*mut u8, AllocErr> {
170-
let ptr = GlobalAlloc::realloc(*self, ptr as *mut Void, old_layout, new_size);
171-
if !ptr.is_null() {
172-
Ok(ptr as *mut u8)
173-
} else {
174-
Err(AllocErr)
175-
}
160+
GlobalAlloc::realloc(*self, ptr as *mut Void, old_layout, new_size).into()
176161
}
177162
}
178163
}

src/libcore/alloc.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,27 @@ impl Void {
4141
}
4242
}
4343

44+
/// Convert from a return value of GlobalAlloc::alloc to that of Alloc::alloc
45+
impl From<*mut Void> for Result<*mut u8, AllocErr> {
46+
fn from(ptr: *mut Void) -> Self {
47+
if !ptr.is_null() {
48+
Ok(ptr as *mut u8)
49+
} else {
50+
Err(AllocErr)
51+
}
52+
}
53+
}
54+
55+
/// Convert from a return value of Alloc::alloc to that of GlobalAlloc::alloc
56+
impl From<Result<*mut u8, AllocErr>> for *mut Void {
57+
fn from(result: Result<*mut u8, AllocErr>) -> Self {
58+
match result {
59+
Ok(ptr) => ptr as *mut Void,
60+
Err(_) => Void::null_mut(),
61+
}
62+
}
63+
}
64+
4465
/// Represents the combination of a starting address and
4566
/// a total capacity of the returned block.
4667
#[derive(Debug)]

0 commit comments

Comments
 (0)