Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
asset: Store a PhantomData lifetime inside AssetManager to repres…
Browse files Browse the repository at this point in the history
…ent missing ownership semantics
MarijnS95 committed May 21, 2024
1 parent 21ff97c commit 1df463e
Showing 3 changed files with 14 additions and 7 deletions.
15 changes: 10 additions & 5 deletions ndk/src/asset.rs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
use std::{
ffi::{CStr, CString},
io,
marker::PhantomData,
os::fd::{FromRawFd, OwnedFd},
ptr::NonNull,
};
@@ -16,24 +17,28 @@ use std::{
/// [`AAssetManager *`]: https://developer.android.com/ndk/reference/group/asset#aassetmanager
#[derive(Debug)]
#[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`].
2 changes: 1 addition & 1 deletion ndk/src/configuration.rs
Original file line number Diff line number Diff line change
@@ -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());
4 changes: 3 additions & 1 deletion ndk/src/native_activity.rs
Original file line number Diff line number Diff line change
@@ -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(),

0 comments on commit 1df463e

Please sign in to comment.