Skip to content

Commit b7a85c7

Browse files
committed
feat: specialize SpecFromElem for ()
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 <me@progrm-jarvis.ru>
1 parent 79e961f commit b7a85c7

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

library/alloc/src/vec/spec_from_elem.rs

+20-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::ptr;
1+
use core::{mem::SizedTypeProperties, ptr};
22

33
use crate::alloc::Allocator;
44
use crate::raw_vec::RawVec;
@@ -36,12 +36,12 @@ impl SpecFromElem for i8 {
3636
if elem == 0 {
3737
return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
3838
}
39+
let mut v = Vec::with_capacity_in(n, alloc);
3940
unsafe {
40-
let mut v = Vec::with_capacity_in(n, alloc);
4141
ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
4242
v.set_len(n);
43-
v
4443
}
44+
v
4545
}
4646
}
4747

@@ -51,11 +51,26 @@ impl SpecFromElem for u8 {
5151
if elem == 0 {
5252
return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
5353
}
54+
let mut v = Vec::with_capacity_in(n, alloc);
5455
unsafe {
55-
let mut v = Vec::with_capacity_in(n, alloc);
5656
ptr::write_bytes(v.as_mut_ptr(), elem, n);
5757
v.set_len(n);
58-
v
5958
}
59+
v
60+
}
61+
}
62+
63+
// A better way would be to implement this for all ZSTs which are `Copy` and have trivial `Clone`
64+
// but this cannot be implemented currently
65+
impl SpecFromElem for () {
66+
#[inline]
67+
fn from_elem<A: Allocator>(elem: (), n: usize, alloc: A) -> Vec<u8, A> {
68+
let mut v = Vec::with_capacity_in(n, alloc);
69+
// SAFETY: the capacity has just been set to `n` and `()`
70+
// is a ZST with trivial `Clone` implementation
71+
unsafe {
72+
v.set_len(n);
73+
}
74+
v
6075
}
6176
}

0 commit comments

Comments
 (0)