Struct enum_map::EnumMap

source ·
pub struct EnumMap<K: EnumArray<V>, V> { /* private fields */ }
Expand description

An enum mapping.

This internally uses an array which stores a value for each possible enum value. To work, it requires implementation of internal (private, although public due to macro limitations) trait which allows extracting information about an enum, which can be automatically generated using #[derive(Enum)] macro.

Additionally, bool and u8 automatically derives from Enum. While u8 is not technically an enum, it’s convenient to consider it like one. In particular, reverse-complement in benchmark game could be using u8 as an enum.

Examples

use enum_map::{enum_map, Enum, EnumMap};

#[derive(Enum)]
enum Example {
    A,
    B,
    C,
}

let mut map = EnumMap::default();
// new initializes map with default values
assert_eq!(map[Example::A], 0);
map[Example::A] = 3;
assert_eq!(map[Example::A], 3);

Implementations§

An iterator visiting all values. The iterator type is &V.

Examples
use enum_map::enum_map;

let map = enum_map! { false => 3, true => 4 };
let mut values = map.values();
assert_eq!(values.next(), Some(&3));
assert_eq!(values.next(), Some(&4));
assert_eq!(values.next(), None);
Examples found in repository?
src/serde.rs (line 14)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            serializer.collect_map(self)
        } else {
            let mut tup = serializer.serialize_tuple(self.len())?;
            for value in self.values() {
                tup.serialize_element(value)?;
            }
            tup.end()
        }
    }
}

/// Requires crate feature `"serde"`
impl<'de, K, V> Deserialize<'de> for EnumMap<K, V>
where
    K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
    V: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        if deserializer.is_human_readable() {
            deserializer.deserialize_map(HumanReadableVisitor(PhantomData))
        } else {
            deserializer.deserialize_tuple(K::LENGTH, CompactVisitor(PhantomData))
        }
    }
}

struct HumanReadableVisitor<K, V>(PhantomData<(K, V)>);

impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor<K, V>
where
    K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
    V: Deserialize<'de>,
{
    type Value = EnumMap<K, V>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a map")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut access: M) -> Result<Self::Value, M::Error> {
        let mut entries = EnumMap::default();
        while let Some((key, value)) = access.next_entry()? {
            entries[key] = Some(value);
        }
        for value in entries.values() {
            value
                .as_ref()
                .ok_or_else(|| M::Error::custom("key not specified"))?;
        }
        Ok(enum_map! { key => entries[key].take().unwrap() })
    }

An iterator visiting all values mutably. The iterator type is &mut V.

Examples
use enum_map::enum_map;

let mut map = enum_map! { _ => 2 };
for value in map.values_mut() {
    *value += 2;
}
assert_eq!(map[false], 4);
assert_eq!(map[true], 4);
Examples found in repository?
src/serde.rs (line 81)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    fn visit_seq<M: SeqAccess<'de>>(self, mut access: M) -> Result<Self::Value, M::Error> {
        let mut entries = EnumMap::default();
        let len = entries.len();
        {
            let mut iter = entries.values_mut();
            while let Some(place) = iter.next() {
                *place = Some(access.next_element()?.ok_or_else(|| {
                    M::Error::invalid_length(
                        len - iter.len() - 1,
                        &"a sequence with as many elements as there are variants",
                    )
                })?);
            }
        }
        Ok(enum_map! { key => entries[key].take().unwrap() })
    }

Creates a consuming iterator visiting all the values. The map cannot be used after calling this. The iterator element type is V.

Examples
use enum_map::enum_map;

let mut map = enum_map! { false => "hello", true => "goodbye" };
assert_eq!(map.into_values().collect::<Vec<_>>(), ["hello", "goodbye"]);

Clear enum map with default values.

Examples
use enum_map::{Enum, EnumMap};

#[derive(Enum)]
enum Example {
    A,
    B,
}

let mut enum_map = EnumMap::<_, String>::default();
enum_map[Example::B] = "foo".into();
enum_map.clear();
assert_eq!(enum_map[Example::A], "");
assert_eq!(enum_map[Example::B], "");

Creates an enum map from array.

Returns an iterator over enum map.

The iteration order is deterministic, and when using Enum derive it will be the order in which enum variants are declared.

Examples
use enum_map::{enum_map, Enum};

#[derive(Enum, PartialEq)]
enum E {
    A,
    B,
    C,
}

let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
assert!(map.iter().eq([(E::A, &1), (E::B, &2), (E::C, &3)]));

Returns a mutable iterator over enum map.

Returns number of elements in enum map.

Examples found in repository?
src/iter.rs (line 246)
245
246
247
248
249
250
251
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        IntoIter {
            map: ManuallyDrop::new(self),
            alive: 0..len,
        }
    }
More examples
Hide additional examples
src/serde.rs (line 13)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            serializer.collect_map(self)
        } else {
            let mut tup = serializer.serialize_tuple(self.len())?;
            for value in self.values() {
                tup.serialize_element(value)?;
            }
            tup.end()
        }
    }
}

/// Requires crate feature `"serde"`
impl<'de, K, V> Deserialize<'de> for EnumMap<K, V>
where
    K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
    V: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        if deserializer.is_human_readable() {
            deserializer.deserialize_map(HumanReadableVisitor(PhantomData))
        } else {
            deserializer.deserialize_tuple(K::LENGTH, CompactVisitor(PhantomData))
        }
    }
}

struct HumanReadableVisitor<K, V>(PhantomData<(K, V)>);

impl<'de, K, V> de::Visitor<'de> for HumanReadableVisitor<K, V>
where
    K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
    V: Deserialize<'de>,
{
    type Value = EnumMap<K, V>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a map")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut access: M) -> Result<Self::Value, M::Error> {
        let mut entries = EnumMap::default();
        while let Some((key, value)) = access.next_entry()? {
            entries[key] = Some(value);
        }
        for value in entries.values() {
            value
                .as_ref()
                .ok_or_else(|| M::Error::custom("key not specified"))?;
        }
        Ok(enum_map! { key => entries[key].take().unwrap() })
    }
}

struct CompactVisitor<K, V>(PhantomData<(K, V)>);

impl<'de, K, V> de::Visitor<'de> for CompactVisitor<K, V>
where
    K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
    V: Deserialize<'de>,
{
    type Value = EnumMap<K, V>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a sequence")
    }

    fn visit_seq<M: SeqAccess<'de>>(self, mut access: M) -> Result<Self::Value, M::Error> {
        let mut entries = EnumMap::default();
        let len = entries.len();
        {
            let mut iter = entries.values_mut();
            while let Some(place) = iter.next() {
                *place = Some(access.next_element()?.ok_or_else(|| {
                    M::Error::invalid_length(
                        len - iter.len() - 1,
                        &"a sequence with as many elements as there are variants",
                    )
                })?);
            }
        }
        Ok(enum_map! { key => entries[key].take().unwrap() })
    }

Swaps two indexes.

Examples
use enum_map::enum_map;

let mut map = enum_map! { false => 0, true => 1 };
map.swap(false, true);
assert_eq!(map[false], 1);
assert_eq!(map[true], 0);

Consumes an enum map and returns the underlying array.

The order of elements is deterministic, and when using Enum derive it will be the order in which enum variants are declared.

Examples
use enum_map::{enum_map, Enum};

#[derive(Enum, PartialEq)]
enum E {
    A,
    B,
    C,
}

let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
assert_eq!(map.into_array(), [1, 2, 3]);

Converts an enum map to a slice representing values.

The order of elements is deterministic, and when using Enum derive it will be the order in which enum variants are declared.

Examples
use enum_map::{enum_map, Enum};

#[derive(Enum, PartialEq)]
enum E {
    A,
    B,
    C,
}

let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
assert_eq!(map.as_slice(), &[1, 2, 3]);
Examples found in repository?
src/enum_map_impls.rs (line 48)
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    fn index(&self, key: K) -> &V {
        &self.as_slice()[key.into_usize()]
    }
}

impl<K: EnumArray<V>, V> IndexMut<K> for EnumMap<K, V> {
    #[inline]
    fn index_mut(&mut self, key: K) -> &mut V {
        &mut self.as_mut_slice()[key.into_usize()]
    }
}

// Implementations provided by derive attribute are too specific, and put requirements on K.
// This is caused by rust-lang/rust#26925.
impl<K: EnumArray<V>, V> Clone for EnumMap<K, V>
where
    K::Array: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        EnumMap {
            array: self.array.clone(),
        }
    }
}

impl<K: EnumArray<V>, V> Copy for EnumMap<K, V> where K::Array: Copy {}

impl<K: EnumArray<V>, V: PartialEq> PartialEq for EnumMap<K, V> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<K: EnumArray<V>, V: Eq> Eq for EnumMap<K, V> {}

impl<K: EnumArray<V>, V: Hash> Hash for EnumMap<K, V> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
More examples
Hide additional examples
src/iter.rs (line 96)
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    fn into_iter(self) -> Self::IntoIter {
        Iter {
            _phantom: PhantomData,
            iterator: self.as_slice().iter().enumerate(),
        }
    }
}

/// Mutable map iterator
///
/// This struct is created by `iter_mut` method or `into_iter` on a mutable
/// reference to `EnumMap`.
///
/// # Examples
///
/// ```
/// use enum_map::{enum_map, Enum};
///
/// #[derive(Debug, Enum)]
/// enum Example {
///     A,
///     B,
///     C,
/// }
///
/// let mut map = enum_map! { Example::A => 3, _ => 0 };
/// for (_, value) in &mut map {
///     *value += 1;
/// }
/// assert_eq!(map, enum_map! { Example::A => 4, _ => 1 });
/// ```
#[derive(Debug)]
pub struct IterMut<'a, K, V: 'a> {
    _phantom: PhantomData<fn() -> K>,
    iterator: Enumerate<slice::IterMut<'a, V>>,
}

impl<'a, K: EnumArray<V>, V> Iterator for IterMut<'a, K, V> {
    type Item = (K, &'a mut V);
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iterator
            .next()
            .map(|(index, item)| (K::from_usize(index), item))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iterator.size_hint()
    }

    fn fold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        self.iterator
            .map(|(index, item)| (K::from_usize(index), item))
            .fold(init, f)
    }
}

impl<'a, K: EnumArray<V>, V> DoubleEndedIterator for IterMut<'a, K, V> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iterator
            .next_back()
            .map(|(index, item)| (K::from_usize(index), item))
    }
}

impl<'a, K: EnumArray<V>, V> ExactSizeIterator for IterMut<'a, K, V> {}

impl<'a, K: EnumArray<V>, V> FusedIterator for IterMut<'a, K, V> {}

impl<'a, K: EnumArray<V>, V> IntoIterator for &'a mut EnumMap<K, V> {
    type Item = (K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        IterMut {
            _phantom: PhantomData,
            iterator: self.as_mut_slice().iter_mut().enumerate(),
        }
    }
}

/// A map iterator that moves out of map.
///
/// This struct is created by `into_iter` on `EnumMap`.
///
/// # Examples
///
/// ```
/// use enum_map::{enum_map, Enum};
///
/// #[derive(Debug, Enum)]
/// enum Example {
///     A,
///     B,
/// }
///
/// let map = enum_map! { Example::A | Example::B => String::from("123") };
/// for (_, value) in map {
///     assert_eq!(value + "4", "1234");
/// }
/// ```
pub struct IntoIter<K: EnumArray<V>, V> {
    map: ManuallyDrop<EnumMap<K, V>>,
    alive: Range<usize>,
}

impl<K: EnumArray<V>, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);
    fn next(&mut self) -> Option<(K, V)> {
        let position = self.alive.next()?;
        Some((K::from_usize(position), unsafe {
            ptr::read(&self.map.as_slice()[position])
        }))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.alive.size_hint()
    }
}

impl<K: EnumArray<V>, V> DoubleEndedIterator for IntoIter<K, V> {
    fn next_back(&mut self) -> Option<(K, V)> {
        let position = self.alive.next_back()?;
        Some((K::from_usize(position), unsafe {
            ptr::read(&self.map.as_slice()[position])
        }))
    }
}

impl<K: EnumArray<V>, V> ExactSizeIterator for IntoIter<K, V> {}

impl<K: EnumArray<V>, V> FusedIterator for IntoIter<K, V> {}

impl<K: EnumArray<V>, V> Drop for IntoIter<K, V> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(&mut self.map.as_mut_slice()[self.alive.clone()]);
        }
    }
}

impl<K: EnumArray<V>, V> IntoIterator for EnumMap<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        IntoIter {
            map: ManuallyDrop::new(self),
            alive: 0..len,
        }
    }
}

impl<K: EnumArray<V>, V> EnumMap<K, V> {
    /// An iterator visiting all values. The iterator type is `&V`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::enum_map;
    ///
    /// let map = enum_map! { false => 3, true => 4 };
    /// let mut values = map.values();
    /// assert_eq!(values.next(), Some(&3));
    /// assert_eq!(values.next(), Some(&4));
    /// assert_eq!(values.next(), None);
    /// ```
    #[inline]
    pub fn values(&self) -> Values<V> {
        Values(self.as_slice().iter())
    }
src/lib.rs (line 419)
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    pub fn map<F, T>(self, mut f: F) -> EnumMap<K, T>
    where
        F: FnMut(K, V) -> T,
        K: EnumArray<T>,
    {
        struct DropOnPanic<K, V>
        where
            K: EnumArray<V>,
        {
            position: usize,
            map: ManuallyDrop<EnumMap<K, V>>,
        }
        impl<K, V> Drop for DropOnPanic<K, V>
        where
            K: EnumArray<V>,
        {
            fn drop(&mut self) {
                unsafe {
                    ptr::drop_in_place(&mut self.map.as_mut_slice()[self.position..]);
                }
            }
        }
        let mut drop_protect = DropOnPanic {
            position: 0,
            map: ManuallyDrop::new(self),
        };
        enum_map! {
            k => {
                let value = unsafe { ptr::read(&drop_protect.map.as_slice()[drop_protect.position]) };
                drop_protect.position += 1;
                f(k, value)
            }
        }
    }

Converts a mutable enum map to a mutable slice representing values.

Examples found in repository?
src/enum_map_impls.rs (line 55)
54
55
56
    fn index_mut(&mut self, key: K) -> &mut V {
        &mut self.as_mut_slice()[key.into_usize()]
    }
More examples
Hide additional examples
src/lib.rs (line 256)
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
    pub fn clear(&mut self) {
        for v in self.as_mut_slice() {
            *v = V::default();
        }
    }
}

#[allow(clippy::len_without_is_empty)]
impl<K: EnumArray<V>, V> EnumMap<K, V> {
    /// Creates an enum map from array.
    #[inline]
    pub const fn from_array(array: K::Array) -> EnumMap<K, V> {
        EnumMap { array }
    }

    /// Returns an iterator over enum map.
    ///
    /// The iteration order is deterministic, and when using [macro@Enum] derive
    /// it will be the order in which enum variants are declared.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::{enum_map, Enum};
    ///
    /// #[derive(Enum, PartialEq)]
    /// enum E {
    ///     A,
    ///     B,
    ///     C,
    /// }
    ///
    /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
    /// assert!(map.iter().eq([(E::A, &1), (E::B, &2), (E::C, &3)]));
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<K, V> {
        self.into_iter()
    }

    /// Returns a mutable iterator over enum map.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<K, V> {
        self.into_iter()
    }

    /// Returns number of elements in enum map.
    #[inline]
    #[allow(clippy::unused_self)]
    pub const fn len(&self) -> usize {
        K::Array::LENGTH
    }

    /// Swaps two indexes.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::enum_map;
    ///
    /// let mut map = enum_map! { false => 0, true => 1 };
    /// map.swap(false, true);
    /// assert_eq!(map[false], 1);
    /// assert_eq!(map[true], 0);
    /// ```
    #[inline]
    pub fn swap(&mut self, a: K, b: K) {
        self.as_mut_slice().swap(a.into_usize(), b.into_usize());
    }

    /// Consumes an enum map and returns the underlying array.
    ///
    /// The order of elements is deterministic, and when using [macro@Enum]
    /// derive it will be the order in which enum variants are declared.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::{enum_map, Enum};
    ///
    /// #[derive(Enum, PartialEq)]
    /// enum E {
    ///     A,
    ///     B,
    ///     C,
    /// }
    ///
    /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
    /// assert_eq!(map.into_array(), [1, 2, 3]);
    /// ```
    pub fn into_array(self) -> K::Array {
        self.array
    }

    /// Converts an enum map to a slice representing values.
    ///
    /// The order of elements is deterministic, and when using [macro@Enum]
    /// derive it will be the order in which enum variants are declared.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::{enum_map, Enum};
    ///
    /// #[derive(Enum, PartialEq)]
    /// enum E {
    ///     A,
    ///     B,
    ///     C,
    /// }
    ///
    /// let map = enum_map! { E::A => 1, E::B => 2, E::C => 3};
    /// assert_eq!(map.as_slice(), &[1, 2, 3]);
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[V] {
        unsafe { slice::from_raw_parts(ptr::addr_of!(self.array).cast(), K::Array::LENGTH) }
    }

    /// Converts a mutable enum map to a mutable slice representing values.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [V] {
        unsafe { slice::from_raw_parts_mut(ptr::addr_of_mut!(self.array).cast(), K::Array::LENGTH) }
    }

    /// Returns an enum map with function `f` applied to each element in order.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::enum_map;
    ///
    /// let a = enum_map! { false => 0, true => 1 };
    /// let b = a.map(|_, x| f64::from(x) + 0.5);
    /// assert_eq!(b, enum_map! { false => 0.5, true => 1.5 });
    /// ```
    pub fn map<F, T>(self, mut f: F) -> EnumMap<K, T>
    where
        F: FnMut(K, V) -> T,
        K: EnumArray<T>,
    {
        struct DropOnPanic<K, V>
        where
            K: EnumArray<V>,
        {
            position: usize,
            map: ManuallyDrop<EnumMap<K, V>>,
        }
        impl<K, V> Drop for DropOnPanic<K, V>
        where
            K: EnumArray<V>,
        {
            fn drop(&mut self) {
                unsafe {
                    ptr::drop_in_place(&mut self.map.as_mut_slice()[self.position..]);
                }
            }
src/iter.rs (line 174)
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
    fn into_iter(self) -> Self::IntoIter {
        IterMut {
            _phantom: PhantomData,
            iterator: self.as_mut_slice().iter_mut().enumerate(),
        }
    }
}

/// A map iterator that moves out of map.
///
/// This struct is created by `into_iter` on `EnumMap`.
///
/// # Examples
///
/// ```
/// use enum_map::{enum_map, Enum};
///
/// #[derive(Debug, Enum)]
/// enum Example {
///     A,
///     B,
/// }
///
/// let map = enum_map! { Example::A | Example::B => String::from("123") };
/// for (_, value) in map {
///     assert_eq!(value + "4", "1234");
/// }
/// ```
pub struct IntoIter<K: EnumArray<V>, V> {
    map: ManuallyDrop<EnumMap<K, V>>,
    alive: Range<usize>,
}

impl<K: EnumArray<V>, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);
    fn next(&mut self) -> Option<(K, V)> {
        let position = self.alive.next()?;
        Some((K::from_usize(position), unsafe {
            ptr::read(&self.map.as_slice()[position])
        }))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.alive.size_hint()
    }
}

impl<K: EnumArray<V>, V> DoubleEndedIterator for IntoIter<K, V> {
    fn next_back(&mut self) -> Option<(K, V)> {
        let position = self.alive.next_back()?;
        Some((K::from_usize(position), unsafe {
            ptr::read(&self.map.as_slice()[position])
        }))
    }
}

impl<K: EnumArray<V>, V> ExactSizeIterator for IntoIter<K, V> {}

impl<K: EnumArray<V>, V> FusedIterator for IntoIter<K, V> {}

impl<K: EnumArray<V>, V> Drop for IntoIter<K, V> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            ptr::drop_in_place(&mut self.map.as_mut_slice()[self.alive.clone()]);
        }
    }
}

impl<K: EnumArray<V>, V> IntoIterator for EnumMap<K, V> {
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        let len = self.len();
        IntoIter {
            map: ManuallyDrop::new(self),
            alive: 0..len,
        }
    }
}

impl<K: EnumArray<V>, V> EnumMap<K, V> {
    /// An iterator visiting all values. The iterator type is `&V`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::enum_map;
    ///
    /// let map = enum_map! { false => 3, true => 4 };
    /// let mut values = map.values();
    /// assert_eq!(values.next(), Some(&3));
    /// assert_eq!(values.next(), Some(&4));
    /// assert_eq!(values.next(), None);
    /// ```
    #[inline]
    pub fn values(&self) -> Values<V> {
        Values(self.as_slice().iter())
    }

    /// An iterator visiting all values mutably. The iterator type is `&mut V`.
    ///
    /// # Examples
    ///
    /// ```
    /// use enum_map::enum_map;
    ///
    /// let mut map = enum_map! { _ => 2 };
    /// for value in map.values_mut() {
    ///     *value += 2;
    /// }
    /// assert_eq!(map[false], 4);
    /// assert_eq!(map[true], 4);
    /// ```
    #[inline]
    pub fn values_mut(&mut self) -> ValuesMut<V> {
        ValuesMut(self.as_mut_slice().iter_mut())
    }

Returns an enum map with function f applied to each element in order.

Examples
use enum_map::enum_map;

let a = enum_map! { false => 0, true => 1 };
let b = a.map(|_, x| f64::from(x) + 0.5);
assert_eq!(b, enum_map! { false => 0.5, true => 1.5 });

Trait Implementations§

Requires crate feature "arbitrary"

Generate an arbitrary value of Self from the given unstructured data. Read more
Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Generate an arbitrary value of Self from the entirety of the given unstructured data. Read more
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more

Requires crate feature "serde"

Deserialize this value from the given Serde deserializer. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Creates a value from an iterator. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more
Performs the mutable indexing (container[index]) operation. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more

Requires crate feature "serde"

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.