|
12 | 12 | // See the License for the specific language governing permissions and |
13 | 13 | // limitations under the License. |
14 | 14 |
|
| 15 | +use android_hardware_common::{ |
| 16 | + aidl::android::hardware::common::NativeHandle::NativeHandle as AidlNativeHandle, |
| 17 | + binder::ParcelFileDescriptor, |
| 18 | +}; |
15 | 19 | use std::{ |
16 | 20 | ffi::c_int, |
17 | 21 | mem::forget, |
@@ -190,6 +194,21 @@ impl Drop for NativeHandle { |
190 | 194 | } |
191 | 195 | } |
192 | 196 |
|
| 197 | +impl From<AidlNativeHandle> for NativeHandle { |
| 198 | + fn from(aidl_native_handle: AidlNativeHandle) -> Self { |
| 199 | + let fds = aidl_native_handle.fds.into_iter().map(OwnedFd::from).collect(); |
| 200 | + Self::new(fds, &aidl_native_handle.ints).unwrap() |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +impl From<NativeHandle> for AidlNativeHandle { |
| 205 | + fn from(native_handle: NativeHandle) -> Self { |
| 206 | + let ints = native_handle.ints().to_owned(); |
| 207 | + let fds = native_handle.into_fds().into_iter().map(ParcelFileDescriptor::new).collect(); |
| 208 | + Self { ints, fds } |
| 209 | + } |
| 210 | +} |
| 211 | + |
193 | 212 | // SAFETY: `NativeHandle` owns the `native_handle_t`, which just contains some integers and file |
194 | 213 | // descriptors, which aren't tied to any particular thread. |
195 | 214 | unsafe impl Send for NativeHandle {} |
@@ -240,4 +259,20 @@ mod test { |
240 | 259 |
|
241 | 260 | drop(cloned); |
242 | 261 | } |
| 262 | + |
| 263 | + #[test] |
| 264 | + fn to_from_aidl() { |
| 265 | + let file = File::open("/dev/null").unwrap(); |
| 266 | + let original = NativeHandle::new(vec![file.into()], &[42]).unwrap(); |
| 267 | + assert_eq!(original.ints(), &[42]); |
| 268 | + assert_eq!(original.fds().len(), 1); |
| 269 | + |
| 270 | + let aidl = AidlNativeHandle::from(original); |
| 271 | + assert_eq!(&aidl.ints, &[42]); |
| 272 | + assert_eq!(aidl.fds.len(), 1); |
| 273 | + |
| 274 | + let converted_back = NativeHandle::from(aidl); |
| 275 | + assert_eq!(converted_back.ints(), &[42]); |
| 276 | + assert_eq!(converted_back.fds().len(), 1); |
| 277 | + } |
243 | 278 | } |
0 commit comments