@@ -2,34 +2,35 @@ pub use self::inner::*;
22
33#[ cfg( feature = "nightly" ) ]
44mod 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+ }
615}
716
817#[ cfg( not( feature = "nightly" ) ) ]
918mod inner {
1019 use crate :: alloc:: alloc:: { alloc, dealloc, Layout } ;
11- use core:: ptr;
1220 use core:: ptr:: NonNull ;
1321
1422 pub struct AllocError ;
1523
1624 pub unsafe trait AllocRef {
17- fn alloc ( & self , layout : Layout ) -> Result < NonNull < [ u8 ] > , AllocError > ;
25+ fn alloc ( & self , layout : Layout ) -> Result < NonNull < u8 > , AllocError > ;
1826 unsafe fn dealloc ( & self , ptr : NonNull < u8 > , layout : Layout ) ;
1927 }
2028
2129 #[ derive( Copy , Clone ) ]
2230 pub struct Global ;
2331 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 ) }
3334 }
3435 unsafe fn dealloc ( & self , ptr : NonNull < u8 > , layout : Layout ) {
3536 dealloc ( ptr. as_ptr ( ) , layout)
@@ -40,4 +41,8 @@ mod inner {
4041 Global
4142 }
4243 }
44+
45+ pub fn do_alloc < A : AllocRef > ( alloc : & A , layout : Layout ) -> Result < NonNull < u8 > , ( ) > {
46+ alloc. alloc ( layout) . map_err ( |_| ( ) )
47+ }
4348}
0 commit comments