enum_collections/enummap.rs
1use crate::Enumerated;
2use std::{
3 array,
4 fmt::Debug,
5 marker::PhantomData,
6 ops::{Index, IndexMut},
7};
8
9/// Creates an EnumMap with user-provided values.
10/// ```
11/// use enum_collections::{em, Enumerated, EnumMap};
12/// #[derive(Enumerated)]
13/// enum Letter {
14/// A,
15/// B,
16/// }
17///
18/// let enum_map = em!(Letter, i32, A => 42, B => 24);
19/// assert_eq!(42, enum_map[Letter::A]);
20/// assert_eq!(24, enum_map[Letter::B]);
21/// ```
22///
23#[macro_export]
24macro_rules! em {
25
26 ($ktp:ty, $vtp:ty, $($x:ident=>$y:expr),* ) => {
27 enum_collections::EnumMap::<$ktp, $vtp, {<$ktp>::SIZE}>::new_inspect(|letter| {
28 match letter {
29 $(<$ktp>::$x => $y,)*
30 }
31 })
32 };
33
34}
35
36/// Initializes an EnumMap with default values for all variants not explicitly specified.
37/// ```
38/// use enum_collections::{em_default, Enumerated, EnumMap};
39/// #[derive(Enumerated)]
40/// enum Letter {
41/// A,
42/// B,
43/// }
44///
45/// // One non-default value
46/// let enum_map = em_default!(Letter, i32, A => 42);
47/// assert_eq!(42, enum_map[Letter::A]);
48/// assert_eq!(i32::default(), enum_map[Letter::B]);
49///
50/// // All default
51///
52/// let enum_map = em_default!(Letter, i32,);
53/// assert_eq!(i32::default(), enum_map[Letter::A]);
54/// assert_eq!(i32::default(), enum_map[Letter::B]);
55/// ```
56///
57#[macro_export]
58macro_rules! em_default {
59 ($ktp:ty, $vtp:ty, $($x:ident=>$y:expr),* ) => {
60 EnumMap::<$ktp, $vtp, {<$ktp>::SIZE}>::new_inspect(|letter| {
61 match letter {
62 $(<$ktp>::$x => $y,)*
63 _ => Default::default(),
64 }
65 })
66 };
67}
68
69/// Initializes an EnumMap with `Option::None` for all variants not explicitly specified.
70///
71/// ```
72/// use enum_collections::{em_option, Enumerated, EnumMap};
73/// #[derive(Enumerated)]
74/// enum Letter {
75/// A,
76/// B,
77/// }
78///
79/// let enum_map = em_option!(Letter, i32, A => 42);
80/// assert_eq!(Some(42), enum_map[Letter::A]);
81/// assert_eq!(None, enum_map[Letter::B]);
82/// ```
83#[macro_export]
84macro_rules! em_option {
85 ($ktp:ty, $vtp:ty, $($x:ident=>$y:expr),* ) => {
86 EnumMap::<$ktp, Option<$vtp>, {<$ktp>::SIZE}>::new_inspect(|letter| {
87 match letter {
88 $(<$ktp>::$x => Some($y),)*
89 _ => None,
90 }
91 })
92 };
93}
94
95#[cfg(test)]
96mod macro_test {
97 use crate::{EnumMap, Enumerated};
98
99 #[derive(Enumerated)]
100 enum Letter {
101 A,
102 B,
103 }
104
105 #[test]
106 fn test_macro() {
107 let enum_map = em_default!(Letter, i32, A=>42);
108 assert_eq!(42, enum_map[Letter::A]);
109 assert_eq!(i32::default(), enum_map[Letter::B]);
110 }
111}
112
113/// A map of enum variants to values. EnumMap is a fixed-size map, where each variant of the enum
114/// is mapped to a value. EnumMap is a a zero-cost abstraction over an array, where the index of the array
115/// corresponds to the position of the variant in the enum.
116///
117/// Because it is a thin wrapper of an array, it is stack-allocated by default. Simply [std::boxed::Box]ing it
118/// will move it to the heap, at the caller's discretion.
119///
120/// - Indexed by enum variants.
121/// - IndexMut by enum variants.
122/// - Debug if the enum is Debug.
123/// - PartialEq if the value is PartialEq. Same for Eq.
124///
125/// Debug and Eq are optional features. They are enabled by default.
126///
127/// # Examples
128///
129/// ```
130/// use enum_collections::{EnumMap, Enumerated, em_default, em};
131///
132/// #[derive(Enumerated)]
133/// pub enum Letter {
134/// A,
135/// B,
136/// }
137///
138///
139/// // Indexing and mutation
140/// let mut enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_default();
141/// assert_eq!(0, enum_map[Letter::A]);
142/// enum_map[Letter::A] = 42;
143/// assert_eq!(42, enum_map[Letter::A]);
144///
145/// // Construction using macros
146/// // (Key type, Value type, Key=>Value pairs)
147/// let enum_map = em!(Letter, i32, A=>42, B=>24); // All values set explicitly
148/// assert_eq!(42, enum_map[Letter::A]);
149/// assert_eq!(24, enum_map[Letter::B]);
150///
151/// // (Key type, Value type, optional Key=>Value pairs)
152/// let enum_map = em_default!(Letter, i32, A => 42); // Default used for missing values
153/// assert_eq!(42, enum_map[Letter::A]);
154/// assert_eq!(i32::default(), enum_map[Letter::B]);
155///
156/// let enum_map = em_default!(Letter, i32,); // All default
157/// assert_eq!(i32::default(), enum_map[Letter::A]);
158/// assert_eq!(i32::default(), enum_map[Letter::B]);
159///
160///
161/// // Constructor with default values
162/// let enum_map_default = EnumMap::<Letter, i32, { Letter::SIZE }>::new_default();
163/// assert_eq!(0, enum_map_default[Letter::A]);
164/// assert_eq!(0, enum_map_default[Letter::B]);
165///
166/// // Convenience constructor for optional values
167/// let mut enum_map_option = EnumMap::<Letter, Option<i32>, { Letter::SIZE }>::new_option();
168/// assert_eq!(None, enum_map_option[Letter::A]);
169/// assert_eq!(None, enum_map_option[Letter::B]);
170/// enum_map_option[Letter::A] = Some(42);
171/// assert_eq!(Some(42), enum_map_option[Letter::A]);
172///
173/// // Constructor with custom initialization
174/// #[derive(PartialEq, Eq, Debug)]
175/// struct Custom;
176/// let enum_map = EnumMap::<Letter, Custom, { Letter::SIZE }>::new(|| Custom);
177/// assert_eq!(Custom, enum_map[Letter::A]);
178/// assert_eq!(Custom, enum_map[Letter::B]);
179///
180/// // Custom initialization function with enum variant (key) inspection
181/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_inspect(|letter| {
182/// match letter {
183/// Letter::A => 42,
184/// Letter::B => 24,
185/// }
186/// });
187/// assert_eq!(42, enum_map[Letter::A]);
188/// assert_eq!(24, enum_map[Letter::B]);
189///
190/// // Debug
191/// #[derive(Enumerated, Debug)]
192/// pub enum LetterDebugDerived {
193/// A,
194/// B,
195/// }
196/// let enum_map_debug =
197/// EnumMap::<LetterDebugDerived, i32, { LetterDebugDerived::SIZE }>::new(|| 42);
198/// assert_eq!("{A: 42, B: 42}", format!("{:?}", enum_map_debug));
199///
200/// ```
201pub struct EnumMap<K: Enumerated, V, const N: usize> {
202 pub(crate) data: [V; N],
203 pub(crate) _key: PhantomData<K>,
204}
205
206impl<K: Enumerated, V: Default, const N: usize> EnumMap<K, V, N> {
207 /// Creates a new EnumMap with type's default values for each variant.
208 ///
209 /// ```
210 /// use enum_collections::{EnumMap, Enumerated};
211 /// #[derive(Enumerated)]
212 /// pub enum Letter {
213 /// A,
214 /// B,
215 /// }
216 ///
217 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_default();
218 /// assert_eq!(0, enum_map[Letter::A]);
219 /// assert_eq!(0, enum_map[Letter::B]);
220 /// ```
221 pub fn new_default() -> Self {
222 Self {
223 data: array::from_fn(|_| V::default()),
224 _key: PhantomData,
225 }
226 }
227 /// Sets all values to `V::default()`.
228 ///
229 /// ```
230 /// use enum_collections::{EnumMap, Enumerated};
231 /// #[derive(Enumerated)]
232 /// pub enum Letter {
233 /// A,
234 /// B,
235 /// }
236 /// let mut enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
237 /// enum_map.iter().for_each(|value| assert_eq!(42, *value));
238 /// enum_map.clear_set_default();
239 /// enum_map.iter().for_each(|value| assert_eq!(0, *value));
240 /// ```
241 ///
242 pub fn clear_set_default(&mut self) {
243 for idx in 0..self.data.len() {
244 self.data[idx] = V::default();
245 }
246 }
247}
248
249impl<K: Enumerated, V, const N: usize> EnumMap<K, Option<V>, N> {
250 /// Creates a new EnumMap with `Option::None` set for each variant.
251 /// Convenience constructor over `EnumMap::new` for optional values.
252 ///
253 /// ```
254 /// use enum_collections::{EnumMap, Enumerated};
255 /// #[derive(Enumerated)]
256 /// pub enum Letter {
257 /// A,
258 /// B,
259 /// }
260 ///
261 /// let enum_map = EnumMap::<Letter, Option<i32>, { Letter::SIZE }>::new_option();
262 /// assert_eq!(None, enum_map[Letter::A]);
263 /// assert_eq!(None, enum_map[Letter::B]);
264 /// ```
265 pub fn new_option() -> Self {
266 Self {
267 data: array::from_fn(|_| None),
268 _key: PhantomData,
269 }
270 }
271
272 /// Clears the EnumMap and sets all values to `None`.
273 ///
274 /// This function iterates over each variant of the EnumMap and sets its value to `None`.
275 ///
276 /// # Examples
277 ///
278 /// ```
279 /// use enum_collections::{EnumMap, Enumerated};
280 /// #[derive(Enumerated)]
281 /// pub enum Letter {
282 /// A,
283 /// B,
284 /// }
285 ///
286 /// let mut enum_map = EnumMap::<Letter, Option<i32>, { Letter::SIZE }>::new_option();
287 /// enum_map[Letter::A] = Some(10);
288 /// enum_map[Letter::B] = Some(20);
289 ///
290 /// enum_map.clear_set_none();
291 /// enum_map.iter().for_each(|value| assert_eq!(None, *value));
292 ///
293 /// ```
294 pub fn clear_set_none(&mut self) {
295 for idx in 0..self.data.len() {
296 self.data[idx] = None;
297 }
298 }
299}
300
301impl<K: Enumerated, V, const N: usize> EnumMap<K, V, N> {
302 /// Creates a new EnumMap where value of each variant is produced by the provided function
303 ///
304 /// ```
305 /// use enum_collections::{EnumMap, Enumerated};
306 /// #[derive(Enumerated)]
307 /// pub enum Letter {
308 /// A,
309 /// B,
310 /// }
311 ///
312 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
313 /// assert_eq!(42, enum_map[Letter::A]);
314 /// assert_eq!(42, enum_map[Letter::B]);
315 ///
316 /// ```
317 pub fn new(default: fn() -> V) -> Self {
318 Self {
319 data: array::from_fn(|_| default()),
320 _key: PhantomData,
321 }
322 }
323
324 /// Iterates over each variant of the EnumMap and sets its value to the value provided by the `val_provider` function.
325 ///
326 /// Unlike [Self::new], this function does not allocate a new EnumMap.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use enum_collections::{EnumMap, Enumerated};
332 /// #[derive(Enumerated)]
333 /// pub enum Letter {
334 /// A,
335 /// B,
336 /// }
337 ///
338 /// let mut enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
339 /// enum_map.set_all(|| 24);
340 /// enum_map.iter().for_each(|value| assert_eq!(24, *value));
341 /// ```
342 pub fn set_all(&mut self, val_provider: fn() -> V) {
343 for idx in 0..self.data.len() {
344 self.data[idx] = val_provider();
345 }
346 }
347
348 /// Iterates over the EnumMap's key-value pairs.
349 ///
350 /// ```
351 /// use enum_collections::{EnumMap, Enumerated};
352 /// #[derive(Enumerated, Debug)]
353 /// pub enum Letter {
354 /// A,
355 /// B,
356 /// }
357 ///
358 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
359 /// for (_letter, value) in enum_map.iter_kv() {
360 /// assert_eq!(42, *value);
361 /// }
362 ///
363 /// ```
364 #[cfg(feature = "variants")]
365 pub fn iter_kv(&self) -> std::iter::Zip<std::slice::Iter<'_, K>, std::slice::Iter<'_, V>> {
366 K::VARIANTS.iter().zip(self.data.iter())
367 }
368
369 /// Iterates over the EnumMap's values.
370 ///
371 /// ```
372 /// use enum_collections::{EnumMap, Enumerated};
373 /// #[derive(Enumerated, Debug)]
374 /// pub enum Letter {
375 /// A,
376 /// B,
377 /// }
378 ///
379 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
380 /// for value in enum_map.iter() {
381 /// assert_eq!(42, *value);
382 /// }
383 ///
384 /// ```
385 #[cfg(feature = "variants")]
386 pub fn iter(&self) -> std::slice::Iter<'_, V> {
387 self.data.iter()
388 }
389
390 /// Creates a new EnumMap where value of each variant is produced by the provided function.
391 /// The function receives the enum variant being initialized for inspection.
392 ///
393 /// ```
394 /// use enum_collections::{EnumMap, Enumerated};
395 /// #[derive(Enumerated)]
396 /// pub enum Letter {
397 /// A,
398 /// B,
399 /// }
400 ///
401 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_inspect(|letter| {
402 /// match letter {
403 /// Letter::A => 42,
404 /// Letter::B => 24,
405 /// }
406 /// });
407 /// assert_eq!(42, enum_map[Letter::A]);
408 /// assert_eq!(24, enum_map[Letter::B]);
409 ///
410 /// ```
411 #[cfg(feature = "variants")]
412 pub fn new_inspect(mut default: impl FnMut(&K) -> V) -> Self {
413 let init_fn = |index| {
414 // Finds the enum variant by its index, as the array is sorted by discriminants in ascending order.
415 default(&K::VARIANTS[index])
416 };
417 Self {
418 data: array::from_fn(init_fn),
419 _key: PhantomData,
420 }
421 }
422}
423
424impl<K: Enumerated, V: Copy, const N: usize> EnumMap<K, V, N> {
425 /// Creates a new EnumMap where value of each variant is the provided value.
426 ///
427 /// ```
428 /// use enum_collections::{EnumMap, Enumerated};
429 /// #[derive(Enumerated)]
430 /// pub enum Letter {
431 /// A,
432 /// B,
433 /// }
434 ///
435 /// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_with_all(42);
436 /// assert_eq!(42, enum_map[Letter::A]);
437 /// assert_eq!(42, enum_map[Letter::B]);
438 ///
439 /// ```
440 pub const fn new_with_all(value: V) -> Self {
441 Self {
442 data: [value; N],
443 _key: PhantomData,
444 }
445 }
446}
447
448/// Allows indexing of EnumMap.
449///
450/// ```
451/// use enum_collections::{EnumMap, Enumerated};
452///
453/// #[derive(Enumerated)]
454/// pub enum LetterEqDerived {
455/// A,
456/// B,
457/// }
458///
459/// let enum_map = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
460/// assert_eq!(42, enum_map[LetterEqDerived::A]);
461/// assert_eq!(42, enum_map[LetterEqDerived::B]);
462/// ```
463impl<K: Enumerated, V, const N: usize> Index<K> for EnumMap<K, V, N> {
464 type Output = V;
465
466 fn index(&self, key: K) -> &Self::Output {
467 &self.data[key.position()]
468 }
469}
470
471/// Allows mutable indexing of EnumMap.
472///
473///
474/// ```
475/// use enum_collections::{EnumMap, Enumerated};
476///
477/// #[derive(Enumerated)]
478/// pub enum LetterEqDerived {
479/// A,
480/// B,
481/// }
482///
483/// let mut enum_map = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new_default();
484/// assert_eq!(0, enum_map[LetterEqDerived::A]);
485/// enum_map[LetterEqDerived::A] = 42;
486/// assert_eq!(42, enum_map[LetterEqDerived::A]);
487///
488/// ```
489impl<K: Enumerated, V, const N: usize> IndexMut<K> for EnumMap<K, V, N> {
490 fn index_mut(&mut self, key: K) -> &mut Self::Output {
491 &mut self.data[key.position()]
492 }
493}
494
495/// Implements Debug for EnumMap. EnumMap is printed as a map of enum variants to their values.
496///
497/// ```
498///
499/// use enum_collections::{EnumMap, Enumerated};
500/// #[derive(Enumerated, Debug)]
501/// enum Letter {
502/// A,
503/// B,
504/// }
505///
506/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
507/// assert_eq!("{A: 42, B: 42}", format!("{:?}", enum_map));
508/// ```
509///
510#[cfg(feature = "debug")]
511impl<K: Enumerated + Debug, V: Debug, const N: usize> std::fmt::Debug for EnumMap<K, V, N> {
512 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
513 f.debug_map()
514 .entries(
515 K::VARIANTS
516 .iter()
517 .enumerate()
518 .map(|(index, variant)| (variant, &self.data[index])),
519 )
520 .finish()
521 }
522}
523
524#[cfg(feature = "eq")]
525mod eq {
526 use super::{EnumMap, Enumerated};
527
528 /// Implements PartialEq for EnumMap. Two enum maps are PartialEq if for each enum variant, the value is the same.
529 ///
530 /// ```
531 /// use enum_collections::{EnumMap, Enumerated};
532 ///
533 /// #[derive(Enumerated, Eq, PartialEq)]
534 /// pub enum LetterEqDerived {
535 /// A,
536 /// B,
537 /// }
538 /// let enum_map = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
539 /// let same_map = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
540 /// assert!(enum_map == same_map);
541 ///
542 /// let different_map = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new_default();
543 /// assert!(enum_map != different_map);
544 /// ```
545 impl<K: Enumerated, V: PartialEq, const N: usize> PartialEq for EnumMap<K, V, N> {
546 fn eq(&self, other: &Self) -> bool {
547 self.data == other.data
548 }
549 }
550
551 /// Marks EnumMap as Eq. Two enum maps are Eq if for each enum variant, the value is the same.
552 ///
553 /// ```
554 /// use enum_collections::{EnumMap, Enumerated};
555 ///
556 /// #[derive(Enumerated, Eq, PartialEq)]
557 /// pub enum LetterEqDerived {
558 /// A,
559 /// B,
560 /// }
561 /// let first = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
562 /// let second = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
563 /// let third = EnumMap::<LetterEqDerived, i32, { LetterEqDerived::SIZE }>::new(|| 42);
564 /// // Reflexive
565 /// assert!(first == first);
566 /// // Symmetric
567 /// assert!(first == second);
568 /// assert!(second == first);
569 /// // Transitive
570 /// assert!(second == third);
571 /// assert!(first == third);
572 /// ```
573 impl<K: Enumerated, V: Eq, const N: usize> Eq for EnumMap<K, V, N> {}
574}
575
576/// Implements Clone for EnumMap. Clones the EnumMap by cloning each value. Requires the value to be `Clone`.
577///
578/// ```
579/// use enum_collections::{EnumMap, Enumerated};
580///
581/// #[derive(Enumerated, Debug)]
582/// pub enum Letter {
583/// A,
584/// B,
585/// }
586/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
587/// let cloned = enum_map.clone();
588/// assert_eq!(enum_map, cloned);
589/// ```
590impl<K: Enumerated, V: Clone, const N: usize> Clone for EnumMap<K, V, N> {
591 fn clone(&self) -> Self {
592 Self {
593 data: self.data.clone(),
594 _key: PhantomData,
595 }
596 }
597}
598
599/// Implements Copy for EnumMap, provided the value type `V` also implements `Copy`.
600///
601/// ```
602///
603/// use enum_collections::{EnumMap, Enumerated};
604/// #[derive(Enumerated, Debug)]
605/// pub enum Letter {
606/// A,
607/// B,
608/// }
609/// let enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new(|| 42);
610/// let copied = enum_map;
611/// assert_eq!(enum_map, copied);
612/// ```
613impl<K: Enumerated, V: Copy, const N: usize> Copy for EnumMap<K, V, N> {}
614
615#[cfg(test)]
616mod tests {
617 use crate::enummap::EnumMap;
618 use crate::Enumerated;
619 /// No Debug derived on purpose, the crate must be usable without [std::fmt::Debug] derived
620 /// for the enum.
621 #[derive(Enumerated, Debug)]
622 pub(super) enum Letter {
623 A,
624 B,
625 }
626
627 #[test]
628 fn index() {
629 let mut enum_map = EnumMap::<Letter, i32, { Letter::SIZE }>::new_default();
630 assert_eq!(0, enum_map[Letter::A]);
631 enum_map[Letter::A] = 42;
632 assert_eq!(42, enum_map[Letter::A]);
633 assert_eq!(i32::default(), enum_map[Letter::B]);
634 }
635
636 #[test]
637 fn constructor_option() {
638 let mut enum_map = EnumMap::<Letter, Option<i32>, { Letter::SIZE }>::new_option();
639 assert_eq!(None, enum_map[Letter::A]);
640 assert_eq!(None, enum_map[Letter::B]);
641
642 enum_map[Letter::A] = Some(42);
643 assert_eq!(Some(42), enum_map[Letter::A]);
644 }
645
646 #[test]
647 fn non_default_type() {
648 #[derive(PartialEq, Eq, Debug)]
649 struct NonDefault;
650 let enum_map = EnumMap::<Letter, NonDefault, { Letter::SIZE }>::new(|| NonDefault);
651 assert_eq!(NonDefault, enum_map[Letter::A]);
652 assert_eq!(NonDefault, enum_map[Letter::B]);
653 }
654
655 /// Safeguard test. Nothing inside the EnumMap should prevent from moving it to the heap.
656 #[test]
657 fn heap_allocation() {
658 let boxed_map = Box::new(EnumMap::<Letter, i32, { Letter::SIZE }>::new_default());
659 assert!(EnumMap::<Letter, i32, { Letter::SIZE }>::new_default() == *boxed_map);
660 }
661
662 #[cfg(feature = "variants")]
663 mod variants {
664 use super::*;
665
666 #[test]
667 fn variants() {
668 assert_eq!(2, Letter::VARIANTS.len());
669 Letter::VARIANTS
670 .iter()
671 .for_each(|letter| println!("{:?}", letter));
672 }
673 }
674
675 #[cfg(feature = "debug")]
676 mod debug {
677 use crate::{EnumMap, Enumerated};
678
679 /// A dedicated enum with [std::fmt::Debug] derived, to test compilation and usability both
680 /// with and without `Debug` implemented.
681 #[derive(Enumerated, Debug)]
682 pub(super) enum LetterDebugDerived {
683 A,
684 B,
685 }
686
687 #[test]
688 fn debug() {
689 let enum_map =
690 EnumMap::<LetterDebugDerived, i32, { LetterDebugDerived::SIZE }>::new(|| 42);
691 assert_eq!("{A: 42, B: 42}", format!("{:?}", enum_map));
692 }
693 }
694
695 #[cfg(feature = "serde")]
696 mod serde {
697 use serde::{Deserialize, Serialize};
698
699 use crate::{EnumMap, Enumerated};
700
701 #[derive(Enumerated, Serialize, Deserialize, PartialEq, Debug)]
702 pub(super) enum LetterSerde {
703 A,
704 B,
705 }
706
707 #[test]
708 fn serialize() {
709 let mut enum_map: EnumMap<_, Option<_>, { LetterSerde::SIZE }> = EnumMap::new_option();
710 enum_map[LetterSerde::A] = Some(10);
711 enum_map[LetterSerde::B] = Some(11);
712
713 let serialized = ron::to_string(&enum_map).unwrap();
714 assert_eq!("{A:Some(10),B:Some(11)}", serialized);
715 }
716
717 #[test]
718 fn deserialize() {
719 let str = "{A:Some(10),B:Some(11)}";
720 let enum_map: EnumMap<_, Option<_>, { LetterSerde::SIZE }> =
721 ron::from_str(str).unwrap();
722
723 let mut correct_enum_map: EnumMap<_, Option<_>, { LetterSerde::SIZE }> =
724 EnumMap::new_option();
725 correct_enum_map[LetterSerde::A] = Some(10);
726 correct_enum_map[LetterSerde::B] = Some(11);
727 assert_eq!(enum_map, correct_enum_map);
728 }
729
730 #[test]
731 fn serde() {
732 let mut enum_map: EnumMap<_, Option<_>, { LetterSerde::SIZE }> = EnumMap::new_option();
733 enum_map[LetterSerde::A] = Some(10);
734
735 let serialized = ron::to_string(&enum_map).unwrap();
736 let new_enum_map: EnumMap<_, Option<_>, { LetterSerde::SIZE }> =
737 ron::from_str(&serialized).unwrap();
738 assert_eq!(enum_map, new_enum_map);
739 }
740 }
741}