small_sorted_set 1.0.1

A `SmallVec`-backed, sorted vec, with no duplicate elements
Documentation
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/*
    small_sorted_set: A `SmallVec`-backed, sorted vec, with no duplicate elements
    Copyright (C) 2026 bigwingbeat

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#![doc = include_str!("../README.md")]
#![no_std]

extern crate alloc;

use alloc::vec::Vec;
use core::{
    borrow::Borrow,
    hash::{Hash, Hasher},
    ops::{Deref, Index, RangeBounds},
    slice::SliceIndex,
};

use smallvec::SmallVec;

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A collection that guarantees its elements are always in sorted order, and that there are no duplicate elements.
/// Is stored inline on the stack for up to `N` elements, beyond which it automatically spills over to a heap allocation.
///
/// A bit like a [`BTreeSet`](alloc::collections::BTreeSet), but backed by a single sorted [`SmallVec<[T; N]>`](SmallVec) instead
/// of a tree of nodes. This makes it simpler, and faster to construct and read from, in exchange for mutations possibly being slower.
#[derive(Clone, Eq, PartialOrd, Ord, Debug)]
pub struct SmallSortedSet<T, const N: usize> {
    vec: SmallVec<[T; N]>,
}

impl<T, const N: usize> SmallSortedSet<T, N> {
    /// Constructs a new, empty `SmallSortedSet`.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self {
            vec: SmallVec::new(),
        }
    }

    /// Constructs a new, empty `SmallSortedSet`, with the specified capacity pre-allocated.
    ///
    /// Will only create a heap allocation if `capacity` is larger than the inline capacity `N`.
    #[must_use]
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            vec: SmallVec::with_capacity(capacity),
        }
    }

    /// Returns a reference to the inner `SmallVec`.
    #[inline]
    pub const fn as_vec(&self) -> &SmallVec<[T; N]> {
        &self.vec
    }

    /// Consume `self` and return ownership of the sorted inner `SmallVec`.
    #[must_use]
    #[inline]
    pub fn into_vec(self) -> SmallVec<[T; N]> {
        self.vec
    }

    /// Reserve capacity for `additional` more elements to be inserted.
    ///
    /// May reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the capacity computation overflows `usize`.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.vec.reserve(additional);
    }

    /// Reserve the minimum capacity for `additional` more elements to be inserted.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `usize`.
    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.vec.reserve_exact(additional);
    }

    /// Shrink the capacity of the collection as much as possible.
    ///
    /// When possible, this will move data from an external heap buffer to the collection's inline storage.
    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit();
    }

    /// Returns the number of items the collection can hold without reallocating.
    #[inline]
    pub fn capacity(&self) -> usize {
        self.vec.capacity()
    }

    // We have an inherent method for this, rather than forwarding to [`Slice::len`] via `Deref`, because `SmallVec` does too I guess
    /// Returns the number of elements in the collection.
    #[inline]
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    // This is really just to get Clippy to shut up
    /// Returns `true` if the collection is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Removes and returns the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    #[inline]
    pub fn remove_at(&mut self, index: usize) -> T {
        self.vec.remove(index)
    }

    /// Removes and returns the element at the given index.
    ///
    /// If the given index is out of bounds, returns `None`.
    #[inline]
    pub fn try_remove_at(&mut self, index: usize) -> Option<T> {
        if index >= self.vec.len() {
            return None;
        }
        Some(self.vec.remove(index))
    }

    /// Removes and returns the last element, or `None` if the collection is empty.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        self.vec.pop()
    }

    /// Clears the collection, removing all values.
    #[inline]
    pub fn clear(&mut self) {
        self.vec.clear();
    }

    /// Shrinks the collection to `len` elements, dropping everything at and after that index.
    ///
    /// If the given length is greater than or equal to the current number of elements, this does nothing.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.vec.truncate(len);
    }

    /// Removes a range of elements, returning a double-ended iterator over the removed subslice.
    ///
    /// # Panics
    ///
    /// Panics if the starting point is greater than the end point or if
    /// the end point is greater than the length of the collection.
    #[inline]
    pub fn drain(&mut self, range: impl RangeBounds<usize>) -> smallvec::Drain<'_, [T; N]> {
        self.vec.drain(range)
    }

    /// Retains only the elements for which `F` returns `true`, removing all other elements.
    #[inline]
    pub fn retain(&mut self, mut f: impl FnMut(&T) -> bool) {
        // For some stupid reason `SmallVec::retain` passes `&mut T` instead of `&T` despite also having a
        // separate `retain_mut` method. We can't expose mutable references to elements as that could allow
        // changing their sort order, thus violating our invariants.
        self.vec.retain(|t| f(t));
    }

    /// Directly inserts the given element at the given index, without checking for correct sort order.
    ///
    /// # Safety
    ///
    /// The collection must still be sorted after the given element is inserted at the given index,
    /// and the given element must not compare equal to any other element already in the collection.
    ///
    /// # Panics
    ///
    /// Panics if the given index is out of bounds.
    #[inline]
    pub unsafe fn insert_at(&mut self, index: usize, element: T) {
        self.vec.insert(index, element);
    }

    // Waiting on SmallVec to update to add this method
    // /// Directly inserts the given element at the given index, without checking for correct sort order.
    // ///
    // /// Returns a reference to the new element.
    // ///
    // /// # Safety
    // ///
    // /// The collection must still be sorted after the given element is inserted at the given index,
    // /// and the given element must not compare equal to any other element already in the collection.
    // ///
    // /// # Panics
    // ///
    // /// Panics if the given index is out of bounds.
    // #[must_use = "if you don't need a reference to the value, use `SortedSet::insert_at` instead"]
    // #[inline]
    // pub unsafe fn insert_at_mut(&mut self, index: usize, element: T) -> &mut T {
    //     self.vec.insert_mut(index, element)
    // }
}

impl<T: Ord, const N: usize> SmallSortedSet<T, N> {
    /// Constructs a new `SmallSortedSet` from the specified collection, by sorting and deduplicating the contained elements.
    #[must_use]
    pub fn from_unsorted(mut vec: SmallVec<[T; N]>) -> Self {
        vec.sort_unstable();
        vec.dedup();
        Self { vec }
    }

    /// Constructs a new `SmallSortedSet` from the specified collection, by sorting and deduplicating the contained elements.
    #[must_use]
    #[inline]
    pub fn from_unsorted_vec(vec: Vec<T>) -> Self {
        Self::from_unsorted(vec.into())
    }

    // We have an inherent method for this, rather than forwarding to [`Slice::contains`] via `Deref`, to avoid the linear scan
    /// Returns `true` if the given element is present in the collection.
    #[must_use]
    #[inline]
    pub fn contains(&self, element: &T) -> bool {
        self.vec.binary_search(element).is_ok()
    }

    /// Inserts the given element into sorted position.
    ///
    /// This returns `Ok` if the element was successfully inserted, and returns `Err`
    /// if the element was already present, in both cases carrying the index of the element.
    pub fn insert(&mut self, element: T) -> Result<usize, usize> {
        // The return value of `binary_search` is the opposite of what we want, as it returns `Ok` if its already present etc.
        match self.vec.binary_search(&element) {
            Ok(i) => Err(i),
            Err(i) => {
                self.vec.insert(i, element);
                Ok(i)
            }
        }
    }

    /// Removes the given element, if it is present.
    ///
    /// Returns `Ok` if the element was successfully removed, with the (former) index of the element.
    /// If the element was not present, returns `Err` and the index that the element would have been at.
    pub fn remove(&mut self, element: &T) -> Result<usize, usize> {
        let result = self.vec.binary_search(element);
        if let Ok(i) = result {
            self.vec.remove(i);
        }
        result
    }
}

impl<T: Ord + Clone, const N: usize> SmallSortedSet<T, N> {
    /// Constructs a new `SmallSortedSet` from the specified slice, by cloning, sorting, and deduplicating the contained elements.
    #[inline]
    pub fn from_unsorted_slice(slice: &[T]) -> Self {
        Self::from_unsorted(slice.into())
    }
}

impl<T, const N: usize> Default for SmallSortedSet<T, N> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Ord, const N: usize> From<SmallVec<[T; N]>> for SmallSortedSet<T, N> {
    #[inline]
    fn from(unsorted: SmallVec<[T; N]>) -> Self {
        Self::from_unsorted(unsorted)
    }
}

impl<T: Ord, const N: usize> From<Vec<T>> for SmallSortedSet<T, N> {
    #[inline]
    fn from(unsorted: Vec<T>) -> Self {
        Self::from_unsorted_vec(unsorted)
    }
}

impl<T: Ord + Clone, const N: usize> From<&[T]> for SmallSortedSet<T, N> {
    #[inline]
    fn from(unsorted: &[T]) -> Self {
        Self::from_unsorted_slice(unsorted)
    }
}

// Like with `SmallVec`, this provides a lot of useful methods that we would otherwise have to impl ourselves.
// Note that unlike `SmallVec`, we do not also impl `DerefMut`, as that would allow violating both of our invariants.
impl<T, const N: usize> Deref for SmallSortedSet<T, N> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &[T] {
        &self.vec
    }
}

// Ditto for not also implementing `AsMut`
impl<T, const N: usize> AsRef<[T]> for SmallSortedSet<T, N> {
    #[inline]
    fn as_ref(&self) -> &[T] {
        &self.vec
    }
}

impl<T, const N: usize> AsRef<SmallVec<[T; N]>> for SmallSortedSet<T, N> {
    #[inline]
    fn as_ref(&self) -> &SmallVec<[T; N]> {
        &self.vec
    }
}

// Ditto ditto for not also implementing `BorrowMut`
impl<T, const N: usize> Borrow<[T]> for SmallSortedSet<T, N> {
    #[inline]
    fn borrow(&self) -> &[T] {
        &self.vec
    }
}

// Ditto ditto ditto for not also implementing `IndexMut`
impl<T, I: SliceIndex<[T]>, const N: usize> Index<I> for SmallSortedSet<T, N> {
    type Output = I::Output;

    #[inline]
    fn index(&self, index: I) -> &Self::Output {
        self.vec.index(index)
    }
}

impl<A: Ord, const N: usize> Extend<A> for SmallSortedSet<A, N> {
    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
        self.vec.extend(iter);
        // Prefer stable sort to unstable sort here as we know the extended vec is already sorted up to the new elements
        self.vec.sort();
        self.vec.dedup();
    }
}

impl<A: Ord, const N: usize> FromIterator<A> for SmallSortedSet<A, N> {
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
        let vec = SmallVec::from_iter(iter);
        Self::from_unsorted(vec)
    }
}

impl<T, const N: usize> IntoIterator for SmallSortedSet<T, N> {
    type Item = T;
    type IntoIter = smallvec::IntoIter<[T; N]>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.vec.into_iter()
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a SmallSortedSet<T, N> {
    type Item = &'a T;
    type IntoIter = core::slice::Iter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.vec.iter()
    }
}

impl<T, U, const TN: usize, const UN: usize> PartialEq<SmallSortedSet<U, UN>>
    for SmallSortedSet<T, TN>
where
    T: PartialEq<U>,
{
    #[inline]
    fn eq(&self, other: &SmallSortedSet<U, UN>) -> bool {
        self.vec == other.vec
    }
}

impl<T: Hash, const N: usize> Hash for SmallSortedSet<T, N> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.vec.hash(state);
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<T, const N: usize> Serialize for SmallSortedSet<T, N>
where
    T: Serialize,
{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.vec.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T, const N: usize> Deserialize<'de> for SmallSortedSet<T, N>
where
    T: Deserialize<'de> + Ord,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        SmallVec::deserialize(deserializer).map(Self::from_unsorted)
    }
}

#[cfg(test)]
mod tests {
    use core::assert_matches;

    use smallvec::smallvec;

    const TEST_INLINE_SIZE: usize = 6;
    type SmallVec = smallvec::SmallVec<[i32; TEST_INLINE_SIZE]>;
    type SmallSortedSet = super::SmallSortedSet<i32, TEST_INLINE_SIZE>;

    #[test]
    fn from_unsorted() {
        let unsorted = smallvec![5, 0, 2, 4, 3, 1, 5, 2, 0, 3, 4, 5, 1, 2, 4, 0, 3];
        let sorted: SmallVec = smallvec![0, 1, 2, 3, 4, 5];
        let a = SmallSortedSet::from_unsorted(unsorted);
        let mut b = SmallSortedSet::new();
        b.extend(sorted);
        assert_eq!(a, b);
    }

    #[test]
    fn insert() {
        let mut vec = SmallSortedSet::new();
        assert_matches!(vec.insert(5), Result::Ok(0));
        assert_matches!(vec.insert(0), Result::Ok(0));
        assert_matches!(vec.insert(2), Result::Ok(1));
        assert_matches!(vec.insert(4), Result::Ok(2));
        assert_matches!(vec.insert(3), Result::Ok(2));
        assert_matches!(vec.insert(1), Result::Ok(1));
        assert_matches!(vec.insert(5), Result::Err(5));
        assert_matches!(vec.insert(2), Result::Err(2));
        assert_matches!(vec.insert(0), Result::Err(0));
        assert_matches!(vec.insert(3), Result::Err(3));
        assert_matches!(vec.insert(4), Result::Err(4));
        assert_matches!(vec.insert(5), Result::Err(5));
        assert_matches!(vec.insert(1), Result::Err(1));
        assert_matches!(vec.insert(2), Result::Err(2));
        assert_matches!(vec.insert(4), Result::Err(4));
        assert_matches!(vec.insert(0), Result::Err(0));
        assert_matches!(vec.insert(3), Result::Err(3));
    }

    #[test]
    fn remove() {
        let mut vec = SmallSortedSet::new();
        let sorted: SmallVec = smallvec![0, 1, 2, 3, 4, 5];
        vec.extend(sorted);

        assert_matches!(vec.remove(&5), Result::Ok(5));
        assert_matches!(vec.remove(&5), Result::Err(5));
        assert_matches!(vec.remove(&0), Result::Ok(0));
        assert_matches!(vec.remove(&0), Result::Err(0));
        assert_matches!(vec.remove(&2), Result::Ok(1));
        assert_matches!(vec.remove(&2), Result::Err(1));
        assert_matches!(vec.remove(&4), Result::Ok(2));
        assert_matches!(vec.remove(&4), Result::Err(2));
        assert_matches!(vec.remove(&3), Result::Ok(1));
        assert_matches!(vec.remove(&3), Result::Err(1));
        assert_matches!(vec.remove(&1), Result::Ok(0));
        assert_matches!(vec.remove(&1), Result::Err(0));

        assert_matches!(vec.remove(&0), Result::Err(0));
        assert_matches!(vec.remove(&1), Result::Err(0));
        assert_matches!(vec.remove(&2), Result::Err(0));
        assert_matches!(vec.remove(&3), Result::Err(0));
        assert_matches!(vec.remove(&4), Result::Err(0));
        assert_matches!(vec.remove(&5), Result::Err(0));
    }

    #[test]
    fn extend() {
        let sorted: SmallVec = smallvec![1, 2, 4, 5, 8, 9];
        let mut vec = SmallSortedSet::new();
        vec.extend(sorted.iter().copied());

        assert_eq!(vec.as_vec(), &sorted);

        let duplicates: SmallVec = smallvec![
            8, 1, 4, 2, 9, 5, 4, 9, 8, 2, 1, 5, 4, 8, 9, 1, 5, 2, 4, 2, 8, 5, 9
        ];

        vec.extend(duplicates);

        assert_eq!(vec.as_vec(), &sorted);

        let new: SmallVec = smallvec![10, 3, 0, 6, 0, 7, 11, 3, 6];

        vec.extend(new);

        let expected: SmallVec = smallvec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

        assert_eq!(vec.as_vec(), &expected);
    }
}