Skip to content

Commit

Permalink
asset: Store a PhantomData lifetime inside AssetManager to repres…
Browse files Browse the repository at this point in the history
…ent missing ownership semantics
  • Loading branch information
MarijnS95 committed Sep 3, 2024
1 parent 29cc9e5 commit a93c680
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
17 changes: 11 additions & 6 deletions ndk/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,38 @@
use std::{
ffi::{CStr, CString},
io,
marker::PhantomData,
os::fd::{FromRawFd, OwnedFd},
ptr::NonNull,
};

/// A native [`AAssetManager *`]
///
/// [`AAssetManager *`]: https://developer.android.com/ndk/reference/group/asset#aassetmanager
#[derive(Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[doc(alias = "AAssetManager")]
pub struct AssetManager {
pub struct AssetManager<'a> {
ptr: NonNull<ffi::AAssetManager>,
_marker: PhantomData<&'a ()>,
}

// AAssetManager is thread safe.
// See https://developer.android.com/ndk/reference/group/asset#aassetmanager
unsafe impl Send for AssetManager {}
unsafe impl Sync for AssetManager {}
unsafe impl<'a> Send for AssetManager<'a> {}
unsafe impl<'a> Sync for AssetManager<'a> {}

impl AssetManager {
impl<'a> AssetManager<'a> {
/// Wraps a pointer to [`ffi::AssetManager`]
///
/// # Safety
/// `ptr` must be a valid pointer to an Android [`ffi::AAssetManager`]. The caller is
/// responsible for guaranteeing the lifetime of this pointer, and should drop the structure
/// _before_ the pointer becomes invalid.
pub unsafe fn from_ptr(ptr: NonNull<ffi::AAssetManager>) -> Self {
Self { ptr }
Self {
ptr,
_marker: PhantomData,
}
}

/// Returns the pointer to the native [`ffi::AAssetManager`].
Expand Down
2 changes: 1 addition & 1 deletion ndk/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Configuration {
self.ptr
}

pub fn from_asset_manager(am: &AssetManager) -> Self {
pub fn from_asset_manager(am: &AssetManager<'_>) -> Self {
let config = Self::new();
unsafe {
ffi::AConfiguration_fromAssetManager(config.ptr().as_mut(), am.ptr().as_mut());
Expand Down
4 changes: 3 additions & 1 deletion ndk/src/native_activity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ impl NativeActivity {
}

/// This app's asset manager, which can be used to access assets from the `.apk` file.
pub fn asset_manager(&self) -> crate::asset::AssetManager {
pub fn asset_manager(&self) -> crate::asset::AssetManager<'_> {
// SAFETY: Android initializes this field to a valid pointer, and the lifetime of the
// returned AssetManager is constrained to the lifetime of Self.
unsafe {
crate::asset::AssetManager::from_ptr(
NonNull::new(self.ptr.as_ref().assetManager).unwrap(),
Expand Down

0 comments on commit a93c680

Please sign in to comment.