Skip to content

Commit

Permalink
Auto merge of #281 - cole-miller:get-each-mut-array-map, r=Amanieu
Browse files Browse the repository at this point in the history
Replace some custom unsafe code with `array::map`

`<[T; N]>::map` was recently stabilized (rust-lang/rust#87174). It's not on any stable or beta yet, but we're only using it here with `cfg(feature = "nightly")` (in the functions `HashMap::get_each_mut` and `HashMap::get_each_key_value_mut`).
  • Loading branch information
bors committed Jul 19, 2021
2 parents d5002fa + bf3247f commit a036b25
Showing 1 changed file with 3 additions and 23 deletions.
26 changes: 3 additions & 23 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ use core::hash::{BuildHasher, Hash};
use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::mem;
#[cfg(feature = "nightly")]
use core::mem::MaybeUninit;
use core::ops::Index;

/// Default hasher for `HashMap`.
Expand Down Expand Up @@ -1149,16 +1147,7 @@ where
K: Borrow<Q>,
Q: Hash + Eq,
{
let mut pairs = self.get_each_inner_mut(ks);
// TODO use `MaybeUninit::uninit_array` here instead once that's stable.
let mut out: [MaybeUninit<Result<&'_ mut V, UnavailableMutError>>; N] =
unsafe { MaybeUninit::uninit().assume_init() };
for i in 0..N {
out[i] = MaybeUninit::new(
mem::replace(&mut pairs[i], Err(UnavailableMutError::Absent)).map(|(_, v)| v),
);
}
unsafe { MaybeUninit::array_assume_init(out) }
self.get_each_inner_mut(ks).map(|res| res.map(|(_, v)| v))
}

/// Attempts to get mutable references to `N` values in the map at once, with immutable
Expand Down Expand Up @@ -1208,17 +1197,8 @@ where
K: Borrow<Q>,
Q: Hash + Eq,
{
let mut pairs = self.get_each_inner_mut(ks);
// TODO use `MaybeUninit::uninit_array` here instead once that's stable.
let mut out: [MaybeUninit<Result<(&'_ K, &'_ mut V), UnavailableMutError>>; N] =
unsafe { MaybeUninit::uninit().assume_init() };
for i in 0..N {
out[i] = MaybeUninit::new(
mem::replace(&mut pairs[i], Err(UnavailableMutError::Absent))
.map(|(k, v)| (&*k, v)),
);
}
unsafe { MaybeUninit::array_assume_init(out) }
self.get_each_inner_mut(ks)
.map(|res| res.map(|(k, v)| (&*k, v)))
}

#[cfg(feature = "nightly")]
Expand Down

0 comments on commit a036b25

Please sign in to comment.