viceroy_lib/wiggle_abi/
entity.rs

1//! [`cranelift_entity::EntityRef`][ref] implementations for ABI types.
2//!
3//! [ref]: https://docs.rs/cranelift-entity/latest/cranelift_entity/trait.EntityRef.html
4
5use super::types::{
6    AclHandle, AsyncItemHandle, BodyHandle, DictionaryHandle, EndpointHandle, KvStoreHandle,
7    ObjectStoreHandle, PendingRequestHandle, RequestHandle, ResponseHandle, SecretHandle,
8    SecretStoreHandle,
9};
10
11/// Macro which implements a 32-bit entity reference for handles generated by Wiggle.
12///
13/// This is for all intents and purposes, a use-case specific version of the [`entity_impl`][impl]
14/// macro provided by [`cranelift-entity`][entity]. For handles generated by a call to
15/// [`wiggle::from_witx`][from-witx], we have to implement entity reference trait slightly
16/// differently than normal, due to these types having a private constructor. Instead, we use their
17/// `From<u32>` trait implementations to convert back and forth from `usize` values.
18///
19/// [entity]: https://docs.rs/cranelift-entity/latest/cranelift_entity/
20/// [from-witx]: https://docs.rs/wiggle/latest/wiggle/macro.from_witx.html
21/// [impl]: https://docs.rs/cranelift-entity/latest/cranelift_entity/macro.entity_impl.html
22// TODO KTM 2020-06-29: If this ever becomes a maintenance burden, this could be submitted upstream
23// as an alternative mode for the `cranelift_entity::entity_impl` macro.
24macro_rules! wiggle_entity {
25    ($entity:ident) => {
26        /// `EntityRef` allows a small integer type to be used as the key to an entity map, such as
27        /// `PrimaryMap`, `SecondaryMap`, or `SparseMap`.
28        impl cranelift_entity::EntityRef for $entity {
29            /// Create a new entity reference from a small integer.
30            fn new(index: usize) -> Self {
31                debug_assert!(index < (std::u32::MAX as usize));
32                (index as u32).into()
33            }
34            /// Get the index that was used to create this entity reference.
35            fn index(self) -> usize {
36                let i: u32 = self.into();
37                i as usize
38            }
39        }
40    };
41}
42
43wiggle_entity!(AclHandle);
44wiggle_entity!(AsyncItemHandle);
45wiggle_entity!(BodyHandle);
46wiggle_entity!(DictionaryHandle);
47wiggle_entity!(EndpointHandle);
48wiggle_entity!(KvStoreHandle);
49wiggle_entity!(ObjectStoreHandle);
50wiggle_entity!(PendingRequestHandle);
51wiggle_entity!(RequestHandle);
52wiggle_entity!(ResponseHandle);
53wiggle_entity!(SecretHandle);
54wiggle_entity!(SecretStoreHandle);