Skip to main content

wasmer_types/entity/
mod.rs

1// This file contains code from external sources.
2// Attributions: https://github.com/wasmerio/wasmer/blob/main/docs/ATTRIBUTIONS.md
3
4/// A type wrapping a small integer index should implement `EntityRef` so it can be used as the key
5/// of an `SecondaryMap` or `SparseMap`.
6pub trait EntityRef: Copy + Eq {
7    /// Create a new entity reference from a small integer.
8    /// This should crash if the requested index is not representable.
9    fn new(_: usize) -> Self;
10
11    /// Get the index that was used to create this entity reference.
12    fn index(self) -> usize;
13}
14
15/// Macro which provides the common implementation of a 32-bit entity reference.
16#[macro_export]
17macro_rules! entity_impl {
18    // Basic traits.
19    ($entity:ident) => {
20        impl $crate::entity::EntityRef for $entity {
21            fn new(index: usize) -> Self {
22                debug_assert!(index < (u32::MAX as usize));
23                $entity(index as u32)
24            }
25
26            fn index(self) -> usize {
27                self.0 as usize
28            }
29        }
30
31        impl $crate::entity::packed_option::ReservedValue for $entity {
32            fn reserved_value() -> $entity {
33                $entity(u32::MAX)
34            }
35
36            fn is_reserved_value(&self) -> bool {
37                self.0 == u32::MAX
38            }
39        }
40
41        impl $entity {
42            /// Create a new instance from a `u32`.
43            #[allow(dead_code)]
44            pub fn from_u32(x: u32) -> Self {
45                debug_assert!(x < u32::MAX);
46                $entity(x)
47            }
48
49            /// Return the underlying index value as a `u32`.
50            #[allow(dead_code)]
51            pub fn as_u32(self) -> u32 {
52                self.0
53            }
54        }
55    };
56
57    // Include basic `Display` impl using the given display prefix.
58    // Display a `Block` reference as "block12".
59    ($entity:ident, $display_prefix:expr) => {
60        entity_impl!($entity);
61
62        impl ::core::fmt::Display for $entity {
63            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
64                write!(f, concat!($display_prefix, "{}"), self.0)
65            }
66        }
67
68        impl ::core::fmt::Debug for $entity {
69            fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
70                (self as &dyn ::core::fmt::Display).fmt(f)
71            }
72        }
73    };
74}
75
76pub mod packed_option;
77
78mod boxed_slice;
79mod iter;
80mod keys;
81mod primary_map;
82mod secondary_map;
83
84pub use crate::entity_impl;
85pub use boxed_slice::BoxedSlice;
86pub use iter::{Iter, IterMut};
87pub use keys::Keys;
88pub use primary_map::{ArchivedPrimaryMap, PrimaryMap};
89pub use secondary_map::SecondaryMap;