From 9aae18d76454b01f07b177efafcc9867dfa7dff1 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Fri, 9 Aug 2019 22:41:26 +0200 Subject: fixes --- src/c/string.rs | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) (limited to 'src/c') diff --git a/src/c/string.rs b/src/c/string.rs index d0e620c..eef6371 100644 --- a/src/c/string.rs +++ b/src/c/string.rs @@ -2,8 +2,6 @@ use super::posix; use core::{mem, ptr, slice}; use core::ops::{Deref, DerefMut}; -const SENTINEL: *mut libc::c_void = 1 as *mut libc::c_void; - fn must_succeed(p: *mut T) -> *mut T { if p.is_null() { panic!("allocation failure"); @@ -13,17 +11,28 @@ fn must_succeed(p: *mut T) -> *mut T { fn malloc() -> *mut T { let size = mem::size_of::(); + let align = mem::align_of::(); if size == 0 { - return SENTINEL as *mut T; + return align as *mut T; } must_succeed( - unsafe {libc::memalign(mem::align_of::() as libc::size_t, size as libc::size_t) } - ) as *mut T + unsafe { + libc::memalign(align as libc::size_t, size as libc::size_t) as *mut T + } + ) } -pub struct CBox(*mut T); +pub struct CBox(*mut T); + +impl CBox { + pub fn new(value: T) -> CBox { + let p = malloc(); + unsafe { + ptr::write(p, value); + CBox::from_raw(p) + } + } -impl CBox { pub const unsafe fn from_raw(p: *mut T) -> CBox { CBox(p) } @@ -43,27 +52,18 @@ impl CBox { } } -impl CBox { - pub fn new(value: T) -> CBox { - let p = malloc(); - unsafe { - ptr::write(p, value); - CBox::from_raw(p) - } - } -} - -impl Drop for CBox { +impl Drop for CBox { fn drop(&mut self) { unsafe { ptr::drop_in_place(self.0); } - let p = self.0 as *mut libc::c_void; - if p != SENTINEL { - unsafe { libc::free(p); } + if mem::size_of::() != 0 { + unsafe { + libc::free(self.0 as *mut libc::c_void); + } } } } -impl Deref for CBox { +impl Deref for CBox { type Target = T; fn deref(&self) -> &T { @@ -71,7 +71,7 @@ impl Deref for CBox { } } -impl DerefMut for CBox { +impl DerefMut for CBox { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.0 } } -- cgit v1.2.3