Skip to content

Commit

Permalink
feat: specialize SpecFromElem for ()
Browse files Browse the repository at this point in the history
While a better approach would be to implement it for all ZSTs
which are `Copy` and have trivial `Clone`,
the last property cannot be detected for now.

Signed-off-by: Petr Portnov <[email protected]>
  • Loading branch information
JarvisCraft committed Nov 20, 2023
1 parent 79e961f commit 2fd9442
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions library/alloc/src/vec/spec_from_elem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ impl SpecFromElem for i8 {
if elem == 0 {
return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
}
let mut v = Vec::with_capacity_in(n, alloc);
unsafe {
let mut v = Vec::with_capacity_in(n, alloc);
ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
v.set_len(n);
v
}
v
}
}

Expand All @@ -51,11 +51,26 @@ impl SpecFromElem for u8 {
if elem == 0 {
return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
}
let mut v = Vec::with_capacity_in(n, alloc);
unsafe {
let mut v = Vec::with_capacity_in(n, alloc);
ptr::write_bytes(v.as_mut_ptr(), elem, n);
v.set_len(n);
v
}
v
}
}

// A better way would be to implement this for all ZSTs which are `Copy` and have trivial `Clone`
// but this cannot be implemented currently
impl SpecFromElem for () {
#[inline]
fn from_elem<A: Allocator>(elem: (), n: usize, alloc: A) -> Vec<(), A> {
let mut v = Vec::with_capacity_in(n, alloc);
// SAFETY: the capacity has just been set to `n` and `()`
// is a ZST with trivial `Clone` implementation
unsafe {
v.set_len(n);
}
v
}
}

0 comments on commit 2fd9442

Please sign in to comment.