wasmer_runtime_core_near/structures/
slice.rs

1use super::{Iter, IterMut, TypedIndex};
2use std::{
3    marker::PhantomData,
4    ops::{Index, IndexMut},
5};
6
7/// This is a dynamically-sized slice
8/// that can only be indexed by the
9/// correct index type.
10#[derive(Debug)]
11pub struct SliceMap<K, V>
12where
13    K: TypedIndex,
14{
15    _marker: PhantomData<K>,
16    slice: [V],
17}
18
19impl<K, V> SliceMap<K, V>
20where
21    K: TypedIndex,
22{
23    /// Gets a reference to the value at the given index.
24    pub fn get(&self, index: K) -> Option<&V> {
25        self.slice.get(index.index())
26    }
27
28    /// Gets a mutable reference to the value at the given index.
29    pub fn get_mut(&mut self, index: K) -> Option<&mut V> {
30        self.slice.get_mut(index.index())
31    }
32
33    /// Gets the length of this slice map.
34    pub fn len(&self) -> usize {
35        self.slice.len()
36    }
37
38    /// Returns an iterator for this slice map.
39    pub fn iter(&self) -> Iter<K, V> {
40        Iter::new(self.slice.iter())
41    }
42
43    /// Returns a mutable iterator for this slice map.
44    pub fn iter_mut(&mut self) -> IterMut<K, V> {
45        IterMut::new(self.slice.iter_mut())
46    }
47
48    /// Gets a pointer to the `SliceMap`.
49    pub fn as_ptr(&self) -> *const V {
50        self as *const SliceMap<K, V> as *const V
51    }
52
53    /// Gets a mutable pointer to the `SliceMap`.
54    pub fn as_mut_ptr(&mut self) -> *mut V {
55        self as *mut SliceMap<K, V> as *mut V
56    }
57}
58
59impl<K, V> Index<K> for SliceMap<K, V>
60where
61    K: TypedIndex,
62{
63    type Output = V;
64    fn index(&self, index: K) -> &V {
65        &self.slice[index.index()]
66    }
67}
68
69impl<K, V> IndexMut<K> for SliceMap<K, V>
70where
71    K: TypedIndex,
72{
73    fn index_mut(&mut self, index: K) -> &mut V {
74        &mut self.slice[index.index()]
75    }
76}