Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mod c_{box,arc}: Make safe #1275

Merged
merged 4 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading