File tree Expand file tree Collapse file tree 1 file changed +12
-5
lines changed
Expand file tree Collapse file tree 1 file changed +12
-5
lines changed Original file line number Diff line number Diff line change 33use libc;
44use std:: borrow:: Borrow ;
55use std:: borrow:: BorrowMut ;
6+ use std:: cmp;
7+ use std:: ffi:: CStr ;
68use std:: mem;
79use std:: ops:: Deref ;
810use std:: ops:: DerefMut ;
@@ -12,6 +14,7 @@ use std::ops::Range;
1214use std:: ops:: RangeFrom ;
1315use std:: ops:: RangeFull ;
1416use std:: ops:: RangeTo ;
17+ use std:: ptr;
1518use std:: slice;
1619
1720/// Fixed-length heap-allocated vector.
@@ -48,14 +51,18 @@ impl<T> Buffer<T> {
4851 pub unsafe fn new_uninitialized ( len : usize ) -> Self {
4952 let elem_size = mem:: size_of :: < T > ( ) ;
5053 let alloc_size = len * elem_size;
51- let align = mem:: align_of :: < T > ( ) ;
54+ let align = cmp:: max ( mem:: align_of :: < T > ( ) , mem:: size_of :: < * const libc:: c_void > ( ) ) ;
55+ // posix_memalign requires the alignment to be at least sizeof(void*).
5256 // TODO: Use alloc::heap::allocate once it's stable, or at least libc::aligned_alloc once it exists
53- let ptr = libc:: memalign ( align, alloc_size) as * mut T ;
54- if ptr. is_null ( ) {
55- panic ! ( "Failed to allocate. Out of memory?" ) ;
57+ let mut ptr = ptr:: null :: < libc:: c_void > ( ) as * mut libc:: c_void ;
58+ let err = libc:: posix_memalign ( & mut ptr, align, alloc_size) ;
59+ if err != 0 {
60+ let c_msg = libc:: strerror ( err) ;
61+ let msg = CStr :: from_ptr ( c_msg) ;
62+ panic ! ( "Failed to allocate: {}" , msg. to_str( ) . unwrap( ) ) ;
5663 }
5764 Buffer {
58- ptr : ptr,
65+ ptr : ptr as * mut T ,
5966 length : len,
6067 owned : true ,
6168 }
You can’t perform that action at this time.
0 commit comments