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§
source§impl<K: EnumArray<V>, V> EnumMap<K, V>
impl<K: EnumArray<V>, V> EnumMap<K, V>
sourcepub fn values(&self) -> Values<'_, V> ⓘ
pub fn values(&self) -> Values<'_, 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);
Examples found in repository?
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() })
}
sourcepub fn values_mut(&mut self) -> ValuesMut<'_, V> ⓘ
pub fn values_mut(&mut self) -> ValuesMut<'_, V> ⓘ
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?
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() })
}
sourcepub fn into_values(self) -> IntoValues<K, V> ⓘ
pub fn into_values(self) -> IntoValues<K, V> ⓘ
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"]);
source§impl<K: EnumArray<V>, V: Default> EnumMap<K, V>
impl<K: EnumArray<V>, V: Default> EnumMap<K, V>
sourcepub fn clear(&mut self)
pub fn clear(&mut self)
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], "");
source§impl<K: EnumArray<V>, V> EnumMap<K, V>
impl<K: EnumArray<V>, V> EnumMap<K, V>
sourcepub const fn from_array(array: K::Array) -> EnumMap<K, V>
pub const fn from_array(array: K::Array) -> EnumMap<K, V>
Creates an enum map from array.
sourcepub fn iter(&self) -> Iter<'_, K, V> ⓘ
pub fn iter(&self) -> Iter<'_, K, V> ⓘ
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)]));
sourcepub const fn len(&self) -> usize
pub const fn len(&self) -> usize
Returns number of elements in enum map.
Examples found in repository?
More examples
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() })
}
sourcepub fn swap(&mut self, a: K, b: K)
pub fn swap(&mut self, a: K, b: K)
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);
sourcepub fn into_array(self) -> K::Array
pub fn into_array(self) -> K::Array
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]);
sourcepub fn as_slice(&self) -> &[V] ⓘ
pub fn as_slice(&self) -> &[V] ⓘ
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?
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
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())
}
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)
}
}
}
sourcepub fn as_mut_slice(&mut self) -> &mut [V] ⓘ
pub fn as_mut_slice(&mut self) -> &mut [V] ⓘ
Converts a mutable enum map to a mutable slice representing values.
Examples found in repository?
More examples
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..]);
}
}
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())
}
sourcepub fn map<F, T>(self, f: F) -> EnumMap<K, T>where
F: FnMut(K, V) -> T,
K: EnumArray<T>,
pub fn map<F, T>(self, f: F) -> EnumMap<K, T>where
F: FnMut(K, V) -> T,
K: EnumArray<T>,
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§
source§impl<'a, K: EnumArray<V>, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap<K, V>
impl<'a, K: EnumArray<V>, V: Arbitrary<'a>> Arbitrary<'a> for EnumMap<K, V>
Requires crate feature "arbitrary"
source§fn arbitrary(u: &mut Unstructured<'a>) -> Result<EnumMap<K, V>>
fn arbitrary(u: &mut Unstructured<'a>) -> Result<EnumMap<K, V>>
Self
from the given unstructured data. Read moresource§fn size_hint(depth: usize) -> (usize, Option<usize>)
fn size_hint(depth: usize) -> (usize, Option<usize>)
Unstructured
this type
needs to construct itself. Read moresource§fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>
fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>
Self
from the entirety of the given
unstructured data. Read moresource§impl<'de, K, V> Deserialize<'de> for EnumMap<K, V>where
K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
V: Deserialize<'de>,
impl<'de, K, V> Deserialize<'de> for EnumMap<K, V>where
K: EnumArray<V> + EnumArray<Option<V>> + Deserialize<'de>,
V: Deserialize<'de>,
Requires crate feature "serde"
source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
source§impl<'a, K, V> Extend<(&'a K, &'a V)> for EnumMap<K, V>where
K: EnumArray<V> + Copy,
V: Copy,
impl<'a, K, V> Extend<(&'a K, &'a V)> for EnumMap<K, V>where
K: EnumArray<V> + Copy,
V: Copy,
source§fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<K: EnumArray<V>, V> Extend<(K, V)> for EnumMap<K, V>
impl<K: EnumArray<V>, V> Extend<(K, V)> for EnumMap<K, V>
source§fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I)
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)source§impl<'a, K: EnumArray<V>, V> IntoIterator for &'a EnumMap<K, V>
impl<'a, K: EnumArray<V>, V> IntoIterator for &'a EnumMap<K, V>
source§impl<'a, K: EnumArray<V>, V> IntoIterator for &'a mut EnumMap<K, V>
impl<'a, K: EnumArray<V>, V> IntoIterator for &'a mut EnumMap<K, V>
source§impl<K: EnumArray<V>, V> IntoIterator for EnumMap<K, V>
impl<K: EnumArray<V>, V> IntoIterator for EnumMap<K, V>
source§impl<K: EnumArray<V>, V: PartialEq> PartialEq<EnumMap<K, V>> for EnumMap<K, V>
impl<K: EnumArray<V>, V: PartialEq> PartialEq<EnumMap<K, V>> for EnumMap<K, V>
source§impl<K: EnumArray<V> + Serialize, V: Serialize> Serialize for EnumMap<K, V>
impl<K: EnumArray<V> + Serialize, V: Serialize> Serialize for EnumMap<K, V>
Requires crate feature "serde"