wasmer_types/
store_id.rs

1use core::fmt::Display;
2use std::{
3    num::NonZeroUsize,
4    sync::atomic::{AtomicUsize, Ordering},
5};
6
7/// Unique ID to identify a context.
8///
9/// Every handle to an object managed by a context also contains the ID of the
10/// context. This is used to check that a handle is always used with the
11/// correct context.
12#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
13pub struct StoreId(NonZeroUsize);
14
15#[cfg(feature = "artifact-size")]
16impl loupe::MemoryUsage for StoreId {
17    fn size_of_val(&self, _visited: &mut dyn loupe::MemoryUsageTracker) -> usize {
18        std::mem::size_of_val(self)
19    }
20}
21
22impl Default for StoreId {
23    // Allocates a unique ID for a new context.
24    fn default() -> Self {
25        // No overflow checking is needed here: overflowing this would take
26        // thousands of years.
27        static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
28        Self(NonZeroUsize::new(NEXT_ID.fetch_add(1, Ordering::Relaxed)).unwrap())
29    }
30}
31
32impl Display for StoreId {
33    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34        let val: usize = self.0.into();
35        if val == usize::MAX {
36            write!(f, "unknown")
37        } else {
38            write!(f, "{}", self.0)
39        }
40    }
41}