blob: 28e5c3be2e8836adfb082e2fe27d8e6db9d35b6b [file] [log] [blame]
David Tolnay3fd7f562020-01-26 17:47:11 -08001use cxx_test_suite::ffi;
2use std::cell::Cell;
David Tolnayf306da42020-02-22 19:55:43 -08003use std::ffi::CStr;
David Tolnay3fd7f562020-01-26 17:47:11 -08004
5thread_local! {
6 static CORRECT: Cell<bool> = Cell::new(false);
7}
8
9#[no_mangle]
10extern "C" fn cxx_test_suite_set_correct() {
11 CORRECT.with(|correct| correct.set(true));
12}
13
David Tolnayf306da42020-02-22 19:55:43 -080014macro_rules! check {
15 ($run:expr) => {{
16 CORRECT.with(|correct| correct.set(false));
17 $run;
18 assert!(CORRECT.with(|correct| correct.get()), stringify!($run));
19 }};
20}
21
David Tolnay3fd7f562020-01-26 17:47:11 -080022#[test]
23fn test_c_return() {
24 let shared = ffi::Shared { z: 2020 };
25
26 assert_eq!(2020, ffi::c_return_primitive());
27 assert_eq!(2020, ffi::c_return_shared().z);
28 ffi::c_return_unique_ptr();
29 assert_eq!(2020, *ffi::c_return_ref(&shared));
30 assert_eq!("2020", ffi::c_return_str(&shared));
31 assert_eq!("2020", ffi::c_return_rust_string());
32 assert_eq!(
33 "2020",
34 ffi::c_return_unique_ptr_string()
35 .as_ref()
36 .unwrap()
37 .to_str()
38 .unwrap()
39 );
40}
41
42#[test]
43fn test_c_take() {
David Tolnay3fd7f562020-01-26 17:47:11 -080044 let unique_ptr = ffi::c_return_unique_ptr();
45
46 check!(ffi::c_take_primitive(2020));
47 check!(ffi::c_take_shared(ffi::Shared { z: 2020 }));
48 check!(ffi::c_take_box(Box::new(())));
49 check!(ffi::c_take_ref_c(unique_ptr.as_ref().unwrap()));
50 check!(ffi::c_take_unique_ptr(unique_ptr));
51 check!(ffi::c_take_str("2020"));
52 check!(ffi::c_take_rust_string("2020".to_owned()));
53 check!(ffi::c_take_unique_ptr_string(
54 ffi::c_return_unique_ptr_string()
55 ));
56}
David Tolnayf306da42020-02-22 19:55:43 -080057
58#[test]
59fn test_c_call_r() {
60 fn cxx_run_test() {
61 extern "C" {
62 fn cxx_run_test() -> *const i8;
63 }
64 let failure = unsafe { cxx_run_test() };
65 if !failure.is_null() {
66 let msg = unsafe { CStr::from_ptr(failure) };
67 eprintln!("{}", msg.to_string_lossy());
68 }
69 }
70 check!(cxx_run_test());
71}