From e4027c7dace3da259632ac4a02c841aad539519b Mon Sep 17 00:00:00 2001 From: Marijn Suijten Date: Fri, 27 Aug 2021 00:51:13 +0200 Subject: [PATCH] ndk/native_window: Use `release`/`acquire` fns for `Drop` and `Clone` Much like ALooper and AHardwareBuffer the reference counter of ANativeWindow must be properly incremented on `Clone`, in turn allowing us to also `_release` the window as soon as it is dropped. --- ndk/CHANGELOG.md | 2 ++ ndk/src/native_window.rs | 23 ++++++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/ndk/CHANGELOG.md b/ndk/CHANGELOG.md index 0368edf8..2e4a0c00 100644 --- a/ndk/CHANGELOG.md +++ b/ndk/CHANGELOG.md @@ -1,5 +1,7 @@ # Unreleased +- ndk/native_window: Use `release`/`acquire` for `Drop` and `Clone` respectively + # 0.5.0 (2021-11-22) - **Breaking:** Replace `add_fd_with_callback` `ident` with constant value `ALOOPER_POLL_CALLBACK`, diff --git a/ndk/src/native_window.rs b/ndk/src/native_window.rs index 05de25cb..c3fc404a 100644 --- a/ndk/src/native_window.rs +++ b/ndk/src/native_window.rs @@ -1,7 +1,7 @@ -//! Bindings for `ANativeWindow` +//! Bindings for [`ffi::ANativeWindow`] use std::ptr::NonNull; -#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct NativeWindow { ptr: NonNull, } @@ -9,9 +9,26 @@ pub struct NativeWindow { unsafe impl Send for NativeWindow {} unsafe impl Sync for NativeWindow {} +impl Drop for NativeWindow { + fn drop(&mut self) { + unsafe { ffi::ANativeWindow_release(self.ptr.as_ptr()) } + } +} + +impl Clone for NativeWindow { + fn clone(&self) -> Self { + unsafe { + ffi::ANativeWindow_acquire(self.ptr.as_ptr()); + Self { ptr: self.ptr } + } + } +} + impl NativeWindow { + /// Takes ownership of `ptr` + /// /// # Safety - /// `ptr` must be a valid pointer to an Android `ANativeWindow`. + /// `ptr` must be a valid pointer to an Android [`ffi::ANativeWindow`]. pub unsafe fn from_ptr(ptr: NonNull) -> Self { Self { ptr } }