wiggle_generate/types/
handle.rs

1use crate::names;
2
3use proc_macro2::TokenStream;
4use quote::quote;
5use witx::Layout;
6
7pub(super) fn define_handle(name: &witx::Id, h: &witx::HandleDatatype) -> TokenStream {
8    let ident = names::type_(name);
9    let size = h.mem_size_align().size as u32;
10    let align = h.mem_size_align().align;
11    quote! {
12        #[repr(transparent)]
13        #[derive(Copy, Clone, Debug, ::std::hash::Hash, Eq, PartialEq)]
14        pub struct #ident(u32);
15
16        impl #ident {
17            #[inline]
18            pub unsafe fn inner(&self) -> u32 {
19                self.0
20            }
21        }
22
23        impl From<#ident> for u32 {
24            #[inline]
25            fn from(e: #ident) -> u32 {
26                e.0
27            }
28        }
29
30        impl From<#ident> for i32 {
31            #[inline]
32            fn from(e: #ident) -> i32 {
33                e.0 as i32
34            }
35        }
36
37        impl From<u32> for #ident {
38            #[inline]
39            fn from(e: u32) -> #ident {
40                #ident(e)
41            }
42        }
43        impl From<i32> for #ident {
44            #[inline]
45            fn from(e: i32) -> #ident {
46                #ident(e as u32)
47            }
48        }
49
50        impl ::std::fmt::Display for #ident {
51            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
52                write!(f, "{}({})", stringify!(#ident), self.0)
53            }
54        }
55
56        impl wiggle::GuestType for #ident {
57            #[inline]
58            fn guest_size() -> u32 {
59                #size
60            }
61
62            #[inline]
63            fn guest_align() -> usize {
64                #align
65            }
66
67            #[inline]
68            fn read(mem: &wiggle::GuestMemory, location: wiggle::GuestPtr<#ident>) -> Result<#ident, wiggle::GuestError> {
69                Ok(#ident(u32::read(mem, location.cast())?))
70            }
71
72            #[inline]
73            fn write(mem: &mut wiggle::GuestMemory, location: wiggle::GuestPtr<Self>, val: Self) -> Result<(), wiggle::GuestError> {
74                u32::write(mem, location.cast(), val.0)
75            }
76        }
77    }
78}
79
80impl super::WiggleType for witx::HandleDatatype {
81    fn impls_display(&self) -> bool {
82        true
83    }
84}