guppy/
sorted_set.rs
1use std::{fmt, iter::FromIterator, ops::Deref};
5
6#[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 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 pub fn contains(&self, item: &T) -> bool {
31 self.binary_search(item).is_ok()
32 }
33
34 pub fn as_slice(&self) -> &[T] {
36 &self.inner
37 }
38
39 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}