rkyv/collections/
btree_set.rs

1//! [`Archive`](crate::Archive) implementation for B-tree sets.
2
3use crate::collections::btree_map::{ArchivedBTreeMap, BTreeMapResolver, Keys};
4use core::{borrow::Borrow, fmt};
5
6/// An archived `BTreeSet`. This is a wrapper around a B-tree map with the same key and a value of
7/// `()`.
8#[cfg_attr(feature = "validation", derive(bytecheck::CheckBytes))]
9#[derive(Eq, Hash, Ord, PartialEq, PartialOrd)]
10#[repr(transparent)]
11pub struct ArchivedBTreeSet<K>(ArchivedBTreeMap<K, ()>);
12
13impl<K> ArchivedBTreeSet<K> {
14    /// Returns `true` if the set contains a value for the specified key.
15    ///
16    /// The key may be any borrowed form of the set's key type, but the ordering on the borrowed
17    /// form _must_ match the ordering on the key type.
18    #[inline]
19    pub fn contains_key<Q: Ord + ?Sized>(&self, key: &Q) -> bool
20    where
21        K: Borrow<Q> + Ord,
22    {
23        self.0.contains_key(key)
24    }
25
26    /// Returns a reference to the value int he set, if any, that is equal to the given value.
27    ///
28    /// The value may be any borrowed form of the set's value type, but the ordering on the borrowed
29    /// form _must_ match the ordering on the value type.
30    #[inline]
31    pub fn get<Q: Ord + ?Sized>(&self, value: &Q) -> Option<&K>
32    where
33        K: Borrow<Q> + Ord,
34    {
35        self.0.get_key_value(value).map(|(key, _)| key)
36    }
37
38    /// Returns `true` if the set contains no elements.
39    #[inline]
40    pub fn is_empty(&self) -> bool {
41        self.0.is_empty()
42    }
43
44    /// Gets an iterator over the keys of the set, in sorted order.
45    #[inline]
46    pub fn iter(&self) -> Keys<K, ()> {
47        self.0.keys()
48    }
49
50    /// Returns the number of items in the archived B-tree set.
51    #[inline]
52    pub fn len(&self) -> usize {
53        self.0.len()
54    }
55
56    /// Resolves a B-tree set from its length.
57    ///
58    /// # Safety
59    ///
60    /// - `len` must be the number of elements that were serialized
61    /// - `pos` must be the position of `out` within the archive
62    /// - `resolver` must be the result of serializing a B-tree set
63    #[inline]
64    pub unsafe fn resolve_from_len(
65        len: usize,
66        pos: usize,
67        resolver: BTreeSetResolver,
68        out: *mut Self,
69    ) {
70        let (fp, fo) = out_field!(out.0);
71        ArchivedBTreeMap::resolve_from_len(len, pos + fp, resolver.0, fo);
72    }
73}
74
75#[cfg(feature = "alloc")]
76const _: () = {
77    use crate::{ser::Serializer, Serialize};
78
79    impl<K> ArchivedBTreeSet<K> {
80        /// Serializes an ordered iterator of key-value pairs as a B-tree map.
81        ///
82        /// # Safety
83        ///
84        /// - Keys returned by the iterator must be unique
85        /// - Keys must be in reverse sorted order from last to first
86        pub unsafe fn serialize_from_reverse_iter<'a, UK, S, I>(
87            iter: I,
88            serializer: &mut S,
89        ) -> Result<BTreeSetResolver, S::Error>
90        where
91            UK: 'a + Serialize<S, Archived = K>,
92            S: Serializer + ?Sized,
93            I: ExactSizeIterator<Item = &'a UK>,
94        {
95            Ok(BTreeSetResolver(
96                ArchivedBTreeMap::serialize_from_reverse_iter(iter.map(|x| (x, &())), serializer)?,
97            ))
98        }
99    }
100};
101
102impl<K: fmt::Debug> fmt::Debug for ArchivedBTreeSet<K> {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.debug_set().entries(self.iter()).finish()
105    }
106}
107
108impl<'a, K> IntoIterator for &'a ArchivedBTreeSet<K> {
109    type Item = &'a K;
110    type IntoIter = Keys<'a, K, ()>;
111
112    fn into_iter(self) -> Self::IntoIter {
113        self.iter()
114    }
115}
116
117/// The resolver for archived B-tree sets.
118pub struct BTreeSetResolver(BTreeMapResolver);