spin_resource_table/
lib.rs

1use std::collections::HashMap;
2
3/// This is a table for generating unique u32 identifiers for each element in a dynamically-changing set of
4/// resources.
5///
6/// This is inspired by the `Table` type in
7/// [wasi-common](https://github.com/bytecodealliance/wasmtime/tree/main/crates/wasi-common) and serves the same
8/// purpose: allow opaque resources and their lifetimes to be managed across an interface boundary, analogous to
9/// how file handles work across the user-kernel boundary.
10pub struct Table<V> {
11    capacity: u32,
12    next_key: u32,
13    tuples: HashMap<u32, V>,
14}
15
16impl<V> Default for Table<V> {
17    fn default() -> Self {
18        Self::new(1024)
19    }
20}
21
22impl<V> Table<V> {
23    /// Create a new, empty table with the specified capacity.
24    pub fn new(capacity: u32) -> Self {
25        Self {
26            capacity,
27            next_key: 0,
28            tuples: HashMap::new(),
29        }
30    }
31
32    /// Add the specified resource to this table.
33    ///
34    /// If the table is full (i.e. there already are `self.capacity` resources inside), this returns `Err(())`.
35    /// Otherwise, a new, unique identifier is allocated for the resource and returned.
36    ///
37    /// This function will attempt to avoid reusing recently closed identifiers, but after 2^32 calls to this
38    /// function they will start repeating.
39    #[allow(clippy::result_unit_err)]
40    pub fn push(&mut self, value: V) -> Result<u32, ()> {
41        if self.tuples.len() == self.capacity as usize {
42            Err(())
43        } else {
44            loop {
45                let key = self.next_key;
46                self.next_key = self.next_key.wrapping_add(1);
47                if self.tuples.contains_key(&key) {
48                    continue;
49                }
50                self.tuples.insert(key, value);
51                return Ok(key);
52            }
53        }
54    }
55
56    /// Get a reference to the resource identified by the specified `key`, if it exists.
57    pub fn get(&self, key: u32) -> Option<&V> {
58        self.tuples.get(&key)
59    }
60
61    /// Get a mutable reference to the resource identified by the specified `key`, if it exists.
62    pub fn get_mut(&mut self, key: u32) -> Option<&mut V> {
63        self.tuples.get_mut(&key)
64    }
65
66    /// Remove the resource identified by the specified `key`, if present.
67    ///
68    /// This makes the key eligible for eventual reuse (i.e. for a newly-pushed resource).
69    pub fn remove(&mut self, key: u32) -> Option<V> {
70        self.tuples.remove(&key)
71    }
72}