fixed_map/set.rs
1//! Contains the fixed [`Set`] implementation.
2
3use core::cmp::Ordering;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6
7pub mod intersection;
8pub mod storage;
9
10pub use self::intersection::Intersection;
11pub use self::storage::SetStorage;
12
13use crate::raw::RawStorage;
14use crate::Key;
15
16/// The iterator produced by [`Set::iter`].
17pub type Iter<'a, T> = <<T as Key>::SetStorage as SetStorage<T>>::Iter<'a>;
18
19/// The iterator produced by [`Set::into_iter`].
20pub type IntoIter<T> = <<T as Key>::SetStorage as SetStorage<T>>::IntoIter;
21
22/// A fixed set with storage specialized through the [`Key`] trait.
23///
24/// # Examples
25///
26/// ```
27/// use fixed_map::{Key, Set};
28///
29/// #[derive(Clone, Copy, Key)]
30/// enum Part {
31/// One,
32/// Two,
33/// }
34///
35/// #[derive(Clone, Copy, Key)]
36/// enum MyKey {
37/// Simple,
38/// Composite(Part),
39/// # #[cfg(feature = "hashbrown")]
40/// String(&'static str),
41/// # #[cfg(feature = "hashbrown")]
42/// Number(u32),
43/// Singleton(()),
44/// Option(Option<Part>),
45/// Boolean(bool),
46/// }
47///
48/// let mut set = Set::new();
49///
50/// set.insert(MyKey::Simple);
51/// set.insert(MyKey::Composite(Part::One));
52/// # #[cfg(feature = "hashbrown")]
53/// set.insert(MyKey::String("foo"));
54/// # #[cfg(feature = "hashbrown")]
55/// set.insert(MyKey::Number(1));
56/// set.insert(MyKey::Singleton(()));
57/// set.insert(MyKey::Option(None));
58/// set.insert(MyKey::Option(Some(Part::One)));
59/// set.insert(MyKey::Boolean(true));
60///
61/// assert!(set.contains(MyKey::Simple));
62/// assert!(set.contains(MyKey::Composite(Part::One)));
63/// assert!(!set.contains(MyKey::Composite(Part::Two)));
64/// # #[cfg(feature = "hashbrown")]
65/// assert!(set.contains(MyKey::String("foo")));
66/// # #[cfg(feature = "hashbrown")]
67/// assert!(!set.contains(MyKey::String("bar")));
68/// # #[cfg(feature = "hashbrown")]
69/// assert!(set.contains(MyKey::Number(1)));
70/// # #[cfg(feature = "hashbrown")]
71/// assert!(!set.contains(MyKey::Number(2)));
72/// assert!(set.contains(MyKey::Singleton(())));
73/// assert!(set.contains(MyKey::Option(None)));
74/// assert!(set.contains(MyKey::Option(Some(Part::One))));
75/// assert!(!set.contains(MyKey::Option(Some(Part::Two))));
76/// assert!(set.contains(MyKey::Boolean(true)));
77/// assert!(!set.contains(MyKey::Boolean(false)));
78/// ```
79#[repr(transparent)]
80pub struct Set<T>
81where
82 T: Key,
83{
84 storage: T::SetStorage,
85}
86
87/// A set implementation that uses fixed storage.
88///
89/// # Examples
90///
91/// ```
92/// use fixed_map::{Key, Set};
93///
94/// #[derive(Clone, Copy, Key)]
95/// enum MyKey {
96/// First,
97/// Second,
98/// }
99///
100/// let mut m = Set::new();
101/// m.insert(MyKey::First);
102///
103/// assert_eq!(m.contains(MyKey::First), true);
104/// assert_eq!(m.contains(MyKey::Second), false);
105/// ```
106///
107/// Using a composite key:
108///
109/// ```
110/// use fixed_map::{Key, Set};
111///
112/// #[derive(Clone, Copy, Key)]
113/// enum Part {
114/// A,
115/// B,
116/// }
117///
118/// #[derive(Clone, Copy, Key)]
119/// enum MyKey {
120/// Simple,
121/// Composite(Part),
122/// }
123///
124/// let mut m = Set::new();
125/// m.insert(MyKey::Simple);
126/// m.insert(MyKey::Composite(Part::A));
127///
128/// assert_eq!(m.contains(MyKey::Simple), true);
129/// assert_eq!(m.contains(MyKey::Composite(Part::A)), true);
130/// assert_eq!(m.contains(MyKey::Composite(Part::B)), false);
131/// ```
132impl<T> Set<T>
133where
134 T: Key,
135{
136 /// Creates an empty [`Set`].
137 ///
138 /// # Examples
139 ///
140 /// ```
141 /// use fixed_map::{Key, Set};
142 ///
143 /// #[derive(Clone, Copy, Key)]
144 /// enum MyKey {
145 /// One,
146 /// Two,
147 /// }
148 ///
149 /// let set: Set<MyKey> = Set::new();
150 /// ```
151 #[inline]
152 #[must_use]
153 pub fn new() -> Set<T> {
154 Set {
155 storage: T::SetStorage::empty(),
156 }
157 }
158
159 /// An iterator visiting all values in arbitrary order.
160 /// The iterator element type is `T`.
161 ///
162 /// # Examples
163 ///
164 /// ```
165 /// use fixed_map::{Key, Set};
166 ///
167 /// #[derive(Debug, Clone, Copy, Key, PartialEq, Eq)]
168 /// enum MyKey {
169 /// One,
170 /// Two,
171 /// Three,
172 /// }
173 ///
174 /// let mut set = Set::new();
175 /// set.insert(MyKey::One);
176 /// set.insert(MyKey::Two);
177 ///
178 /// assert_eq!(set.iter().collect::<Vec<_>>(), vec![MyKey::One, MyKey::Two]);
179 /// ```
180 #[inline]
181 pub fn iter(&self) -> Iter<'_, T> {
182 self.storage.iter()
183 }
184
185 /// Returns `true` if the set currently contains the given value.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use fixed_map::{Key, Set};
191 ///
192 /// #[derive(Clone, Copy, Key)]
193 /// enum MyKey {
194 /// One,
195 /// Two,
196 /// }
197 ///
198 /// let mut set = Set::new();
199 /// set.insert(MyKey::One);
200 /// assert_eq!(set.contains(MyKey::One), true);
201 /// assert_eq!(set.contains(MyKey::Two), false);
202 /// ```
203 #[inline]
204 pub fn contains(&self, value: T) -> bool {
205 self.storage.contains(value)
206 }
207
208 /// Adds a value to the set.
209 ///
210 /// If the set did not have this value present, `true` is returned.
211 ///
212 /// If the set did have this value present, `false` is returned.
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use fixed_map::{Key, Set};
218 ///
219 /// #[derive(Clone, Copy, Key)]
220 /// enum MyKey {
221 /// One,
222 /// Two,
223 /// }
224 ///
225 /// let mut set = Set::new();
226 /// assert!(set.insert(MyKey::One));
227 /// assert!(!set.is_empty());
228 ///
229 /// set.insert(MyKey::Two);
230 /// assert!(!set.insert(MyKey::Two));
231 /// assert!(set.contains(MyKey::Two));
232 /// ```
233 #[inline]
234 pub fn insert(&mut self, value: T) -> bool {
235 self.storage.insert(value)
236 }
237
238 /// Removes a value from the set. Returns `true` if the value was
239 /// present in the set.
240 ///
241 /// # Examples
242 ///
243 /// ```
244 /// use fixed_map::{Key, Set};
245 ///
246 /// #[derive(Clone, Copy, Key)]
247 /// enum MyKey {
248 /// One,
249 /// Two,
250 /// }
251 ///
252 /// let mut set = Set::new();
253 /// set.insert(MyKey::One);
254 /// assert_eq!(set.remove(MyKey::One), true);
255 /// assert_eq!(set.remove(MyKey::One), false);
256 /// ```
257 #[inline]
258 pub fn remove(&mut self, value: T) -> bool {
259 self.storage.remove(value)
260 }
261
262 /// Retains only the elements specified by the predicate.
263 ///
264 /// In other words, remove all elements e for which f(e) returns false.
265 /// The elements are visited in unsorted (and unspecified) order.
266 ///
267 /// # Examples
268 ///
269 /// ```
270 /// use fixed_map::{Key, Set};
271 ///
272 /// #[derive(Clone, Copy, Key)]
273 /// enum MyKey {
274 /// First,
275 /// Second,
276 /// }
277 ///
278 /// let mut set = Set::new();
279 ///
280 /// set.insert(MyKey::First);
281 /// set.insert(MyKey::Second);
282 ///
283 /// set.retain(|k| matches!(k, MyKey::First));
284 ///
285 /// assert_eq!(set.len(), 1);
286 /// assert_eq!(set.contains(MyKey::First), true);
287 /// assert_eq!(set.contains(MyKey::Second), false);
288 /// ```
289 ///
290 /// Using a composite key:
291 ///
292 /// ```
293 /// use fixed_map::{Key, Set};
294 ///
295 /// #[derive(Clone, Copy, Key)]
296 /// enum MyKey {
297 /// First(bool),
298 /// Second(bool),
299 /// }
300 ///
301 /// let mut set = Set::new();
302 ///
303 /// set.insert(MyKey::First(true));
304 /// set.insert(MyKey::First(false));
305 /// set.insert(MyKey::Second(true));
306 /// set.insert(MyKey::Second(false));
307 ///
308 /// let mut other = set.clone();
309 /// assert_eq!(set.len(), 4);
310 ///
311 /// set.retain(|k| matches!(k, MyKey::First(true) | MyKey::Second(true)));
312 ///
313 /// assert_eq!(set.len(), 2);
314 /// assert_eq!(set.contains(MyKey::First(true)), true);
315 /// assert_eq!(set.contains(MyKey::First(false)), false);
316 /// assert_eq!(set.contains(MyKey::Second(true)), true);
317 /// assert_eq!(set.contains(MyKey::Second(false)), false);
318 ///
319 /// other.retain(|k| matches!(k, MyKey::First(_)));
320 ///
321 /// assert_eq!(other.len(), 2);
322 /// assert_eq!(other.contains(MyKey::First(true)), true);
323 /// assert_eq!(other.contains(MyKey::First(false)), true);
324 /// assert_eq!(other.contains(MyKey::Second(true)), false);
325 /// assert_eq!(other.contains(MyKey::Second(false)), false);
326 /// ```
327 #[inline]
328 pub fn retain<F>(&mut self, f: F)
329 where
330 F: FnMut(T) -> bool,
331 {
332 self.storage.retain(f);
333 }
334
335 /// Clears the set, removing all values.
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use fixed_map::{Key, Set};
341 ///
342 /// #[derive(Clone, Copy, Key)]
343 /// enum MyKey {
344 /// One,
345 /// Two,
346 /// }
347 ///
348 /// let mut set = Set::new();
349 /// set.insert(MyKey::One);
350 /// set.clear();
351 /// assert!(set.is_empty());
352 /// ```
353 #[inline]
354 pub fn clear(&mut self) {
355 self.storage.clear();
356 }
357
358 /// Returns true if the set contains no elements.
359 ///
360 /// # Examples
361 ///
362 /// ```
363 /// use fixed_map::{Key, Set};
364 ///
365 /// #[derive(Clone, Copy, Key)]
366 /// enum MyKey {
367 /// One,
368 /// Two,
369 /// }
370 ///
371 /// let mut set = Set::new();
372 /// assert!(set.is_empty());
373 /// set.insert(MyKey::One);
374 /// assert!(!set.is_empty());
375 /// ```
376 #[inline]
377 pub fn is_empty(&self) -> bool {
378 self.storage.is_empty()
379 }
380
381 /// Returns the number of elements in the set.
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// use fixed_map::{Key, Set};
387 ///
388 /// #[derive(Clone, Copy, Key)]
389 /// enum MyKey {
390 /// First,
391 /// Second,
392 /// }
393 ///
394 /// let mut set = Set::new();
395 /// assert_eq!(set.len(), 0);
396 /// set.insert(MyKey::First);
397 /// assert_eq!(set.len(), 1);
398 /// ```
399 #[inline]
400 pub fn len(&self) -> usize {
401 self.storage.len()
402 }
403
404 /// Visits the values representing the intersection, i.e., the values that
405 /// are both in `self` and `other`.
406 ///
407 /// When an equal element is present in `self` and `other` then the
408 /// resulting `Intersection` may yield references to one or the other. This
409 /// can be relevant if `T` contains fields which are not compared by its
410 /// `Eq` implementation, and may hold different value between the two equal
411 /// copies of `T` in the two sets.
412 ///
413 /// # Examples
414 ///
415 /// ```
416 /// use fixed_map::{Key, Set};
417 ///
418 /// #[derive(Clone, Copy, Key, Debug)]
419 /// enum K {
420 /// One,
421 /// Two,
422 /// Three,
423 /// }
424 ///
425 /// let a = Set::from([K::One]);
426 /// let b = Set::from([K::One, K::Two, K::Two]);
427 ///
428 /// let intersection = a.intersection(&b).collect::<Set<_>>();
429 /// assert_eq!(intersection, Set::from([K::One]));
430 /// ```
431 #[inline]
432 pub fn intersection<'a>(&'a self, other: &'a Set<T>) -> Intersection<'a, T> {
433 if self.len() <= other.len() {
434 Intersection {
435 iter: self.iter(),
436 other,
437 }
438 } else {
439 Intersection {
440 iter: other.iter(),
441 other: self,
442 }
443 }
444 }
445}
446
447impl<T> Set<T>
448where
449 T: Key,
450 T::SetStorage: RawStorage,
451{
452 /// Get the raw value of the set.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// use fixed_map::{Key, Set};
458 ///
459 /// #[derive(Debug, Clone, Copy, Key)]
460 /// #[key(bitset)]
461 /// enum MyKey {
462 /// First,
463 /// Second,
464 /// }
465 ///
466 /// let mut set = Set::new();
467 /// assert!(set.as_raw() == 0);
468 /// set.insert(MyKey::First);
469 /// assert!(set.as_raw() != 0);
470 ///
471 /// let set2 = Set::from_raw(set.as_raw());
472 /// assert_eq!(set, set2);
473 /// ```
474 #[inline]
475 pub fn as_raw(&self) -> <T::SetStorage as RawStorage>::Value {
476 self.storage.as_raw()
477 }
478
479 /// Construct the set from a raw value.
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// use fixed_map::{Key, Set};
485 ///
486 /// #[derive(Debug, Clone, Copy, Key)]
487 /// #[key(bitset)]
488 /// enum MyKey {
489 /// First,
490 /// Second,
491 /// }
492 ///
493 /// let mut set = Set::new();
494 /// assert!(set.as_raw() == 0);
495 /// set.insert(MyKey::First);
496 /// assert!(set.as_raw() != 0);
497 ///
498 /// let set2 = Set::from_raw(set.as_raw());
499 /// assert_eq!(set, set2);
500 /// ```
501 #[inline]
502 pub fn from_raw(raw: <T::SetStorage as RawStorage>::Value) -> Self {
503 Self {
504 storage: <T::SetStorage as RawStorage>::from_raw(raw),
505 }
506 }
507}
508
509/// [`Clone`] implementation for a [`Set`].
510///
511/// # Examples
512///
513/// ```
514/// use fixed_map::{Key, Set};
515///
516/// #[derive(Debug, Clone, Copy, Key)]
517/// enum MyKey {
518/// First(bool),
519/// Second,
520/// }
521///
522/// let mut a = Set::new();
523/// a.insert(MyKey::First(true));
524/// let mut b = a.clone();
525/// b.insert(MyKey::Second);
526///
527/// assert_ne!(a, b);
528///
529/// assert!(a.contains(MyKey::First(true)));
530/// assert!(!a.contains(MyKey::Second));
531///
532/// assert!(b.contains(MyKey::First(true)));
533/// assert!(b.contains(MyKey::Second));
534/// ```
535impl<T> Clone for Set<T>
536where
537 T: Key,
538 T::SetStorage: Clone,
539{
540 #[inline]
541 fn clone(&self) -> Set<T> {
542 Set {
543 storage: self.storage.clone(),
544 }
545 }
546}
547
548/// The [`Copy`] implementation for a [`Set`] depends on its [`Key`]. If the
549/// derived key only consists of unit variants the corresponding [`Set`] will be
550/// [`Copy`] as well.
551///
552/// # Examples
553///
554/// ```
555/// use fixed_map::{Key, Set};
556///
557/// #[derive(Debug, Clone, Copy, Key)]
558/// enum MyKey {
559/// First,
560/// Second,
561/// }
562///
563/// let mut a = Set::new();
564/// a.insert(MyKey::First);
565/// let mut b = a;
566/// b.insert(MyKey::Second);
567///
568/// assert_ne!(a, b);
569///
570/// assert!(a.contains(MyKey::First));
571/// assert!(!a.contains(MyKey::Second));
572///
573/// assert!(b.contains(MyKey::First));
574/// assert!(b.contains(MyKey::Second));
575/// ```
576impl<T> Copy for Set<T>
577where
578 T: Key,
579 T::SetStorage: Copy,
580{
581}
582
583/// The [`Default`] implementation for a [`Set`] produces an empty set.
584///
585/// # Examples
586///
587/// ```
588/// use fixed_map::{Key, Set};
589///
590/// #[derive(Debug, Clone, Copy, Key)]
591/// enum MyKey {
592/// First,
593/// Second,
594/// }
595///
596/// let a = Set::<MyKey>::default();
597/// let b = Set::<MyKey>::new();
598///
599/// assert_eq!(a, b);
600/// ```
601impl<T> Default for Set<T>
602where
603 T: Key,
604{
605 #[inline]
606 fn default() -> Self {
607 Self::new()
608 }
609}
610
611/// The [`Debug`][fmt::Debug] implementation for a [`Set`].
612///
613/// # Examples
614///
615/// ```
616/// use fixed_map::{Key, Set};
617///
618/// #[derive(Debug, Clone, Copy, Key)]
619/// enum MyKey {
620/// First,
621/// Second,
622/// }
623///
624/// let mut a = Set::new();
625/// a.insert(MyKey::First);
626///
627/// assert_eq!("{First}", format!("{:?}", a));
628/// ```
629impl<T> fmt::Debug for Set<T>
630where
631 T: Key + fmt::Debug,
632{
633 #[inline]
634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635 f.debug_set().entries(self.iter()).finish()
636 }
637}
638
639/// [`PartialEq`] implementation for a [`Set`].
640///
641/// # Examples
642///
643/// ```
644/// use fixed_map::{Key, Set};
645///
646/// #[derive(Debug, Clone, Copy, Key)]
647/// enum MyKey {
648/// First,
649/// Second,
650/// }
651///
652/// let mut a = Set::new();
653/// a.insert(MyKey::First);
654/// // Note: `a` is Copy since it's using a simple key.
655/// let mut b = a;
656///
657/// assert_eq!(a, b);
658///
659/// b.insert(MyKey::Second);
660/// assert_ne!(a, b);
661/// ```
662///
663/// Using a composite key:
664///
665/// ```
666/// use fixed_map::{Key, Set};
667///
668/// #[derive(Debug, Clone, Copy, Key)]
669/// enum MyKey {
670/// First(bool),
671/// Second,
672/// }
673///
674/// let mut a = Set::new();
675/// a.insert(MyKey::First(true));
676/// let mut b = a.clone();
677///
678/// assert_eq!(a, b);
679///
680/// b.insert(MyKey::Second);
681/// assert_ne!(a, b);
682/// ```
683impl<T> PartialEq for Set<T>
684where
685 T: Key,
686 T::SetStorage: PartialEq,
687{
688 #[inline]
689 fn eq(&self, other: &Self) -> bool {
690 self.storage == other.storage
691 }
692}
693
694impl<T> Eq for Set<T>
695where
696 T: Key,
697 T::SetStorage: Eq,
698{
699}
700
701/// [`Hash`] implementation for a [`Set`].
702///
703/// # Examples
704///
705/// ```
706/// use std::collections::HashSet;
707///
708/// use fixed_map::{Key, Set};
709///
710/// #[derive(Debug, Clone, Copy, Key, Hash)]
711/// enum MyKey {
712/// First,
713/// Second,
714/// }
715///
716/// let mut a = Set::new();
717/// a.insert(MyKey::First);
718///
719/// let mut set = HashSet::new();
720/// set.insert(a);
721/// ```
722///
723/// Using a composite key:
724///
725/// ```
726/// use std::collections::HashSet;
727///
728/// use fixed_map::{Key, Set};
729///
730/// #[derive(Debug, Clone, Copy, Key, Hash)]
731/// enum MyKey {
732/// First(bool),
733/// Second,
734/// }
735///
736/// let mut a = Set::new();
737/// a.insert(MyKey::First(true));
738///
739/// // TODO: support this
740/// // let mut set = HashSet::new();
741/// // set.insert(a);
742/// ```
743impl<T> Hash for Set<T>
744where
745 T: Key,
746 T::SetStorage: Hash,
747{
748 #[inline]
749 fn hash<H>(&self, state: &mut H)
750 where
751 H: Hasher,
752 {
753 self.storage.hash(state);
754 }
755}
756
757/// [`PartialOrd`] implementation for a [`Set`].
758///
759/// For more details on ordering, see the [`Key`] documentation.
760///
761/// # Examples
762///
763/// ```
764/// use fixed_map::{Key, Set};
765///
766/// #[derive(Debug, Clone, Copy, Key, Hash)]
767/// enum MyKey {
768/// First,
769/// Second,
770/// Third,
771/// }
772///
773/// let mut a = Set::new();
774/// a.insert(MyKey::First);
775///
776/// let mut b = Set::new();
777/// b.insert(MyKey::Third);
778///
779/// assert!(a < b);
780///
781/// let mut empty = Set::new();
782/// assert!(empty < a);
783/// assert!(empty < b);
784/// ```
785///
786/// Using a composite key:
787///
788/// ```
789/// use fixed_map::{Key, Set};
790///
791/// #[derive(Debug, Clone, Copy, Key, Hash)]
792/// enum MyKey {
793/// First(bool),
794/// Second,
795/// }
796///
797/// let mut a = Set::new();
798/// a.insert(MyKey::First(true));
799///
800/// let mut b = Set::new();
801/// b.insert(MyKey::Second);
802///
803/// // TODO: support this
804/// // assert!(a < b);
805/// ```
806impl<T> PartialOrd for Set<T>
807where
808 T: Key,
809 T::SetStorage: PartialOrd,
810{
811 #[inline]
812 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
813 self.storage.partial_cmp(&other.storage)
814 }
815
816 #[inline]
817 fn lt(&self, other: &Self) -> bool {
818 self.storage.lt(&other.storage)
819 }
820
821 #[inline]
822 fn le(&self, other: &Self) -> bool {
823 self.storage.le(&other.storage)
824 }
825
826 #[inline]
827 fn gt(&self, other: &Self) -> bool {
828 self.storage.gt(&other.storage)
829 }
830
831 #[inline]
832 fn ge(&self, other: &Self) -> bool {
833 self.storage.ge(&other.storage)
834 }
835}
836
837/// [`Ord`] implementation for a [`Set`].
838///
839/// For more details on ordering, see the [`Key`] documentation.
840///
841/// # Examples
842///
843/// ```
844/// use fixed_map::{Key, Set};
845///
846/// #[derive(Debug, Clone, Copy, Key, Hash)]
847/// enum MyKey {
848/// First,
849/// Second,
850/// }
851///
852/// let mut a = Set::new();
853/// a.insert(MyKey::First);
854///
855/// let mut b = Set::new();
856/// b.insert(MyKey::Second);
857///
858/// let mut list = vec![b, a];
859/// list.sort();
860///
861/// assert_eq!(list, [a, b]);
862/// ```
863///
864/// Using a composite key:
865///
866/// ```
867/// use fixed_map::{Key, Set};
868///
869/// #[derive(Debug, Clone, Copy, Key, Hash)]
870/// enum MyKey {
871/// First(bool),
872/// Second,
873/// }
874///
875/// let mut a = Set::new();
876/// a.insert(MyKey::First(true));
877///
878/// let mut b = Set::new();
879/// b.insert(MyKey::Second);
880///
881/// // TODO: support this
882/// // let mut list = vec![a, b];
883/// // list.sort();
884/// ```
885impl<T> Ord for Set<T>
886where
887 T: Key,
888 T::SetStorage: Ord,
889{
890 #[inline]
891 fn cmp(&self, other: &Self) -> Ordering {
892 self.storage.cmp(&other.storage)
893 }
894
895 #[inline]
896 fn max(self, other: Self) -> Self {
897 Self {
898 storage: self.storage.max(other.storage),
899 }
900 }
901
902 #[inline]
903 fn min(self, other: Self) -> Self {
904 Self {
905 storage: self.storage.min(other.storage),
906 }
907 }
908
909 #[inline]
910 fn clamp(self, min: Self, max: Self) -> Self {
911 Self {
912 storage: self.storage.clamp(min.storage, max.storage),
913 }
914 }
915}
916
917impl<'a, T> IntoIterator for &'a Set<T>
918where
919 T: Key,
920{
921 type Item = T;
922 type IntoIter = Iter<'a, T>;
923
924 #[inline]
925 fn into_iter(self) -> Self::IntoIter {
926 self.iter()
927 }
928}
929
930/// Produce an owning iterator which iterates over all elements in the set in
931/// order.
932///
933/// # Examples
934///
935/// ```
936/// use fixed_map::{Key, Set};
937///
938/// #[derive(Debug, Clone, Copy, Key, PartialEq, Eq)]
939/// enum MyKey {
940/// First,
941/// Second,
942/// Third,
943/// }
944///
945/// let mut set = Set::new();
946/// set.insert(MyKey::First);
947/// set.insert(MyKey::Second);
948///
949/// assert_eq!(set.into_iter().collect::<Vec<_>>(), vec![MyKey::First, MyKey::Second]);
950/// ```
951impl<T> IntoIterator for Set<T>
952where
953 T: Key,
954{
955 type Item = T;
956 type IntoIter = IntoIter<T>;
957
958 /// An iterator visiting all values in arbitrary order.
959 /// The iterator element type is `T`.
960 ///
961 /// # Examples
962 ///
963 /// ```
964 /// use fixed_map::{Key, Set};
965 ///
966 /// #[derive(Debug, Clone, Copy, Key, PartialEq, Eq)]
967 /// enum MyKey {
968 /// One,
969 /// Two,
970 /// Three,
971 /// }
972 ///
973 /// let mut set = Set::new();
974 /// set.insert(MyKey::One);
975 /// set.insert(MyKey::Two);
976 ///
977 /// assert_eq!(set.into_iter().collect::<Vec<_>>(), vec![MyKey::One, MyKey::Two]);
978 /// ```
979 #[inline]
980 fn into_iter(self) -> Self::IntoIter {
981 self.storage.into_iter()
982 }
983}
984
985impl<T> FromIterator<T> for Set<T>
986where
987 T: Key,
988{
989 #[inline]
990 fn from_iter<I>(iter: I) -> Self
991 where
992 I: IntoIterator<Item = T>,
993 {
994 let mut set = Self::new();
995
996 for value in iter {
997 set.insert(value);
998 }
999
1000 set
1001 }
1002}
1003
1004#[cfg(feature = "serde")]
1005impl<T> serde::Serialize for Set<T>
1006where
1007 T: Key + serde::Serialize,
1008{
1009 #[inline]
1010 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1011 where
1012 S: serde::Serializer,
1013 {
1014 use serde::ser::SerializeSeq as _;
1015
1016 let mut seq = serializer.serialize_seq(Some(self.len()))?;
1017
1018 for v in self {
1019 seq.serialize_element(&v)?;
1020 }
1021
1022 seq.end()
1023 }
1024}
1025
1026#[cfg(feature = "serde")]
1027impl<'de, T> serde::de::Deserialize<'de> for Set<T>
1028where
1029 T: Key + serde::de::Deserialize<'de>,
1030{
1031 #[inline]
1032 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1033 where
1034 D: serde::Deserializer<'de>,
1035 {
1036 struct SeqVisitor<T>(core::marker::PhantomData<T>);
1037
1038 impl<'de, T> serde::de::Visitor<'de> for SeqVisitor<T>
1039 where
1040 T: Key + serde::de::Deserialize<'de>,
1041 {
1042 type Value = Set<T>;
1043
1044 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1045 formatter.write_str("a sequence")
1046 }
1047
1048 #[inline]
1049 fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
1050 where
1051 V: serde::de::SeqAccess<'de>,
1052 {
1053 let mut set = Set::new();
1054
1055 while let Some(elem) = visitor.next_element()? {
1056 set.insert(elem);
1057 }
1058
1059 Ok(set)
1060 }
1061 }
1062
1063 deserializer.deserialize_seq(SeqVisitor(core::marker::PhantomData))
1064 }
1065}
1066
1067#[cfg(feature = "musli02")]
1068impl<M, T> musli_core02::Encode<M> for Set<T>
1069where
1070 T: Key + musli_core02::Encode<M>,
1071{
1072 type Encode = Self;
1073
1074 #[inline]
1075 fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
1076 where
1077 E: musli_core02::Encoder<Mode = M>,
1078 {
1079 use musli_core02::en::SequenceEncoder as _;
1080
1081 encoder.encode_sequence_fn(self.len(), |seq| {
1082 for v in self {
1083 seq.push(v)?;
1084 }
1085
1086 Ok(())
1087 })
1088 }
1089
1090 #[inline]
1091 fn as_encode(&self) -> &Self::Encode {
1092 self
1093 }
1094}
1095
1096#[cfg(feature = "musli02")]
1097impl<'de, M, A, T> musli_core02::Decode<'de, M, A> for Set<T>
1098where
1099 A: musli_core02::Allocator,
1100 T: Key + musli_core02::Decode<'de, M, A>,
1101{
1102 #[inline]
1103 fn decode<D>(decoder: D) -> Result<Self, D::Error>
1104 where
1105 D: musli_core02::Decoder<'de, Mode = M, Allocator = A>,
1106 {
1107 use musli_core02::de::{Decoder as _, SequenceDecoder as _};
1108
1109 decoder.decode_sequence(|seq| {
1110 let mut set = Set::new();
1111
1112 while let Some(value) = seq.try_decode_next()? {
1113 set.insert(value.decode()?);
1114 }
1115
1116 Ok(set)
1117 })
1118 }
1119}
1120
1121// SAFETY: `Set<T>` is `#[repr(transparent)]` over `T::SetStorage`, which
1122// `TransparentRawStorage` guarantees is `#[repr(transparent)]` over its raw
1123// value with every bit pattern valid, so `Set<T>` has the layout and validity
1124// of that value and can forward to its `ZeroCopy` implementation.
1125#[cfg(feature = "musli-zerocopy01")]
1126unsafe impl<T> musli_zerocopy01::ZeroCopy for Set<T>
1127where
1128 T: Key,
1129 T::SetStorage: crate::raw::TransparentRawStorage,
1130 <T::SetStorage as RawStorage>::Value: musli_zerocopy01::ZeroCopy,
1131{
1132 const ANY_BITS: bool =
1133 <<T::SetStorage as RawStorage>::Value as musli_zerocopy01::ZeroCopy>::ANY_BITS;
1134 const PADDED: bool =
1135 <<T::SetStorage as RawStorage>::Value as musli_zerocopy01::ZeroCopy>::PADDED;
1136 const CAN_SWAP_BYTES: bool =
1137 <<T::SetStorage as RawStorage>::Value as musli_zerocopy01::ZeroCopy>::CAN_SWAP_BYTES;
1138
1139 #[inline]
1140 unsafe fn pad(padder: &mut musli_zerocopy01::buf::Padder<'_, Self>) {
1141 unsafe {
1142 <<T::SetStorage as RawStorage>::Value as musli_zerocopy01::ZeroCopy>::pad(
1143 padder.transparent(),
1144 );
1145 }
1146 }
1147
1148 #[inline]
1149 unsafe fn validate(
1150 validator: &mut musli_zerocopy01::buf::Validator<'_, Self>,
1151 ) -> Result<(), musli_zerocopy01::Error> {
1152 unsafe {
1153 <<T::SetStorage as RawStorage>::Value as musli_zerocopy01::ZeroCopy>::validate(
1154 validator.transparent(),
1155 )
1156 }
1157 }
1158
1159 #[inline]
1160 fn swap_bytes<E>(self) -> Self
1161 where
1162 E: musli_zerocopy01::ByteOrder,
1163 {
1164 Set::from_raw(musli_zerocopy01::ZeroCopy::swap_bytes::<E>(self.as_raw()))
1165 }
1166}
1167
1168impl<T, const N: usize> From<[T; N]> for Set<T>
1169where
1170 T: Key,
1171{
1172 /// # Examples
1173 ///
1174 /// ```
1175 /// use fixed_map::{Key, Set};
1176 ///
1177 /// #[derive(Debug, Clone, Copy, Key, PartialEq, Eq)]
1178 /// enum K {
1179 /// One,
1180 /// Two,
1181 /// Three,
1182 /// }
1183 ///
1184 /// let set1 = Set::from([K::One, K::Two, K::Three]);
1185 /// let set2: Set<_> = [K::One, K::Two, K::Three].into();
1186 /// assert_eq!(set1, set2);
1187 /// ```
1188 fn from(arr: [T; N]) -> Self {
1189 Self::from_iter(arr)
1190 }
1191}