guppy/
sorted_set.rs

1// Copyright (c) The cargo-guppy Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::{fmt, iter::FromIterator, ops::Deref};
5
6/// An immutable set stored as a sorted vector.
7#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
8pub struct SortedSet<T> {
9    inner: Box<[T]>,
10}
11
12type _SortedSetCovariant<'a> = SortedSet<&'a ()>;
13assert_covariant!(_SortedSetCovariant);
14
15impl<T> SortedSet<T>
16where
17    T: Ord,
18{
19    /// Creates a new `SortedSet` from a vector or other slice container.
20    pub fn new(v: impl Into<Vec<T>>) -> Self {
21        let mut v = v.into();
22        v.sort();
23        v.dedup();
24        Self { inner: v.into() }
25    }
26
27    // TODO: new + sort by/sort by key?
28
29    /// Returns true if this sorted vector contains this element.
30    pub fn contains(&self, item: &T) -> bool {
31        self.binary_search(item).is_ok()
32    }
33
34    /// Returns the data as a slice.
35    pub fn as_slice(&self) -> &[T] {
36        &self.inner
37    }
38
39    /// Returns the inner data.
40    pub fn into_inner(self) -> Box<[T]> {
41        self.inner
42    }
43}
44
45impl<T> FromIterator<T> for SortedSet<T>
46where
47    T: Ord,
48{
49    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
50        let v: Vec<T> = iter.into_iter().collect();
51        Self::new(v)
52    }
53}
54
55impl<T> Deref for SortedSet<T> {
56    type Target = [T];
57
58    fn deref(&self) -> &Self::Target {
59        &self.inner
60    }
61}
62
63impl fmt::Display for SortedSet<String> {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        write!(f, "{{{}}}", self.as_slice().join(", "))
66    }
67}