xref: /wasmtime-44.0.1/crates/wiggle/tests/ints.rs (revision 90ac295e)
1 use proptest::prelude::*;
2 use wiggle::{GuestMemory, GuestPtr};
3 use wiggle_test::{HostMemory, MemArea, WasiCtx, impl_errno};
4 
5 wiggle::from_witx!({
6     witx: ["tests/ints.witx"],
7 });
8 
9 impl_errno!(types::Errno);
10 
11 impl<'a> ints::Ints for WasiCtx<'a> {
cookie_cutter( &mut self, _memory: &mut GuestMemory<'_>, init_cookie: types::Cookie, ) -> Result<types::Bool, types::Errno>12     fn cookie_cutter(
13         &mut self,
14         _memory: &mut GuestMemory<'_>,
15         init_cookie: types::Cookie,
16     ) -> Result<types::Bool, types::Errno> {
17         let res = if init_cookie == types::COOKIE_START {
18             types::Bool::True
19         } else {
20             types::Bool::False
21         };
22         Ok(res)
23     }
24 }
25 
cookie_strat() -> impl Strategy<Value = types::Cookie>26 fn cookie_strat() -> impl Strategy<Value = types::Cookie> {
27     (0..std::u64::MAX)
28         .prop_map(|x| types::Cookie::try_from(x).expect("within range of cookie"))
29         .boxed()
30 }
31 
32 #[derive(Debug)]
33 struct CookieCutterExercise {
34     cookie: types::Cookie,
35     return_ptr_loc: MemArea,
36 }
37 
38 impl CookieCutterExercise {
strat() -> BoxedStrategy<Self>39     pub fn strat() -> BoxedStrategy<Self> {
40         (cookie_strat(), HostMemory::mem_area_strat(4))
41             .prop_map(|(cookie, return_ptr_loc)| Self {
42                 cookie,
43                 return_ptr_loc,
44             })
45             .boxed()
46     }
47 
test(&self)48     pub fn test(&self) {
49         let mut ctx = WasiCtx::new();
50         let mut host_memory = HostMemory::new();
51         let mut memory = host_memory.guest_memory();
52 
53         let res = ints::cookie_cutter(
54             &mut ctx,
55             &mut memory,
56             self.cookie as i64,
57             self.return_ptr_loc.ptr as i32,
58         )
59         .unwrap();
60         assert_eq!(res, types::Errno::Ok as i32, "cookie cutter errno");
61 
62         let is_cookie_start = memory
63             .read(GuestPtr::<types::Bool>::new(self.return_ptr_loc.ptr))
64             .expect("deref to Bool value");
65 
66         assert_eq!(
67             if is_cookie_start == types::Bool::True {
68                 true
69             } else {
70                 false
71             },
72             self.cookie == types::COOKIE_START,
73             "returned Bool should test if input was Cookie::START",
74         );
75     }
76 }
77 proptest! {
78     #[test]
79     fn cookie_cutter(e in CookieCutterExercise::strat()) {
80         e.test()
81     }
82 }
83