wai_bindgen_wasmer/
table.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::convert::TryFrom;
use std::fmt;
use std::mem;

pub struct Table<T> {
    elems: Vec<Slot<T>>,
    next: usize,
}

#[derive(Debug)]
pub enum RemoveError {
    NotAllocated,
}

enum Slot<T> {
    Empty { next_empty: usize },
    Full { item: Box<T> },
}

impl<T> Table<T> {
    /// Creates a new empty table
    pub fn new() -> Table<T> {
        Table {
            elems: Vec::new(),
            next: 0,
        }
    }

    /// Inserts an item into this table, returning the index that it was
    /// inserted at.
    pub fn insert(&mut self, item: T) -> u32 {
        if self.next == self.elems.len() {
            let next_empty = self.next + 1;
            self.elems.push(Slot::Empty { next_empty });
        }
        let index = self.next;
        let ret = u32::try_from(index).unwrap();
        self.next = match &self.elems[index] {
            Slot::Empty { next_empty } => *next_empty,
            Slot::Full { .. } => unreachable!(),
        };
        self.elems[index] = Slot::Full {
            item: Box::new(item),
        };
        ret
    }

    /// Borrows an item from this table.
    ///
    /// Returns `None` if the index is not allocated at this time. Otherwise
    /// returns `Some` with a borrow of the item from this table.
    pub fn get(&self, item: u32) -> Option<&T> {
        let index = usize::try_from(item).unwrap();
        match self.elems.get(index)? {
            Slot::Empty { .. } => None,
            Slot::Full { item } => Some(item),
        }
    }

    /// Removes an item from this table.
    ///
    /// On success it returns back the original item.
    pub fn remove(&mut self, item: u32) -> Result<T, RemoveError> {
        let index = usize::try_from(item).unwrap();
        let new_empty = Slot::Empty {
            next_empty: self.next,
        };
        let slot = self.elems.get_mut(index).ok_or(RemoveError::NotAllocated)?;

        // Assume that `item` is valid, and if it is, we can return quickly
        match mem::replace(slot, new_empty) {
            Slot::Full { item } => {
                self.next = index;
                Ok(*item)
            }

            // Oops `item` wasn't valid, put it back where we found it and then
            // figure out why it was invalid
            Slot::Empty { next_empty } => {
                *slot = Slot::Empty { next_empty };
                Err(RemoveError::NotAllocated)
            }
        }
    }
}

impl<T> Default for Table<T> {
    fn default() -> Table<T> {
        Table::new()
    }
}

impl<T> fmt::Debug for Table<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Table")
            .field("capacity", &self.elems.capacity())
            .finish()
    }
}

impl fmt::Display for RemoveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RemoveError::NotAllocated => f.write_str("invalid handle index"),
        }
    }
}

impl std::error::Error for RemoveError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simple() {
        let mut table = Table::new();
        assert_eq!(table.insert(0), 0);
        assert_eq!(table.insert(100), 1);
        assert_eq!(table.insert(200), 2);

        assert_eq!(*table.get(0).unwrap(), 0);
        assert_eq!(*table.get(1).unwrap(), 100);
        assert_eq!(*table.get(2).unwrap(), 200);
        assert!(table.get(100).is_none());

        assert!(table.remove(0).is_ok());
        assert!(table.get(0).is_none());
        assert_eq!(table.insert(1), 0);
        assert!(table.get(0).is_some());

        table.get(1).unwrap();
        assert!(table.remove(1).is_ok());
        assert!(table.remove(1).is_err());

        assert!(table.remove(2).is_ok());
        assert!(table.remove(0).is_ok());

        assert_eq!(table.insert(100), 0);
        assert_eq!(table.insert(100), 2);
        assert_eq!(table.insert(100), 1);
        assert_eq!(table.insert(100), 3);
    }
}