summaryrefslogtreecommitdiffstats
path: root/vendor/tinyvec/src-backup/arrayset.rs
blob: 22ea7cae94e1e6b823e86e2161a212b19f93e69f (plain)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#![cfg(feature = "experimental_array_set")]

// This was contributed by user `dhardy`! Big thanks.

use super::{take, Array};
use core::{
  borrow::Borrow,
  fmt,
  mem::swap,
  ops::{AddAssign, SubAssign},
};

/// Error resulting from attempting to insert into a full array
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct InsertError;

// TODO(when std): impl std::error::Error for InsertError {}

impl fmt::Display for InsertError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "ArraySet: insertion failed")
  }
}

/// An array-backed set
///
/// This set supports `O(n)` operations and has a fixed size, thus may fail to
/// insert items. The potential advantage is a *really* small size.
///
/// The set is backed by an array of type `A` and indexed by type `L`.
/// The item type must support `Default`.
/// Due to restrictions, `L` may be only `u8` or `u16`.
#[derive(Clone, Debug, Default)]
pub struct ArraySet<A: Array, L> {
  arr: A,
  len: L,
}

impl<A: Array + Default, L: From<u8>> ArraySet<A, L> {
  /// Constructs a new, empty, set
  #[inline]
  pub fn new() -> Self {
    ArraySet { arr: Default::default(), len: 0.into() }
  }
}

impl<A: Array, L: Copy + Into<usize>> ArraySet<A, L> {
  /// Constructs a new set from given inputs
  ///
  /// Panics if `len> arr.len()`.
  #[inline]
  pub fn from(arr: A, len: L) -> Self {
    if len.into() > A::CAPACITY {
      panic!("ArraySet::from(array, len): len > array.len()");
    }
    ArraySet { arr, len }
  }
}

impl<A: Array, L> ArraySet<A, L>
where
  L: Copy + PartialEq + From<u8> + Into<usize>,
{
  /// Returns the fixed capacity of the set
  #[inline]
  pub fn capacity(&self) -> usize {
    A::CAPACITY
  }

  /// Returns the number of elements in the set
  #[inline]
  pub fn len(&self) -> usize {
    self.len.into()
  }

  /// Returns true when the set contains no elements
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len == 0.into()
  }

  /// Removes all elements
  #[inline]
  pub fn clear(&mut self) {
    self.len = 0.into();
  }

  /// Iterate over all contents
  #[inline]
  pub fn iter(&self) -> Iter<A::Item> {
    Iter { a: self.arr.as_slice(), i: 0 }
  }
}

impl<A: Array, L> ArraySet<A, L>
where
  L: Copy + PartialOrd + AddAssign + SubAssign + From<u8> + Into<usize>,
{
  /// Check whether the set contains `elt`
  #[inline]
  pub fn contains<Q: Eq + ?Sized>(&self, elt: &Q) -> bool
  where
    A::Item: Borrow<Q>,
  {
    self.get(elt).is_some()
  }

  /// Get a reference to a contained item matching `elt`
  pub fn get<Q: Eq + ?Sized>(&self, elt: &Q) -> Option<&A::Item>
  where
    A::Item: Borrow<Q>,
  {
    let len: usize = self.len.into();
    let arr = self.arr.as_slice();
    for i in 0..len {
      if arr[i].borrow() == elt {
        return Some(&arr[i]);
      }
    }
    None
  }

  /// Remove an item matching `elt`, if any
  pub fn remove<Q: Eq + ?Sized>(&mut self, elt: &Q) -> Option<A::Item>
  where
    A::Item: Borrow<Q>,
  {
    let len: usize = self.len.into();
    let arr = self.arr.as_slice_mut();
    for i in 0..len {
      if arr[i].borrow() == elt {
        let l1 = len - 1;
        if i < l1 {
          arr.swap(i, l1);
        }
        self.len -= L::from(1);
        return Some(take(&mut arr[l1]));
      }
    }
    None
  }

  /// Remove any items for which `f(item) == false`
  pub fn retain<F>(&mut self, mut f: F)
  where
    F: FnMut(&A::Item) -> bool,
  {
    let mut len = self.len;
    let arr = self.arr.as_slice_mut();
    let mut i = 0;
    while i < len.into() {
      if !f(&arr[i]) {
        len -= L::from(1);
        if i < len.into() {
          arr.swap(i, len.into());
        }
      } else {
        i += 1;
      }
    }
    self.len = len;
  }
}

impl<A: Array, L> ArraySet<A, L>
where
  A::Item: Eq,
  L: Copy + PartialOrd + AddAssign + SubAssign + From<u8> + Into<usize>,
{
  /// Insert an item
  ///
  /// Due to the fixed size of the backing array, insertion may fail.
  #[inline]
  pub fn insert(&mut self, elt: A::Item) -> Result<bool, InsertError> {
    if self.contains(&elt) {
      return Ok(false);
    }

    let len = self.len.into();
    let arr = self.arr.as_slice_mut();
    if len >= arr.len() {
      return Err(InsertError);
    }
    arr[len] = elt;
    self.len += L::from(1);
    Ok(true)
  }

  /* Hits borrow checker
  pub fn get_or_insert(&mut self, elt: A::Item) -> Result<&A::Item, InsertError> {
      if let Some(r) = self.get(&elt) {
          return Ok(r);
      }
      self.insert(elt)?;
      let len: usize = self.len.into();
      Ok(&self.arr.as_slice()[len - 1])
  }
  */

  /// Replace an item matching `elt` with `elt`, or insert `elt`
  ///
  /// Returns the replaced item, if any. Fails when there is no matching item
  /// and the backing array is full, preventing insertion.
  pub fn replace(
    &mut self,
    mut elt: A::Item,
  ) -> Result<Option<A::Item>, InsertError> {
    let len: usize = self.len.into();
    let arr = self.arr.as_slice_mut();
    for i in 0..len {
      if arr[i] == elt {
        swap(&mut arr[i], &mut elt);
        return Ok(Some(elt));
      }
    }

    if len >= arr.len() {
      return Err(InsertError);
    }
    arr[len] = elt;
    self.len += L::from(1);
    Ok(None)
  }
}

/// Type returned by [`ArraySet::iter`]
pub struct Iter<'a, T> {
  a: &'a [T],
  i: usize,
}

impl<'a, T> ExactSizeIterator for Iter<'a, T> {
  #[inline]
  fn len(&self) -> usize {
    self.a.len() - self.i
  }
}

impl<'a, T> Iterator for Iter<'a, T> {
  type Item = &'a T;

  #[inline]
  fn next(&mut self) -> Option<Self::Item> {
    if self.i < self.a.len() {
      let i = self.i;
      self.i += 1;
      Some(&self.a[i])
    } else {
      None
    }
  }

  #[inline]
  fn size_hint(&self) -> (usize, Option<usize>) {
    let len = self.len();
    (len, Some(len))
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use core::mem::size_of;

  #[test]
  fn test_size() {
    assert_eq!(size_of::<ArraySet<[i8; 7], u8>>(), 8);
  }

  #[test]
  fn test() {
    let mut set: ArraySet<[i8; 7], u8> = ArraySet::new();
    assert_eq!(set.capacity(), 7);

    assert_eq!(set.insert(1), Ok(true));
    assert_eq!(set.insert(5), Ok(true));
    assert_eq!(set.insert(6), Ok(true));
    assert_eq!(set.len(), 3);

    assert_eq!(set.insert(5), Ok(false));
    assert_eq!(set.len(), 3);

    assert_eq!(set.replace(1), Ok(Some(1)));
    assert_eq!(set.replace(2), Ok(None));
    assert_eq!(set.len(), 4);

    assert_eq!(set.insert(3), Ok(true));
    assert_eq!(set.insert(4), Ok(true));
    assert_eq!(set.insert(7), Ok(true));
    assert_eq!(set.insert(8), Err(InsertError));
    assert_eq!(set.len(), 7);

    assert_eq!(set.replace(9), Err(InsertError));

    assert_eq!(set.remove(&3), Some(3));
    assert_eq!(set.len(), 6);

    set.retain(|x| *x == 3 || *x == 6);
    assert_eq!(set.len(), 1);
    assert!(!set.contains(&3));
    assert!(set.contains(&6));
  }
}