Skip to content

Commit 5b8e177

Browse files
committed
Create lang item array and add map fn
This creates the language item for arrays, and adds the map fn which is like map in options or iterators. It currently allocates an extra array, unfortunately. Added fixme for transmuting Fix typo
1 parent ec9d524 commit 5b8e177

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

library/core/src/array/mod.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,3 +364,30 @@ macro_rules! array_impl_default {
364364
}
365365

366366
array_impl_default! {32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
367+
368+
#[lang = "array"]
369+
#[cfg(not(bootstrap))]
370+
impl<T, const N: usize> [T; N] {
371+
/// Returns an array of the same size as self, with `f` applied to each element.
372+
///
373+
/// # Examples
374+
/// ```
375+
/// let x = [1,2,3];
376+
/// let y = x.map(|v| v + 1);
377+
/// assert_eq!(y, [2,3,4]);
378+
/// ```
379+
#[unstable(feature = "array_map", issue = "77777")]
380+
fn map<F, S>(self, f: F) -> [S; N]
381+
where
382+
F: FnMut(T) -> S,
383+
{
384+
use crate::mem::MaybeUninit;
385+
let dst = MaybeUninit::uninit_array::<N>();
386+
for (i, e) in self.into_iter().enumerate() {
387+
dst[i] = MaybeUninit::new(f(e));
388+
}
389+
// FIXME convert to crate::mem::transmute when works with generics
390+
// unsafe { crate::mem::transmute::<[MaybeUninit<S>; N], [S; N]>(dst) }
391+
unsafe { (&mut dst as *mut _ as *mut [S; N]).read() }
392+
}
393+
}

src/librustc_hir/lang_items.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@ language_item_table! {
157157
BoolImplItem, sym::bool, bool_impl, Target::Impl;
158158
CharImplItem, sym::char, char_impl, Target::Impl;
159159
StrImplItem, sym::str, str_impl, Target::Impl;
160+
ArrayImplItem, sym::array, array_impl, Target::Impl;
160161
SliceImplItem, sym::slice, slice_impl, Target::Impl;
161162
SliceU8ImplItem, sym::slice_u8, slice_u8_impl, Target::Impl;
162163
StrAllocImplItem, sym::str_alloc, str_alloc_impl, Target::Impl;

0 commit comments

Comments
 (0)