Skip to content

Commit

Permalink
mod c_{box,arc}: Make safe (#1275)
Browse files Browse the repository at this point in the history
Including #1239, this is the last of non-`neon` `unsafe` ops.
  • Loading branch information
kkysen authored Jul 1, 2024
2 parents 5cf49e0 + e19d07c commit e77f29b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
4 changes: 3 additions & 1 deletion src/c_arc.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![deny(unsafe_op_in_unsafe_fn)]

use crate::src::c_box::CBox;
use crate::src::error::Rav1dResult;
use std::marker::PhantomData;
Expand Down Expand Up @@ -212,7 +214,7 @@ impl<T: ?Sized> CArc<T> {
pub unsafe fn from_raw(raw: RawCArc<T>) -> Self {
// Safety: The [`RawCArc`] contains the output of [`Arc::into_raw`],
// so we can call [`Arc::from_raw`] on it.
let owner = raw.0.into_arc();
let owner = unsafe { raw.0.into_arc() };
owner.into()
}
}
Expand Down
15 changes: 13 additions & 2 deletions src/c_box.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![deny(unsafe_op_in_unsafe_fn)]

use std::ffi::c_void;
use std::marker::PhantomData;
use std::ops::Deref;
Expand All @@ -15,8 +17,15 @@ pub struct Free {
}

impl Free {
/// # Safety
///
/// `ptr` is a [`NonNull`]`<T>` and `free` deallocates it.
/// It must not be used after this call as it is deallocated.
pub unsafe fn free(&self, ptr: *mut c_void) {
(self.free)(ptr as *const u8, self.cookie)
// SAFETY: `self` came from `CBox::from_c`,
// which requires `self.free` to deallocate the `NonNull<T>` passed to it,
// and `self.cookie` to be passed to it, which it is.
unsafe { (self.free)(ptr as *const u8, self.cookie) }
}
}

Expand Down Expand Up @@ -85,7 +94,9 @@ impl<T: ?Sized> CBox<T> {
/// # Safety
///
/// `data` must be valid to dereference
/// until `free` is called on it, which must deallocate it.
/// until `free.free` is called on it, which must deallocate it.
/// `free.free` is always called with `free.cookie`,
/// which must be accessed thread-safely.
pub unsafe fn from_c(data: NonNull<T>, free: Free) -> Self {
Self::C {
data,
Expand Down

0 comments on commit e77f29b

Please sign in to comment.