fixed_queue/
linear_set.rs

1//! Set
2
3use crate::vec::Vec;
4use core::borrow::{Borrow, BorrowMut};
5use core::convert::{AsMut, AsRef};
6use core::ops;
7
8pub struct LinearSet<T, const N: usize> {
9    vec: Vec<T, N>,
10}
11impl<T, const N: usize> LinearSet<T, N> {
12    const CAPACITY: usize = N;
13    pub const fn new() -> Self {
14        LinearSet { vec: Vec::new() }
15    }
16    pub fn capacity(&self) -> usize {
17        Self::CAPACITY
18    }
19}
20impl<T: PartialEq, const N: usize> LinearSet<T, N> {
21    pub fn get_index(&self, value: &T) -> Option<usize> {
22        if let Some((i, _item)) = self.iter().enumerate().find(|(_i, item)| item == &value) {
23            Some(i)
24        } else {
25            None
26        }
27    }
28    pub fn get(&self, value: &T) -> Option<&T> {
29        if let Some(i) = self.get_index(value) {
30            Some(&self[i])
31        } else {
32            None
33        }
34    }
35    pub fn contains(&self, value: &T) -> bool {
36        self.iter().any(|x| x == value)
37    }
38    pub fn insert(&mut self, value: T) -> Result<bool, T> {
39        if let Some(_) = self.get_index(&value) {
40            Ok(false)
41        } else {
42            self.vec.push(value)?;
43            Ok(true)
44        }
45    }
46    pub fn remove(&mut self, value: &T) -> bool {
47        if let Some(i) = self.get_index(value) {
48            self.vec.swap_remove(i);
49            true
50        } else {
51            false
52        }
53    }
54}
55
56impl<T, const N: usize> ops::Deref for LinearSet<T, N> {
57    type Target = [T];
58
59    fn deref(&self) -> &[T] {
60        self.vec.deref()
61    }
62}
63impl<T, const N: usize> ops::DerefMut for LinearSet<T, N> {
64    fn deref_mut(&mut self) -> &mut [T] {
65        self.vec.deref_mut()
66    }
67}
68impl<T, const N: usize> AsRef<[T]> for LinearSet<T, N> {
69    fn as_ref(&self) -> &[T] {
70        self
71    }
72}
73impl<T, const N: usize> AsMut<[T]> for LinearSet<T, N> {
74    fn as_mut(&mut self) -> &mut [T] {
75        self
76    }
77}
78impl<T, const N: usize> Borrow<[T]> for LinearSet<T, N> {
79    fn borrow(&self) -> &[T] {
80        &self[..]
81    }
82}
83impl<T, const N: usize> BorrowMut<[T]> for LinearSet<T, N> {
84    fn borrow_mut(&mut self) -> &mut [T] {
85        &mut self[..]
86    }
87}