Add conversions between NativeHandle and AIDL NativeHandle.
Bug: 359100544
Test: atest libnativewindow_rs-internal_test
Change-Id: I5186d142fa6b1fb7810c05ab056ab0f609a47ae3
diff --git a/libs/nativewindow/rust/src/handle.rs b/libs/nativewindow/rust/src/handle.rs
index c41ab8d..ee70e3f 100644
--- a/libs/nativewindow/rust/src/handle.rs
+++ b/libs/nativewindow/rust/src/handle.rs
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use android_hardware_common::{
+ aidl::android::hardware::common::NativeHandle::NativeHandle as AidlNativeHandle,
+ binder::ParcelFileDescriptor,
+};
use std::{
ffi::c_int,
mem::forget,
@@ -190,6 +194,21 @@
}
}
+impl From<AidlNativeHandle> for NativeHandle {
+ fn from(aidl_native_handle: AidlNativeHandle) -> Self {
+ let fds = aidl_native_handle.fds.into_iter().map(OwnedFd::from).collect();
+ Self::new(fds, &aidl_native_handle.ints).unwrap()
+ }
+}
+
+impl From<NativeHandle> for AidlNativeHandle {
+ fn from(native_handle: NativeHandle) -> Self {
+ let ints = native_handle.ints().to_owned();
+ let fds = native_handle.into_fds().into_iter().map(ParcelFileDescriptor::new).collect();
+ Self { ints, fds }
+ }
+}
+
// SAFETY: `NativeHandle` owns the `native_handle_t`, which just contains some integers and file
// descriptors, which aren't tied to any particular thread.
unsafe impl Send for NativeHandle {}
@@ -240,4 +259,20 @@
drop(cloned);
}
+
+ #[test]
+ fn to_from_aidl() {
+ let file = File::open("/dev/null").unwrap();
+ let original = NativeHandle::new(vec![file.into()], &[42]).unwrap();
+ assert_eq!(original.ints(), &[42]);
+ assert_eq!(original.fds().len(), 1);
+
+ let aidl = AidlNativeHandle::from(original);
+ assert_eq!(&aidl.ints, &[42]);
+ assert_eq!(aidl.fds.len(), 1);
+
+ let converted_back = NativeHandle::from(aidl);
+ assert_eq!(converted_back.ints(), &[42]);
+ assert_eq!(converted_back.fds().len(), 1);
+ }
}