• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //! Test Rust client for the AIDL compiler.
18 
19 use ::binder::{binder_impl::Parcel, Parcelable};
20 use aidl_test_fixedsizearray::aidl::android::aidl::fixedsizearray::FixedSizeArrayExample::{
21     FixedSizeArrayExample,
22     IRepeatFixedSizeArray::{BpRepeatFixedSizeArray, IRepeatFixedSizeArray},
23     IntParcelable::IntParcelable,
24 };
25 use aidl_test_interface::aidl::android::aidl::tests::nested::{
26     INestedService, ParcelableWithNested,
27 };
28 use aidl_test_interface::aidl::android::aidl::tests::unions::EnumUnion::EnumUnion;
29 use aidl_test_interface::aidl::android::aidl::tests::INewName::{self, BpNewName};
30 use aidl_test_interface::aidl::android::aidl::tests::IOldName::{self, BpOldName};
31 use aidl_test_interface::aidl::android::aidl::tests::ITestService::{
32     self, BpTestService, Empty::Empty, ITestServiceDefault, ITestServiceDefaultRef,
33 };
34 use aidl_test_interface::aidl::android::aidl::tests::{
35     extension::ExtendableParcelable::ExtendableParcelable, extension::MyExt::MyExt,
36     extension::MyExt2::MyExt2, extension::MyExtLike::MyExtLike, BackendType::BackendType,
37     ByteEnum::ByteEnum, IntEnum::IntEnum, LongEnum::LongEnum, RecursiveList::RecursiveList,
38     StructuredParcelable, Union,
39 };
40 use aidl_test_interface::binder::{self, BinderFeatures, IBinder, Interface};
41 use aidl_test_nonvintf_parcelable::aidl::android::aidl::tests::nonvintf::{
42     NonVintfExtendableParcelable::NonVintfExtendableParcelable,
43     NonVintfParcelable::NonVintfParcelable,
44 };
45 use aidl_test_unstable_parcelable::aidl::android::aidl::tests::unstable::{
46     UnstableExtendableParcelable::UnstableExtendableParcelable,
47     UnstableParcelable::UnstableParcelable,
48 };
49 use aidl_test_versioned_interface::aidl::android::aidl::versioned::tests::{
50     BazUnion::BazUnion, Foo::Foo, IFooInterface, IFooInterface::BpFooInterface,
51 };
52 use aidl_test_vintf_parcelable::aidl::android::aidl::tests::vintf::{
53     VintfExtendableParcelable::VintfExtendableParcelable, VintfParcelable::VintfParcelable,
54 };
55 use std::fs::File;
56 use std::io::{Read, Write};
57 use std::os::unix::io::FromRawFd;
58 use std::sync::{Arc, Mutex};
59 
get_test_service() -> binder::Strong<dyn ITestService::ITestService>60 fn get_test_service() -> binder::Strong<dyn ITestService::ITestService> {
61     binder::get_interface(<BpTestService as ITestService::ITestService>::get_descriptor())
62         .expect("did not get binder service")
63 }
64 
65 #[test]
test_constants()66 fn test_constants() {
67     assert_eq!(ITestService::A1, 1);
68     assert_eq!(ITestService::A2, 1);
69     assert_eq!(ITestService::A3, 1);
70     assert_eq!(ITestService::A4, 1);
71     assert_eq!(ITestService::A5, 1);
72     assert_eq!(ITestService::A6, 1);
73     assert_eq!(ITestService::A7, 1);
74     assert_eq!(ITestService::A8, 1);
75     assert_eq!(ITestService::A9, 1);
76     assert_eq!(ITestService::A10, 1);
77     assert_eq!(ITestService::A11, 1);
78     assert_eq!(ITestService::A12, 1);
79     assert_eq!(ITestService::A13, 1);
80     assert_eq!(ITestService::A14, 1);
81     assert_eq!(ITestService::A15, 1);
82     assert_eq!(ITestService::A16, 1);
83     assert_eq!(ITestService::A17, 1);
84     assert_eq!(ITestService::A18, 1);
85     assert_eq!(ITestService::A19, 1);
86     assert_eq!(ITestService::A20, 1);
87     assert_eq!(ITestService::A21, 1);
88     assert_eq!(ITestService::A22, 1);
89     assert_eq!(ITestService::A23, 1);
90     assert_eq!(ITestService::A24, 1);
91     assert_eq!(ITestService::A25, 1);
92     assert_eq!(ITestService::A26, 1);
93     assert_eq!(ITestService::A27, 1);
94     assert_eq!(ITestService::A28, 1);
95     assert_eq!(ITestService::A29, 1);
96     assert_eq!(ITestService::A30, 1);
97     assert_eq!(ITestService::A31, 1);
98     assert_eq!(ITestService::A32, 1);
99     assert_eq!(ITestService::A33, 1);
100     assert_eq!(ITestService::A34, 1);
101     assert_eq!(ITestService::A35, 1);
102     assert_eq!(ITestService::A36, 1);
103     assert_eq!(ITestService::A37, 1);
104     assert_eq!(ITestService::A38, 1);
105     assert_eq!(ITestService::A39, 1);
106     assert_eq!(ITestService::A40, 1);
107     assert_eq!(ITestService::A41, 1);
108     assert_eq!(ITestService::A42, 1);
109     assert_eq!(ITestService::A43, 1);
110     assert_eq!(ITestService::A44, 1);
111     assert_eq!(ITestService::A45, 1);
112     assert_eq!(ITestService::A46, 1);
113     assert_eq!(ITestService::A47, 1);
114     assert_eq!(ITestService::A48, 1);
115     assert_eq!(ITestService::A49, 1);
116     assert_eq!(ITestService::A50, 1);
117     assert_eq!(ITestService::A51, 1);
118     assert_eq!(ITestService::A52, 1);
119     assert_eq!(ITestService::A53, 1);
120     assert_eq!(ITestService::A54, 1);
121     assert_eq!(ITestService::A55, 1);
122     assert_eq!(ITestService::A56, 1);
123     assert_eq!(ITestService::A57, 1);
124     assert_eq!(ITestService::FLOAT_TEST_CONSTANT4, 2.2_f32);
125     assert_eq!(ITestService::FLOAT_TEST_CONSTANT5, -2.2_f32);
126     assert_eq!(ITestService::DOUBLE_TEST_CONSTANT4, 2.2_f64);
127     assert_eq!(ITestService::DOUBLE_TEST_CONSTANT5, -2.2_f64);
128 }
129 
130 #[test]
test_oneway()131 fn test_oneway() {
132     let result = get_test_service().TestOneway();
133     assert_eq!(result, Ok(()));
134 }
135 
136 macro_rules! test_primitive {
137     ($test:ident, $func:ident, $value:expr) => {
138         #[test]
139         fn $test() {
140             let value = $value;
141             let result = get_test_service().$func(value);
142             assert_eq!(result, Ok(value));
143         }
144     };
145 }
146 
147 test_primitive! {test_primitive_bool_false, RepeatBoolean, false}
148 test_primitive! {test_primitive_bool_true, RepeatBoolean, true}
149 test_primitive! {test_primitive_byte, RepeatByte, -128i8}
150 test_primitive! {test_primitive_char, RepeatChar, 'A' as u16}
151 test_primitive! {test_primitive_int, RepeatInt, 1i32 << 30}
152 test_primitive! {test_primitive_long, RepeatLong, 1i64 << 60}
153 test_primitive! {test_primitive_float, RepeatFloat, 1.0f32 / 3.0f32}
154 test_primitive! {test_primitive_double, RepeatDouble, 1.0f64 / 3.0f64}
155 test_primitive! {test_primitive_byte_constant, RepeatByte, ITestService::BYTE_TEST_CONSTANT}
156 test_primitive! {test_primitive_constant1, RepeatInt, ITestService::TEST_CONSTANT}
157 test_primitive! {test_primitive_constant2, RepeatInt, ITestService::TEST_CONSTANT2}
158 test_primitive! {test_primitive_constant3, RepeatInt, ITestService::TEST_CONSTANT3}
159 test_primitive! {test_primitive_constant4, RepeatInt, ITestService::TEST_CONSTANT4}
160 test_primitive! {test_primitive_constant5, RepeatInt, ITestService::TEST_CONSTANT5}
161 test_primitive! {test_primitive_constant6, RepeatInt, ITestService::TEST_CONSTANT6}
162 test_primitive! {test_primitive_constant7, RepeatInt, ITestService::TEST_CONSTANT7}
163 test_primitive! {test_primitive_constant8, RepeatInt, ITestService::TEST_CONSTANT8}
164 test_primitive! {test_primitive_constant9, RepeatInt, ITestService::TEST_CONSTANT9}
165 test_primitive! {test_primitive_constant10, RepeatInt, ITestService::TEST_CONSTANT10}
166 test_primitive! {test_primitive_constant11, RepeatInt, ITestService::TEST_CONSTANT11}
167 test_primitive! {test_primitive_constant12, RepeatInt, ITestService::TEST_CONSTANT12}
168 test_primitive! {test_primitive_long_constant, RepeatLong, ITestService::LONG_TEST_CONSTANT}
169 test_primitive! {test_primitive_byte_enum, RepeatByteEnum, ByteEnum::FOO}
170 test_primitive! {test_primitive_int_enum, RepeatIntEnum, IntEnum::BAR}
171 test_primitive! {test_primitive_long_enum, RepeatLongEnum, LongEnum::FOO}
172 test_primitive! {test_primitive_float_constant, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT}
173 test_primitive! {test_primitive_float_constant2, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT2}
174 test_primitive! {test_primitive_float_constant3, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT3}
175 test_primitive! {test_primitive_float_constant4, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT4}
176 test_primitive! {test_primitive_float_constant5, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT5}
177 test_primitive! {test_primitive_float_constant6, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT6}
178 test_primitive! {test_primitive_float_constant7, RepeatFloat, ITestService::FLOAT_TEST_CONSTANT7}
179 test_primitive! {test_primitive_double_constant, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT}
180 test_primitive! {test_primitive_double_constant2, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT2}
181 test_primitive! {test_primitive_double_constant3, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT3}
182 test_primitive! {test_primitive_double_constant4, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT4}
183 test_primitive! {test_primitive_double_constant5, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT5}
184 test_primitive! {test_primitive_double_constant6, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT6}
185 test_primitive! {test_primitive_double_constant7, RepeatDouble, ITestService::DOUBLE_TEST_CONSTANT7}
186 
187 #[test]
test_repeat_string()188 fn test_repeat_string() {
189     let service = get_test_service();
190     let inputs = [
191         "typical string".into(),
192         String::new(),
193         "\0\0".into(),
194         // This is actually two unicode code points:
195         //   U+10437: The 'small letter yee' character in the deseret alphabet
196         //   U+20AC: A euro sign
197         String::from_utf16(&[0xD801, 0xDC37, 0x20AC]).expect("error converting string"),
198         ITestService::STRING_TEST_CONSTANT.into(),
199         ITestService::STRING_TEST_CONSTANT2.into(),
200     ];
201     for input in &inputs {
202         let result = service.RepeatString(input);
203         assert_eq!(result.as_ref(), Ok(input));
204     }
205 }
206 
207 macro_rules! test_reverse_array {
208     ($test:ident, $func:ident, $array:expr) => {
209         #[test]
210         fn $test() {
211             let mut array = $array.to_vec();
212 
213             // Java needs initial values here (can't resize arrays)
214             let mut repeated = vec![Default::default(); array.len()];
215 
216             let result = get_test_service().$func(&array, &mut repeated);
217             assert_eq!(repeated, array);
218             array.reverse();
219             assert_eq!(result, Ok(array));
220         }
221     };
222 }
223 
224 test_reverse_array! {test_array_boolean, ReverseBoolean, vec![true, false, false]}
225 test_reverse_array! {test_array_byte, ReverseByte, vec![255u8, 0u8, 127u8]}
226 test_reverse_array! {
227     service,
228     ReverseChar,
229     vec!['A' as u16, 'B' as u16, 'C' as u16]
230 }
231 test_reverse_array! {test_array_int, ReverseInt, vec![1, 2, 3]}
232 test_reverse_array! {test_array_long, ReverseLong, vec![-1i64, 0i64, 1i64 << 60]}
233 test_reverse_array! {test_array_float, ReverseFloat, vec![-0.3f32, -0.7f32, 8.0f32]}
234 test_reverse_array! {
235     test_array_double,
236     ReverseDouble,
237     vec![1.0f64 / 3.0f64, 1.0f64 / 7.0f64, 42.0f64]
238 }
239 test_reverse_array! {
240     test_array_string,
241     ReverseString,
242     vec!["f".into(), "a".into(), "b".into()]
243 }
244 test_reverse_array! {
245     test_array_byte_enum,
246     ReverseByteEnum,
247     vec![ByteEnum::FOO, ByteEnum::BAR, ByteEnum::BAR]
248 }
249 test_reverse_array! {
250     test_array_byte_enum_values,
251     ReverseByteEnum,
252     ByteEnum::enum_values()
253 }
254 test_reverse_array! {
255     test_array_byte_enum_v2,
256     ReverseByteEnum,
257     vec![ByteEnum::FOO, ByteEnum::BAR, ByteEnum::BAZ]
258 }
259 test_reverse_array! {
260     test_array_int_enum,
261     ReverseIntEnum,
262     vec![IntEnum::FOO, IntEnum::BAR, IntEnum::BAR]
263 }
264 test_reverse_array! {
265     test_array_long_enum,
266     ReverseLongEnum,
267     vec![LongEnum::FOO, LongEnum::BAR, LongEnum::BAR]
268 }
269 test_reverse_array! {
270     test_array_string_list,
271     ReverseStringList,
272     vec!["f".into(), "a".into(), "b".into()]
273 }
274 test_reverse_array! {
275     test_array_utf8_string,
276     ReverseUtf8CppString,
277     vec![
278         "a".into(),
279         String::new(),
280         std::str::from_utf8(&[0xC3, 0xB8])
281             .expect("error converting string")
282             .into(),
283     ]
284 }
285 
286 #[test]
test_binder_exchange()287 fn test_binder_exchange() {
288     const NAME: &str = "Smythe";
289     let service = get_test_service();
290     let got = service.GetOtherTestService(NAME).expect("error calling GetOtherTestService");
291     assert_eq!(got.GetName().as_ref().map(String::as_ref), Ok(NAME));
292     assert_eq!(service.VerifyName(&got, NAME), Ok(true));
293 }
294 
295 #[test]
test_binder_array_exchange()296 fn test_binder_array_exchange() {
297     let names = vec!["Fizz".into(), "Buzz".into()];
298     let service = get_test_service();
299     let got = service.GetInterfaceArray(&names).expect("error calling GetInterfaceArray");
300     assert_eq!(got.iter().map(|s| s.GetName()).collect::<Result<Vec<_>, _>>(), Ok(names.clone()));
301     assert_eq!(service.VerifyNamesWithInterfaceArray(&got, &names), Ok(true));
302 }
303 
304 #[test]
test_binder_nullable_array_exchange()305 fn test_binder_nullable_array_exchange() {
306     let names = vec![Some("Fizz".into()), None, Some("Buzz".into())];
307     let service = get_test_service();
308     let got = service
309         .GetNullableInterfaceArray(Some(&names))
310         .expect("error calling GetNullableInterfaceArray");
311     assert_eq!(
312         got.as_ref().map(|arr| arr
313             .iter()
314             .map(|opt_s| opt_s.as_ref().map(|s| s.GetName().expect("error calling GetName")))
315             .collect::<Vec<_>>()),
316         Some(names.clone())
317     );
318     assert_eq!(
319         service.VerifyNamesWithNullableInterfaceArray(got.as_ref().map(|v| &v[..]), Some(&names)),
320         Ok(true)
321     );
322 }
323 
324 #[test]
test_interface_list_exchange()325 fn test_interface_list_exchange() {
326     let names = vec![Some("Fizz".into()), None, Some("Buzz".into())];
327     let service = get_test_service();
328     let got = service.GetInterfaceList(Some(&names)).expect("error calling GetInterfaceList");
329     assert_eq!(
330         got.as_ref().map(|arr| arr
331             .iter()
332             .map(|opt_s| opt_s.as_ref().map(|s| s.GetName().expect("error calling GetName")))
333             .collect::<Vec<_>>()),
334         Some(names.clone())
335     );
336     assert_eq!(
337         service.VerifyNamesWithInterfaceList(got.as_ref().map(|v| &v[..]), Some(&names)),
338         Ok(true)
339     );
340 }
341 
build_pipe() -> (File, File)342 fn build_pipe() -> (File, File) {
343     // Safety: we get two file descriptors from pipe()
344     // and pass them after checking if the function returned
345     // without an error, so the descriptors should be valid
346     // by that point
347     unsafe {
348         let mut fds = [0, 0];
349         if libc::pipe(fds.as_mut_ptr()) != 0 {
350             panic!("pipe() error");
351         }
352         (File::from_raw_fd(fds[0]), File::from_raw_fd(fds[1]))
353     }
354 }
355 
356 #[test]
test_parcel_file_descriptor()357 fn test_parcel_file_descriptor() {
358     let service = get_test_service();
359     let (mut read_file, write_file) = build_pipe();
360 
361     let write_pfd = binder::ParcelFileDescriptor::new(write_file);
362     let result_pfd = service
363         .RepeatParcelFileDescriptor(&write_pfd)
364         .expect("error calling RepeatParcelFileDescriptor");
365 
366     const TEST_DATA: &[u8] = b"FrazzleSnazzleFlimFlamFlibbityGumboChops";
367     result_pfd.as_ref().write_all(TEST_DATA).expect("error writing to pipe");
368 
369     let mut buf = [0u8; TEST_DATA.len()];
370     read_file.read_exact(&mut buf).expect("error reading from pipe");
371     assert_eq!(&buf[..], TEST_DATA);
372 }
373 
374 #[test]
test_parcel_file_descriptor_array()375 fn test_parcel_file_descriptor_array() {
376     let service = get_test_service();
377 
378     let (read_file, write_file) = build_pipe();
379     let input = vec![
380         binder::ParcelFileDescriptor::new(read_file),
381         binder::ParcelFileDescriptor::new(write_file),
382     ];
383 
384     let mut repeated = vec![];
385 
386     let backend = service.getBackendType().expect("error getting backend type");
387     if backend == BackendType::JAVA {
388         // Java needs initial values here (can't resize arrays)
389         // Other backends can't accept 'None', but we can use it in Java for convenience, rather
390         // than creating file descriptors.
391         repeated = vec![None, None];
392     }
393 
394     let result = service
395         .ReverseParcelFileDescriptorArray(&input[..], &mut repeated)
396         .expect("error calling ReverseParcelFileDescriptorArray");
397 
398     input[1].as_ref().write_all(b"First").expect("error writing to pipe");
399     repeated[1]
400         .as_mut()
401         .expect("received None for ParcelFileDescriptor")
402         .as_ref()
403         .write_all(b"Second")
404         .expect("error writing to pipe");
405     result[0].as_ref().write_all(b"Third").expect("error writing to pipe");
406 
407     const TEST_DATA: &[u8] = b"FirstSecondThird";
408     let mut buf = [0u8; TEST_DATA.len()];
409     input[0].as_ref().read_exact(&mut buf).expect("error reading from pipe");
410     assert_eq!(&buf[..], TEST_DATA);
411 }
412 
413 #[test]
test_service_specific_exception()414 fn test_service_specific_exception() {
415     let service = get_test_service();
416 
417     for i in -1..2 {
418         let result = service.ThrowServiceException(i);
419         assert!(result.is_err());
420 
421         let status = result.unwrap_err();
422         assert_eq!(status.exception_code(), binder::ExceptionCode::SERVICE_SPECIFIC);
423         assert_eq!(status.service_specific_error(), i);
424     }
425 }
426 
427 macro_rules! test_nullable {
428     ($test:ident, $func:ident, $value:expr) => {
429         #[test]
430         fn $test() {
431             let service = get_test_service();
432             let value = Some($value);
433             let result = service.$func(value.as_deref());
434             assert_eq!(result, Ok(value));
435 
436             let result = service.$func(None);
437             assert_eq!(result, Ok(None));
438         }
439     };
440 }
441 
442 test_nullable! {test_nullable_array_int, RepeatNullableIntArray, vec![1, 2, 3]}
443 test_nullable! {
444     test_nullable_array_byte_enum,
445     RepeatNullableByteEnumArray,
446     vec![ByteEnum::FOO, ByteEnum::BAR]
447 }
448 test_nullable! {
449     test_nullable_array_int_enum,
450     RepeatNullableIntEnumArray,
451     vec![IntEnum::FOO, IntEnum::BAR]
452 }
453 test_nullable! {
454     test_nullable_array_long_enum,
455     RepeatNullableLongEnumArray,
456     vec![LongEnum::FOO, LongEnum::BAR]
457 }
458 test_nullable! {test_nullable_string, RepeatNullableString, "Blooob".into()}
459 test_nullable! {
460     test_nullable_string_list,
461     RepeatNullableStringList,
462     vec![
463         Some("Wat".into()),
464         Some("Blooob".into()),
465         Some("Wat".into()),
466         None,
467         Some("YEAH".into()),
468         Some("OKAAAAY".into()),
469     ]
470 }
471 
472 #[test]
test_nullable_parcelable()473 fn test_nullable_parcelable() {
474     let value = Empty {};
475 
476     let service = get_test_service();
477     let value = Some(value);
478     let result = service.RepeatNullableParcelable(value.as_ref());
479     assert_eq!(result, Ok(value));
480 
481     let result = service.RepeatNullableParcelable(None);
482     assert_eq!(result, Ok(None));
483 }
484 
485 test_nullable! {
486     test_nullable_parcelable_array,
487     RepeatNullableParcelableArray,
488     vec![
489         Some(Empty {}),
490         None,
491     ]
492 }
493 
494 test_nullable! {
495     test_nullable_parcelable_list,
496     RepeatNullableParcelableList,
497     vec![
498         Some(Empty {}),
499         None,
500     ]
501 }
502 
503 #[test]
test_binder()504 fn test_binder() {
505     let service = get_test_service();
506     assert!(service.GetCallback(true).expect("error calling GetCallback").is_none());
507     let callback = service
508         .GetCallback(false)
509         .expect("error calling GetCallback")
510         .expect("expected Some from GetCallback");
511 
512     // We don't have any place to get a fresh `SpIBinder`, so we
513     // reuse the interface for the binder tests
514     let binder = callback.as_binder();
515     assert_eq!(service.TakesAnIBinder(&binder), Ok(()));
516     assert_eq!(service.TakesANullableIBinder(None), Ok(()));
517     assert_eq!(service.TakesANullableIBinder(Some(&binder)), Ok(()));
518 }
519 
520 macro_rules! test_reverse_null_array {
521     ($service:expr, $func:ident, $expect_repeated:expr) => {{
522         let mut repeated = None;
523         let result = $service.$func(None, &mut repeated);
524         assert_eq!(repeated, $expect_repeated);
525         assert_eq!(result, Ok(None));
526     }};
527 }
528 
529 macro_rules! test_reverse_nullable_array {
530     ($service:expr, $func:ident, $array:expr) => {{
531         let mut array = $array;
532         // Java needs initial values here (can't resize arrays)
533         let mut repeated = Some(vec![Default::default(); array.len()]);
534         let result = $service.$func(Some(&array[..]), &mut repeated);
535         assert_eq!(repeated.as_ref(), Some(&array));
536         array.reverse();
537         assert_eq!(result, Ok(Some(array)));
538     }};
539 }
540 
541 #[test]
test_utf8_string()542 fn test_utf8_string() {
543     let service = get_test_service();
544     let inputs = [
545         "typical string",
546         "",
547         "\0\0",
548         std::str::from_utf8(&[0xF0, 0x90, 0x90, 0xB7, 0xE2, 0x82, 0xAC])
549             .expect("error converting string"),
550         ITestService::STRING_TEST_CONSTANT_UTF8,
551     ];
552     for input in &inputs {
553         let result = service.RepeatUtf8CppString(input);
554         assert_eq!(result.as_ref().map(String::as_str), Ok(*input));
555 
556         let result = service.RepeatNullableUtf8CppString(Some(input));
557         assert_eq!(result.as_ref().map(Option::as_deref), Ok(Some(*input)));
558     }
559 
560     let result = service.RepeatNullableUtf8CppString(None);
561     assert_eq!(result, Ok(None));
562 
563     let inputs = vec![
564         Some("typical string".into()),
565         Some(String::new()),
566         None,
567         Some(
568             std::str::from_utf8(&[0xF0, 0x90, 0x90, 0xB7, 0xE2, 0x82, 0xAC])
569                 .expect("error converting string")
570                 .into(),
571         ),
572         Some(ITestService::STRING_TEST_CONSTANT_UTF8.into()),
573     ];
574 
575     // Java can't return a null list as a parameter
576     let backend = service.getBackendType().expect("error getting backend type");
577     let null_output = if backend == BackendType::JAVA { Some(vec![]) } else { None };
578     test_reverse_null_array!(service, ReverseUtf8CppStringList, null_output);
579 
580     test_reverse_null_array!(service, ReverseNullableUtf8CppString, None);
581 
582     test_reverse_nullable_array!(service, ReverseUtf8CppStringList, inputs.clone());
583     test_reverse_nullable_array!(service, ReverseNullableUtf8CppString, inputs);
584 }
585 
586 #[allow(clippy::approx_constant)]
587 #[allow(clippy::float_cmp)]
588 #[test]
test_parcelable()589 fn test_parcelable() {
590     let service = get_test_service();
591     let mut parcelable = StructuredParcelable::StructuredParcelable::default();
592 
593     const DESIRED_VALUE: i32 = 23;
594     parcelable.f = DESIRED_VALUE;
595 
596     assert_eq!(parcelable.stringDefaultsToFoo, "foo");
597     assert_eq!(parcelable.byteDefaultsToFour, 4);
598     assert_eq!(parcelable.intDefaultsToFive, 5);
599     assert_eq!(parcelable.longDefaultsToNegativeSeven, -7);
600     assert!(parcelable.booleanDefaultsToTrue);
601     assert_eq!(parcelable.charDefaultsToC, 'C' as u16);
602     assert_eq!(parcelable.floatDefaultsToPi, 3.14f32);
603     assert_eq!(parcelable.doubleWithDefault, -3.14e17f64);
604     assert!(!parcelable.boolDefault);
605     assert_eq!(parcelable.byteDefault, 0);
606     assert_eq!(parcelable.intDefault, 0);
607     assert_eq!(parcelable.longDefault, 0);
608     assert_eq!(parcelable.floatDefault, 0.0f32);
609     assert_eq!(parcelable.doubleDefault, 0.0f64);
610     assert_eq!(parcelable.arrayDefaultsTo123, &[1, 2, 3]);
611     assert!(parcelable.arrayDefaultsToEmpty.is_empty());
612 
613     let result = service.FillOutStructuredParcelable(&mut parcelable);
614     assert_eq!(result, Ok(()));
615 
616     assert_eq!(parcelable.shouldContainThreeFs, [DESIRED_VALUE, DESIRED_VALUE, DESIRED_VALUE]);
617     assert_eq!(parcelable.shouldBeJerry, "Jerry");
618     assert_eq!(parcelable.int32_min, i32::MIN);
619     assert_eq!(parcelable.int32_max, i32::MAX);
620     assert_eq!(parcelable.int64_max, i64::MAX);
621     assert_eq!(parcelable.hexInt32_neg_1, -1);
622     for i in parcelable.int8_1 {
623         assert_eq!(i, 1);
624     }
625     for i in parcelable.int32_1 {
626         assert_eq!(i, 1);
627     }
628     for i in parcelable.int64_1 {
629         assert_eq!(i, 1);
630     }
631     assert_eq!(parcelable.hexInt32_pos_1, 1);
632     assert_eq!(parcelable.hexInt64_pos_1, 1);
633     assert_eq!(parcelable.const_exprs_1.0, 1);
634     assert_eq!(parcelable.const_exprs_2.0, 1);
635     assert_eq!(parcelable.const_exprs_3.0, 1);
636     assert_eq!(parcelable.const_exprs_4.0, 1);
637     assert_eq!(parcelable.const_exprs_5.0, 1);
638     assert_eq!(parcelable.const_exprs_6.0, 1);
639     assert_eq!(parcelable.const_exprs_7.0, 1);
640     assert_eq!(parcelable.const_exprs_8.0, 1);
641     assert_eq!(parcelable.const_exprs_9.0, 1);
642     assert_eq!(parcelable.const_exprs_10.0, 1);
643     assert_eq!(parcelable.addString1, "hello world!");
644     assert_eq!(parcelable.addString2, "The quick brown fox jumps over the lazy dog.");
645 
646     assert_eq!(
647         parcelable.shouldSetBit0AndBit2,
648         StructuredParcelable::BIT0 | StructuredParcelable::BIT2
649     );
650 
651     assert_eq!(parcelable.u, Some(Union::Union::Ns(vec![1, 2, 3])));
652     assert_eq!(parcelable.shouldBeConstS1, Some(Union::Union::S(Union::S1.to_string())))
653 }
654 
655 #[test]
test_repeat_extendable_parcelable()656 fn test_repeat_extendable_parcelable() {
657     let service = get_test_service();
658 
659     let ext = Arc::new(MyExt { a: 42, b: "EXT".into() });
660     let mut ep = ExtendableParcelable { a: 1, b: "a".into(), c: 42, ..Default::default() };
661     ep.ext.set_parcelable(Arc::clone(&ext)).expect("error setting parcelable");
662 
663     let mut ep2 = ExtendableParcelable::default();
664     let result = service.RepeatExtendableParcelable(&ep, &mut ep2);
665     assert_eq!(result, Ok(()));
666     assert_eq!(ep2.a, ep.a);
667     assert_eq!(ep2.b, ep.b);
668 
669     let ret_ext = ep2.ext.get_parcelable::<MyExt>().expect("error getting parcelable");
670     assert!(ret_ext.is_some());
671 
672     let ret_ext = ret_ext.unwrap();
673     assert_eq!(ret_ext.a, ext.a);
674     assert_eq!(ret_ext.b, ext.b);
675 }
676 
677 macro_rules! test_parcelable_holder_stability {
678     ($test:ident, $holder:path, $parcelable:path) => {
679         #[test]
680         fn $test() {
681             let mut holder = <$holder>::default();
682             let parcelable = Arc::new(<$parcelable>::default());
683             let result = holder.ext.set_parcelable(Arc::clone(&parcelable));
684             assert_eq!(result, Ok(()));
685 
686             let parcelable2 = holder.ext.get_parcelable::<$parcelable>().unwrap().unwrap();
687             assert!(Arc::ptr_eq(&parcelable, &parcelable2));
688         }
689     };
690 }
691 
692 test_parcelable_holder_stability! {
693     test_vintf_parcelable_holder_can_contain_vintf_parcelable,
694     VintfExtendableParcelable,
695     VintfParcelable
696 }
697 test_parcelable_holder_stability! {
698     test_stable_parcelable_holder_can_contain_vintf_parcelable,
699     NonVintfExtendableParcelable,
700     VintfParcelable
701 }
702 test_parcelable_holder_stability! {
703     test_stable_parcelable_holder_can_contain_non_vintf_parcelable,
704     NonVintfExtendableParcelable,
705     NonVintfParcelable
706 }
707 test_parcelable_holder_stability! {
708     test_stable_parcelable_holder_can_contain_unstable_parcelable,
709     NonVintfExtendableParcelable,
710     UnstableParcelable
711 }
712 test_parcelable_holder_stability! {
713     test_unstable_parcelable_holder_can_contain_vintf_parcelable,
714     UnstableExtendableParcelable,
715     VintfParcelable
716 }
717 test_parcelable_holder_stability! {
718     test_unstable_parcelable_holder_can_contain_non_vintf_parcelable,
719     UnstableExtendableParcelable,
720     NonVintfParcelable
721 }
722 test_parcelable_holder_stability! {
723     test_unstable_parcelable_holder_can_contain_unstable_parcelable,
724     UnstableExtendableParcelable,
725     UnstableParcelable
726 }
727 
728 #[test]
test_vintf_parcelable_holder_cannot_contain_not_vintf_parcelable()729 fn test_vintf_parcelable_holder_cannot_contain_not_vintf_parcelable() {
730     let mut holder = VintfExtendableParcelable::default();
731     let parcelable = Arc::new(NonVintfParcelable::default());
732     let result = holder.ext.set_parcelable(Arc::clone(&parcelable));
733     assert_eq!(result, Err(binder::StatusCode::BAD_VALUE));
734 
735     let parcelable2 = holder.ext.get_parcelable::<NonVintfParcelable>();
736     assert!(parcelable2.unwrap().is_none());
737 }
738 
739 #[test]
test_vintf_parcelable_holder_cannot_contain_unstable_parcelable()740 fn test_vintf_parcelable_holder_cannot_contain_unstable_parcelable() {
741     let mut holder = VintfExtendableParcelable::default();
742     let parcelable = Arc::new(UnstableParcelable::default());
743     let result = holder.ext.set_parcelable(Arc::clone(&parcelable));
744     assert_eq!(result, Err(binder::StatusCode::BAD_VALUE));
745 
746     let parcelable2 = holder.ext.get_parcelable::<UnstableParcelable>();
747     assert!(parcelable2.unwrap().is_none());
748 }
749 
750 #[test]
test_read_write_extension()751 fn test_read_write_extension() {
752     let ext = Arc::new(MyExt { a: 42, b: "EXT".into() });
753     let ext2 = Arc::new(MyExt2 { a: 42, b: MyExt { a: 24, b: "INEXT".into() }, c: "EXT2".into() });
754 
755     let mut ep = ExtendableParcelable { a: 1, b: "a".into(), c: 42, ..Default::default() };
756 
757     ep.ext.set_parcelable(Arc::clone(&ext)).unwrap();
758     ep.ext2.set_parcelable(Arc::clone(&ext2)).unwrap();
759 
760     let ext_like = ep.ext.get_parcelable::<MyExtLike>();
761     assert_eq!(ext_like.unwrap_err(), binder::StatusCode::BAD_VALUE);
762 
763     let actual_ext = ep.ext.get_parcelable::<MyExt>();
764     assert!(actual_ext.unwrap().is_some());
765     let actual_ext2 = ep.ext2.get_parcelable::<MyExt2>();
766     assert!(actual_ext2.unwrap().is_some());
767 
768     check_extension_content(&ep, &ext, &ext2);
769 
770     let mut parcel = Parcel::new();
771     ep.write_to_parcel(&mut parcel.borrowed()).unwrap();
772 
773     unsafe {
774         parcel.set_data_position(0).unwrap();
775     }
776     let mut ep1 = ExtendableParcelable::default();
777     ep1.read_from_parcel(parcel.borrowed_ref()).unwrap();
778 
779     unsafe {
780         parcel.set_data_position(0).unwrap();
781     }
782     ep1.write_to_parcel(&mut parcel.borrowed()).unwrap();
783 
784     unsafe {
785         parcel.set_data_position(0).unwrap();
786     }
787     let mut ep2 = ExtendableParcelable::default();
788     ep2.read_from_parcel(parcel.borrowed_ref()).unwrap();
789 
790     let ext_like = ep2.ext.get_parcelable::<MyExtLike>();
791     assert!(ext_like.unwrap().is_none());
792 
793     let actual_ext = ep2.ext.get_parcelable::<MyExt>();
794     assert!(actual_ext.unwrap().is_some());
795 
796     let new_ext2 =
797         Arc::new(MyExt2 { a: 79, b: MyExt { a: 42, b: "INNEWEXT".into() }, c: "NEWEXT2".into() });
798     ep2.ext2.set_parcelable(Arc::clone(&new_ext2)).unwrap();
799 
800     check_extension_content(&ep1, &ext, &ext2);
801     check_extension_content(&ep2, &ext, &new_ext2);
802 }
803 
check_extension_content(ep: &ExtendableParcelable, ext: &MyExt, ext2: &MyExt2)804 fn check_extension_content(ep: &ExtendableParcelable, ext: &MyExt, ext2: &MyExt2) {
805     assert_eq!(ep.a, 1);
806     assert_eq!(ep.b, "a");
807     assert_eq!(ep.c, 42);
808 
809     let actual_ext = ep.ext.get_parcelable::<MyExt>().unwrap().unwrap();
810     assert_eq!(ext.a, actual_ext.a);
811     assert_eq!(ext.b, actual_ext.b);
812 
813     let actual_ext2 = ep.ext2.get_parcelable::<MyExt2>().unwrap().unwrap();
814     assert_eq!(ext2.a, actual_ext2.a);
815     assert_eq!(ext2.b.a, actual_ext2.b.a);
816     assert_eq!(ext2.b.b, actual_ext2.b.b);
817     assert_eq!(ext2.c, actual_ext2.c);
818 }
819 
820 #[test]
test_reverse_recursive_list()821 fn test_reverse_recursive_list() {
822     let service = get_test_service();
823 
824     let mut head = None;
825     for n in 0..10 {
826         let node = RecursiveList { value: n, next: head };
827         head = Some(Box::new(node));
828     }
829     // head = [9, 8, .., 0]
830     let result = service.ReverseList(head.as_ref().unwrap());
831     assert!(result.is_ok());
832 
833     // reversed should be [0, 1, ... 9]
834     let mut reversed: Option<&RecursiveList> = result.as_ref().ok();
835     for n in 0..10 {
836         assert_eq!(reversed.map(|inner| inner.value), Some(n));
837         reversed = reversed.unwrap().next.as_ref().map(|n| n.as_ref());
838     }
839     assert!(reversed.is_none())
840 }
841 
842 #[test]
test_get_union_tags()843 fn test_get_union_tags() {
844     let service = get_test_service();
845     let result = service.GetUnionTags(&[]);
846     assert_eq!(result, Ok(vec![]));
847     let result = service.GetUnionTags(&[Union::Union::N(0), Union::Union::Ns(vec![])]);
848     assert_eq!(result, Ok(vec![Union::Tag::Tag::n, Union::Tag::Tag::ns]));
849 }
850 
851 #[test]
test_unions()852 fn test_unions() {
853     assert_eq!(Union::Union::default(), Union::Union::Ns(vec![]));
854     assert_eq!(EnumUnion::default(), EnumUnion::IntEnum(IntEnum::FOO));
855 }
856 
857 const EXPECTED_ARG_VALUE: i32 = 100;
858 const EXPECTED_RETURN_VALUE: i32 = 200;
859 
860 struct TestDefaultImpl;
861 
862 impl binder::Interface for TestDefaultImpl {}
863 
864 impl ITestServiceDefault for TestDefaultImpl {
UnimplementedMethod(&self, arg: i32) -> binder::Result<i32>865     fn UnimplementedMethod(&self, arg: i32) -> binder::Result<i32> {
866         assert_eq!(arg, EXPECTED_ARG_VALUE);
867         Ok(EXPECTED_RETURN_VALUE)
868     }
869 }
870 
871 #[test]
test_default_impl()872 fn test_default_impl() {
873     let service = get_test_service();
874     let di: ITestServiceDefaultRef = Some(Arc::new(TestDefaultImpl));
875     <BpTestService as ITestService::ITestService>::setDefaultImpl(di);
876 
877     let result = service.UnimplementedMethod(EXPECTED_ARG_VALUE);
878     assert_eq!(result, Ok(EXPECTED_RETURN_VALUE));
879 }
880 
881 #[test]
test_versioned_interface_version()882 fn test_versioned_interface_version() {
883     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
884         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
885             .expect("did not get binder service");
886 
887     let version = service.getInterfaceVersion();
888     assert_eq!(version, Ok(1));
889 }
890 
891 #[test]
test_versioned_interface_hash()892 fn test_versioned_interface_hash() {
893     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
894         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
895             .expect("did not get binder service");
896 
897     let hash = service.getInterfaceHash();
898     assert_eq!(hash.as_ref().map(String::as_str), Ok("9e7be1859820c59d9d55dd133e71a3687b5d2e5b"));
899 }
900 
901 #[test]
test_versioned_known_union_field_is_ok()902 fn test_versioned_known_union_field_is_ok() {
903     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
904         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
905             .expect("did not get binder service");
906 
907     assert_eq!(service.acceptUnionAndReturnString(&BazUnion::IntNum(42)), Ok(String::from("42")));
908 }
909 
910 #[test]
test_versioned_unknown_union_field_triggers_error()911 fn test_versioned_unknown_union_field_triggers_error() {
912     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
913         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
914             .expect("did not get binder service");
915 
916     let ret = service.acceptUnionAndReturnString(&BazUnion::LongNum(42));
917     assert!(ret.is_err());
918 
919     let main_service = get_test_service();
920     let backend = main_service.getBackendType().expect("error getting backend type");
921 
922     // b/173458620 - for investigation of fixing difference
923     if backend == BackendType::JAVA {
924         assert_eq!(ret.unwrap_err().exception_code(), binder::ExceptionCode::ILLEGAL_ARGUMENT);
925     } else {
926         assert_eq!(ret.unwrap_err().transaction_error(), binder::StatusCode::BAD_VALUE);
927     }
928 }
929 
930 #[test]
test_array_of_parcelable_with_new_field()931 fn test_array_of_parcelable_with_new_field() {
932     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
933         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
934             .expect("did not get binder service");
935 
936     let foos = [Default::default(), Default::default(), Default::default()];
937     let ret = service.returnsLengthOfFooArray(&foos);
938     assert_eq!(ret, Ok(foos.len() as i32));
939 }
940 
941 #[test]
test_read_data_correctly_after_parcelable_with_new_field()942 fn test_read_data_correctly_after_parcelable_with_new_field() {
943     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
944         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
945             .expect("did not get binder service");
946 
947     let in_foo = Default::default();
948     let mut inout_foo = Foo { intDefault42: 0 };
949     let mut out_foo = Foo { intDefault42: 0 };
950     let ret = service.ignoreParcelablesAndRepeatInt(&in_foo, &mut inout_foo, &mut out_foo, 43);
951     assert_eq!(ret, Ok(43));
952     assert_eq!(inout_foo.intDefault42, 0);
953     assert_eq!(out_foo.intDefault42, 0);
954 }
955 
956 #[test]
test_calling_v2_api_triggers_error()957 fn test_calling_v2_api_triggers_error() {
958     let service: binder::Strong<dyn IFooInterface::IFooInterface> =
959         binder::get_interface(<BpFooInterface as IFooInterface::IFooInterface>::get_descriptor())
960             .expect("did not get binder service");
961 
962     let ret = service.newApi();
963 
964     assert_eq!(ret.unwrap_err().transaction_error(), binder::StatusCode::UNKNOWN_TRANSACTION);
965 }
966 
test_renamed_interface<F>(f: F) where F: FnOnce(binder::Strong<dyn IOldName::IOldName>, binder::Strong<dyn INewName::INewName>),967 fn test_renamed_interface<F>(f: F)
968 where
969     F: FnOnce(binder::Strong<dyn IOldName::IOldName>, binder::Strong<dyn INewName::INewName>),
970 {
971     let service = get_test_service();
972     let old_name = service.GetOldNameInterface();
973     assert!(old_name.is_ok());
974 
975     let new_name = service.GetNewNameInterface();
976     assert!(new_name.is_ok());
977 
978     f(old_name.unwrap(), new_name.unwrap());
979 }
980 
981 #[test]
test_renamed_interface_old_as_old()982 fn test_renamed_interface_old_as_old() {
983     test_renamed_interface(|old_name, _| {
984         assert_eq!(
985             <BpOldName as IOldName::IOldName>::get_descriptor(),
986             "android.aidl.tests.IOldName"
987         );
988 
989         let real_name = old_name.RealName();
990         assert_eq!(real_name.as_ref().map(String::as_str), Ok("OldName"));
991     });
992 }
993 
994 #[test]
test_renamed_interface_new_as_new()995 fn test_renamed_interface_new_as_new() {
996     test_renamed_interface(|_, new_name| {
997         assert_eq!(
998             <BpNewName as INewName::INewName>::get_descriptor(),
999             "android.aidl.tests.IOldName"
1000         );
1001 
1002         let real_name = new_name.RealName();
1003         assert_eq!(real_name.as_ref().map(String::as_str), Ok("NewName"));
1004     });
1005 }
1006 
1007 #[test]
test_renamed_interface_old_as_new()1008 fn test_renamed_interface_old_as_new() {
1009     test_renamed_interface(|old_name, _| {
1010         let new_name = old_name.as_binder().into_interface::<dyn INewName::INewName>();
1011         assert!(new_name.is_ok());
1012 
1013         let real_name = new_name.unwrap().RealName();
1014         assert_eq!(real_name.as_ref().map(String::as_str), Ok("OldName"));
1015     });
1016 }
1017 
1018 #[test]
test_renamed_interface_new_as_old()1019 fn test_renamed_interface_new_as_old() {
1020     test_renamed_interface(|_, new_name| {
1021         let old_name = new_name.as_binder().into_interface::<dyn IOldName::IOldName>();
1022         assert!(old_name.is_ok());
1023 
1024         let real_name = old_name.unwrap().RealName();
1025         assert_eq!(real_name.as_ref().map(String::as_str), Ok("NewName"));
1026     });
1027 }
1028 
1029 #[derive(Debug, Default)]
1030 struct Callback {
1031     received: Arc<Mutex<Option<ParcelableWithNested::Status::Status>>>,
1032 }
1033 
1034 impl Interface for Callback {}
1035 
1036 impl INestedService::ICallback::ICallback for Callback {
done(&self, st: ParcelableWithNested::Status::Status) -> binder::Result<()>1037     fn done(&self, st: ParcelableWithNested::Status::Status) -> binder::Result<()> {
1038         *self.received.lock().unwrap() = Some(st);
1039         Ok(())
1040     }
1041 }
1042 
1043 #[test]
test_nested_type()1044 fn test_nested_type() {
1045     let service: binder::Strong<dyn INestedService::INestedService> = binder::get_interface(
1046         <INestedService::BpNestedService as INestedService::INestedService>::get_descriptor(),
1047     )
1048     .expect("did not get binder service");
1049 
1050     let p = ParcelableWithNested::ParcelableWithNested {
1051         status: ParcelableWithNested::Status::Status::OK,
1052     };
1053     // OK -> NOT_OK
1054     let ret = service.flipStatus(&p);
1055     assert_eq!(
1056         ret,
1057         Ok(INestedService::Result::Result { status: ParcelableWithNested::Status::Status::NOT_OK })
1058     );
1059     let received = Arc::new(Mutex::new(None));
1060     // NOT_OK -> OK with nested callback interface
1061     let cb = INestedService::ICallback::BnCallback::new_binder(
1062         Callback { received: Arc::clone(&received) },
1063         BinderFeatures::default(),
1064     );
1065     let ret = service.flipStatusWithCallback(ParcelableWithNested::Status::Status::NOT_OK, &cb);
1066     assert_eq!(ret, Ok(()));
1067     let received = received.lock().unwrap();
1068     assert_eq!(*received, Some(ParcelableWithNested::Status::Status::OK))
1069 }
1070 
1071 #[test]
test_nonnull_binder()1072 fn test_nonnull_binder() {
1073     let service = get_test_service();
1074     let result = service.TakesAnIBinder(&service.as_binder());
1075     assert!(result.is_ok());
1076 }
1077 
1078 #[test]
test_binder_list_without_null()1079 fn test_binder_list_without_null() {
1080     let service = get_test_service();
1081     let result = service.TakesAnIBinderList(&[service.as_binder()]);
1082     assert!(result.is_ok());
1083 }
1084 
1085 #[test]
test_null_binder_to_annotated_method()1086 fn test_null_binder_to_annotated_method() {
1087     let service = get_test_service();
1088     let result = service.TakesANullableIBinder(None);
1089     assert!(result.is_ok());
1090 }
1091 
1092 #[test]
test_binder_list_with_null_to_annotated_method()1093 fn test_binder_list_with_null_to_annotated_method() {
1094     let service = get_test_service();
1095     let result = service.TakesANullableIBinderList(Some(&[Some(service.as_binder()), None]));
1096     assert!(result.is_ok());
1097 }
1098 
1099 #[test]
test_binder_array()1100 fn test_binder_array() {
1101     let service = get_test_service();
1102     let callback = service
1103         .GetCallback(false)
1104         .expect("error calling GetCallback")
1105         .expect("expected Some from GetCallback");
1106 
1107     let mut array = vec![service.as_binder(), callback.as_binder()];
1108 
1109     // Java needs initial values here (can't resize arrays)
1110     let mut repeated = vec![Default::default(); array.len()];
1111 
1112     let result = service.ReverseIBinderArray(&array, &mut repeated);
1113     assert_eq!(repeated.into_iter().collect::<Option<Vec<_>>>().as_ref(), Some(&array));
1114     array.reverse();
1115     assert_eq!(result, Ok(array));
1116 }
1117 
1118 #[test]
test_nullable_binder_array()1119 fn test_nullable_binder_array() {
1120     let service = get_test_service();
1121     let mut array = vec![Some(service.as_binder()), None];
1122 
1123     // Java needs initial values here (can't resize arrays)
1124     let mut repeated = Some(vec![Default::default(); array.len()]);
1125 
1126     let result = service.ReverseNullableIBinderArray(Some(&array[..]), &mut repeated);
1127     assert_eq!(repeated.as_ref(), Some(&array));
1128     array.reverse();
1129     assert_eq!(result, Ok(Some(array)));
1130 }
1131 
1132 #[test]
test_read_write_fixed_size_array()1133 fn test_read_write_fixed_size_array() {
1134     let mut parcel = Parcel::new();
1135     let mut p: FixedSizeArrayExample = Default::default();
1136     p.byteMatrix[0][0] = 0;
1137     p.byteMatrix[0][1] = 1;
1138     p.byteMatrix[1][0] = 2;
1139     p.byteMatrix[1][1] = 3;
1140 
1141     p.floatMatrix[0][0] = 0.0;
1142     p.floatMatrix[0][1] = 1.0;
1143     p.floatMatrix[1][0] = 2.0;
1144     p.floatMatrix[1][1] = 3.0;
1145 
1146     p.boolNullableArray = Some([true, false]);
1147     p.byteNullableArray = Some([42, 0]);
1148     p.stringNullableArray = Some([Some("hello".into()), Some("world".into())]);
1149 
1150     p.boolNullableMatrix = Some([[true, false], Default::default()]);
1151     p.byteNullableMatrix = Some([[42, 0], Default::default()]);
1152     p.stringNullableMatrix =
1153         Some([[Some("hello".into()), Some("world".into())], Default::default()]);
1154 
1155     assert_eq!(parcel.write(&p), Ok(()));
1156     unsafe {
1157         parcel.set_data_position(0).unwrap();
1158     }
1159     assert_eq!(p, parcel.read::<FixedSizeArrayExample>().unwrap());
1160 }
1161 
1162 #[test]
test_fixed_size_array_uses_array_optimization()1163 fn test_fixed_size_array_uses_array_optimization() {
1164     let mut parcel = Parcel::new();
1165     let byte_array = [[1u8, 2u8, 3u8], [4u8, 5u8, 6u8]];
1166     assert_eq!(parcel.write(&byte_array), Ok(()));
1167     unsafe {
1168         parcel.set_data_position(0).unwrap();
1169     }
1170     assert_eq!(parcel.read::<i32>(), Ok(2i32));
1171     assert_eq!(parcel.read::<Vec<u8>>(), Ok(vec![1u8, 2u8, 3u8]));
1172     assert_eq!(parcel.read::<Vec<u8>>(), Ok(vec![4u8, 5u8, 6u8]));
1173 }
1174 
1175 macro_rules! test_repeat_fixed_size_array {
1176     ($service:ident, $func:ident, $value:expr) => {
1177         let array = $value;
1178         let mut repeated = Default::default();
1179         let result = $service.$func(&array, &mut repeated).unwrap();
1180         assert_eq!(repeated, array);
1181         assert_eq!(result, array);
1182     };
1183 }
1184 
1185 macro_rules! test_repeat_fixed_size_array_1d_binder {
1186     ($service:ident, $func:ident, $value:expr) => {
1187         let array = $value;
1188         let mut repeated = Default::default();
1189         let result = $service.$func(&array, &mut repeated).unwrap();
1190         assert_eq!(result, array.clone());
1191         assert_eq!(repeated, array.map(Some));
1192     };
1193 }
1194 
1195 macro_rules! test_repeat_fixed_size_array_2d_binder {
1196     ($service:ident, $func:ident, $value:expr) => {
1197         let array = $value;
1198         let mut repeated = Default::default();
1199         let result = $service.$func(&array, &mut repeated).unwrap();
1200         assert_eq!(result, array.clone());
1201         assert_eq!(repeated, array.map(|row| row.map(Some)));
1202     };
1203 }
1204 
1205 #[test]
test_fixed_size_array_over_binder()1206 fn test_fixed_size_array_over_binder() {
1207     let test_service = get_test_service();
1208     let service: binder::Strong<dyn IRepeatFixedSizeArray> =
1209         binder::get_interface(<BpRepeatFixedSizeArray as IRepeatFixedSizeArray>::get_descriptor())
1210             .expect("did not get binder service");
1211 
1212     test_repeat_fixed_size_array!(service, RepeatBytes, [1u8, 2u8, 3u8]);
1213     test_repeat_fixed_size_array!(service, RepeatInts, [1i32, 2i32, 3i32]);
1214 
1215     let binder1 = test_service.as_binder();
1216     let binder2 = test_service
1217         .GetCallback(false)
1218         .expect("error calling GetCallback")
1219         .expect("expected Some from GetCallback")
1220         .as_binder();
1221     let binder3 = service.as_binder();
1222     test_repeat_fixed_size_array_1d_binder!(
1223         service,
1224         RepeatBinders,
1225         [binder1.clone(), binder2.clone(), binder3.clone()]
1226     );
1227 
1228     let p1 = IntParcelable { value: 1 };
1229     let p2 = IntParcelable { value: 2 };
1230     let p3 = IntParcelable { value: 3 };
1231     test_repeat_fixed_size_array!(service, RepeatParcelables, [p1, p2, p3]);
1232 
1233     test_repeat_fixed_size_array!(service, Repeat2dBytes, [[1u8, 2u8, 3u8], [1u8, 2u8, 3u8]]);
1234     test_repeat_fixed_size_array!(service, Repeat2dInts, [[1i32, 2i32, 3i32], [1i32, 2i32, 3i32]]);
1235 
1236     test_repeat_fixed_size_array_2d_binder!(
1237         service,
1238         Repeat2dBinders,
1239         [[binder1.clone(), binder2.clone(), binder3.clone()], [binder1, binder2, binder3]]
1240     );
1241 
1242     test_repeat_fixed_size_array!(service, Repeat2dParcelables, [[p1, p2, p3], [p1, p2, p3]]);
1243 }
1244 
1245 #[test]
test_ping()1246 fn test_ping() {
1247     let test_service = get_test_service();
1248     assert_eq!(test_service.as_binder().ping_binder(), Ok(()));
1249 }
1250