Skip to main content

hv1_structs/
vtl_array.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Container data structures indexable by [`Vtl`].
5
6use bitvec::array::BitArray;
7use core::ops::Deref;
8use core::ops::DerefMut;
9use core::ops::Index;
10use core::ops::IndexMut;
11use hvdef::Vtl;
12use inspect::Inspect;
13use inspect::InspectMut;
14
15// TODO: Enforce N <= 3 on the type when stable
16/// An array indexable by [`Vtl`].
17#[derive(Debug, Clone, Inspect)]
18#[inspect(transparent(iter_by_index), bound = "T: Inspect")]
19pub struct VtlArray<T, const N: usize> {
20    data: [T; N],
21}
22
23impl<T, const N: usize> VtlArray<T, N> {
24    /// Creates an array of type T, where each element is `value`.
25    pub const fn new(value: T) -> Self
26    where
27        T: Copy,
28    {
29        assert!(N > 0 && N <= 3);
30        Self { data: [value; N] }
31    }
32
33    /// Creates an array of type T, where each element is
34    /// the returned value from `f` using that element’s index.
35    pub fn from_fn<F>(mut f: F) -> Self
36    where
37        F: FnMut(Vtl) -> T,
38    {
39        assert!(N > 0 && N <= 3);
40        Self {
41            data: core::array::from_fn(|i| f(Vtl::try_from(i as u8).unwrap())),
42        }
43    }
44
45    /// Maps over the vtl array using the raw underlying array.
46    pub fn map<U, F>(self, f: F) -> VtlArray<U, N>
47    where
48        F: FnMut(T) -> U,
49    {
50        VtlArray {
51            data: self.data.map(f),
52        }
53    }
54
55    /// Borrows each element and returns an array of references with the same
56    /// size as self.
57    pub const fn each_ref(&self) -> VtlArray<&T, N> {
58        VtlArray {
59            data: self.data.each_ref(),
60        }
61    }
62
63    /// Borrows each element mutably and returns an array of mutable references
64    /// with the same size as self.
65    pub const fn each_mut(&mut self) -> VtlArray<&mut T, N> {
66        VtlArray {
67            data: self.data.each_mut(),
68        }
69    }
70
71    /// Returns the raw underlying array.
72    pub fn into_inner(self) -> [T; N] {
73        self.data
74    }
75}
76
77impl<T> From<[T; 1]> for VtlArray<T, 1> {
78    fn from(a: [T; 1]) -> Self {
79        Self { data: a }
80    }
81}
82
83impl<T> From<[T; 2]> for VtlArray<T, 2> {
84    fn from(a: [T; 2]) -> Self {
85        Self { data: a }
86    }
87}
88
89impl<T> From<[T; 3]> for VtlArray<T, 3> {
90    fn from(a: [T; 3]) -> Self {
91        Self { data: a }
92    }
93}
94
95// TODO: Remove this when deriving Default for arrays is stable
96impl<T, const N: usize> Default for VtlArray<T, N>
97where
98    T: Default,
99{
100    fn default() -> Self {
101        Self::from_fn(|_| T::default())
102    }
103}
104
105impl<T, const N: usize> InspectMut for VtlArray<T, N>
106where
107    T: InspectMut,
108{
109    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
110        let mut resp = req.respond();
111        for (i, data) in self.data.iter_mut().enumerate() {
112            resp.field_mut(&i.to_string(), data);
113        }
114    }
115}
116
117impl<T, V: Into<Vtl>, const N: usize> Index<V> for VtlArray<T, N> {
118    type Output = T;
119
120    fn index(&self, index: V) -> &Self::Output {
121        &self.data[index.into() as usize]
122    }
123}
124
125impl<T, V: Into<Vtl>, const N: usize> IndexMut<V> for VtlArray<T, N> {
126    fn index_mut(&mut self, index: V) -> &mut Self::Output {
127        &mut self.data[index.into() as usize]
128    }
129}
130
131impl<T, const N: usize> Deref for VtlArray<T, N> {
132    type Target = [T; N];
133
134    fn deref(&self) -> &Self::Target {
135        &self.data
136    }
137}
138
139impl<T, const N: usize> DerefMut for VtlArray<T, N> {
140    fn deref_mut(&mut self) -> &mut Self::Target {
141        &mut self.data
142    }
143}
144
145/// A set of [`Vtl`]s.
146#[derive(Copy, Clone, Inspect)]
147#[inspect(transparent(with = "|bits| inspect::iter_by_index(bits.iter().map(|v| *v))"))]
148pub struct VtlSet {
149    bits: BitArray<u16>,
150}
151
152impl VtlSet {
153    /// Creates a new empty set.
154    pub fn new() -> Self {
155        Self {
156            bits: BitArray::new(0),
157        }
158    }
159
160    /// Adds a [`Vtl`] to the set.
161    pub fn set(&mut self, vtl: Vtl) {
162        self.bits.set(vtl as usize, true);
163    }
164
165    /// Removes a [`Vtl`] from the set.
166    pub fn clear(&mut self, vtl: Vtl) {
167        self.bits.set(vtl as usize, false);
168    }
169
170    /// Returns true if any [`Vtl`] in the set is higher than `vtl`.
171    pub fn is_higher_vtl_set_than(&self, vtl: Vtl) -> bool {
172        self.highest_set() > Some(vtl)
173    }
174
175    /// Returns the highest set [`Vtl`] in the set, if any.
176    pub fn highest_set(&self) -> Option<Vtl> {
177        Some(Vtl::try_from(self.bits.last_one()? as u8).unwrap())
178    }
179
180    /// Returns true if the given [`Vtl`] is set.
181    pub fn is_set<V: Into<Vtl>>(&self, vtl: V) -> bool {
182        self.bits[vtl.into() as usize]
183    }
184
185    /// Returns true if the given [`Vtl`] is not set.
186    pub fn is_clear<V: Into<Vtl>>(&self, vtl: V) -> bool {
187        !self.is_set(vtl)
188    }
189
190    /// Returns an iterator over the set [`Vtl`]s, in order from highest to lowest.
191    pub fn iter_highest_first(&self) -> impl Iterator<Item = Vtl> + '_ {
192        self.bits
193            .iter_ones()
194            .rev()
195            .map(|i| Vtl::try_from(i as u8).unwrap())
196    }
197
198    /// Sets the given [`Vtl`] in the set and returns self.
199    pub fn with_vtl(mut self, vtl: Vtl) -> Self {
200        self.set(vtl);
201        self
202    }
203}
204
205impl From<u16> for VtlSet {
206    fn from(bits: u16) -> Self {
207        VtlSet {
208            bits: BitArray::new(bits),
209        }
210    }
211}
212
213impl From<VtlSet> for u16 {
214    fn from(set: VtlSet) -> Self {
215        set.bits.into_inner()
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::VtlSet;
222    use hvdef::Vtl;
223    use test_with_tracing::test;
224
225    #[test]
226    fn highest_vtl_matches_reverse_iteration() {
227        for bits in 0..8 {
228            let set = VtlSet::from(bits);
229            assert_eq!(set.highest_set(), set.iter_highest_first().next());
230        }
231    }
232
233    #[test]
234    fn test_vtlset() {
235        let mut set = VtlSet::new();
236        assert_eq!(set.highest_set(), None);
237        set.set(Vtl::Vtl0);
238        assert_eq!(set.highest_set(), Some(Vtl::Vtl0));
239        set.set(Vtl::Vtl2);
240        assert_eq!(set.highest_set(), Some(Vtl::Vtl2));
241
242        {
243            let mut iter = set.iter_highest_first();
244            assert_eq!(iter.next(), Some(Vtl::Vtl2));
245            assert_eq!(iter.next(), Some(Vtl::Vtl0));
246            assert_eq!(iter.next(), None);
247        }
248
249        assert!(!set.is_higher_vtl_set_than(Vtl::Vtl2));
250        assert!(set.is_higher_vtl_set_than(Vtl::Vtl1));
251        assert!(set.is_higher_vtl_set_than(Vtl::Vtl0));
252
253        set.clear(Vtl::Vtl2);
254        assert!(!set.is_higher_vtl_set_than(Vtl::Vtl0));
255    }
256}