@@ -2,34 +2,35 @@ pub use self::inner::*;
2
2
3
3
#[ cfg( feature = "nightly" ) ]
4
4
mod inner {
5
- pub use crate :: alloc:: alloc:: { AllocError , AllocRef , Global } ;
5
+ use crate :: alloc:: alloc:: Layout ;
6
+ pub use crate :: alloc:: alloc:: { AllocRef , Global } ;
7
+ use core:: ptr:: NonNull ;
8
+
9
+ pub fn do_alloc < A : AllocRef > ( alloc : & A , layout : Layout ) -> Result < NonNull < u8 > , ( ) > {
10
+ alloc
11
+ . alloc ( layout)
12
+ . map ( |ptr| ptr. as_non_null_ptr ( ) )
13
+ . map_err ( |_| ( ) )
14
+ }
6
15
}
7
16
8
17
#[ cfg( not( feature = "nightly" ) ) ]
9
18
mod inner {
10
19
use crate :: alloc:: alloc:: { alloc, dealloc, Layout } ;
11
- use core:: ptr;
12
20
use core:: ptr:: NonNull ;
13
21
14
22
pub struct AllocError ;
15
23
16
24
pub unsafe trait AllocRef {
17
- fn alloc ( & self , layout : Layout ) -> Result < NonNull < [ u8 ] > , AllocError > ;
25
+ fn alloc ( & self , layout : Layout ) -> Result < NonNull < u8 > , AllocError > ;
18
26
unsafe fn dealloc ( & self , ptr : NonNull < u8 > , layout : Layout ) ;
19
27
}
20
28
21
29
#[ derive( Copy , Clone ) ]
22
30
pub struct Global ;
23
31
unsafe impl AllocRef for Global {
24
- fn alloc ( & self , layout : Layout ) -> Result < NonNull < [ u8 ] > , AllocError > {
25
- unsafe {
26
- let ptr = alloc ( layout) ;
27
- if ptr. is_null ( ) {
28
- return Err ( AllocError ) ;
29
- }
30
- let slice = ptr:: slice_from_raw_parts_mut ( ptr, layout. size ( ) ) ;
31
- Ok ( NonNull :: new_unchecked ( slice) )
32
- }
32
+ fn alloc ( & self , layout : Layout ) -> Result < NonNull < u8 > , AllocError > {
33
+ unsafe { NonNull :: new ( alloc ( layout) ) . ok_or ( AllocError ) }
33
34
}
34
35
unsafe fn dealloc ( & self , ptr : NonNull < u8 > , layout : Layout ) {
35
36
dealloc ( ptr. as_ptr ( ) , layout)
@@ -40,4 +41,8 @@ mod inner {
40
41
Global
41
42
}
42
43
}
44
+
45
+ pub fn do_alloc < A : AllocRef > ( alloc : & A , layout : Layout ) -> Result < NonNull < u8 > , ( ) > {
46
+ alloc. alloc ( layout) . map_err ( |_| ( ) )
47
+ }
43
48
}
0 commit comments