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