]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/vec/spec_from_elem.rs
Merge commit '63734fcdd718cca089f84c42f3a42c0096cfd431' into sync_cg_clif-2022-05-15
[rust.git] / library / alloc / src / vec / spec_from_elem.rs
1 use crate::alloc::Allocator;
2 use crate::raw_vec::RawVec;
3 use core::ptr::{self};
4
5 use super::{ExtendElement, IsZero, Vec};
6
7 // Specialization trait used for Vec::from_elem
8 pub(super) trait SpecFromElem: Sized {
9     fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A>;
10 }
11
12 impl<T: Clone> SpecFromElem for T {
13     default fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A> {
14         let mut v = Vec::with_capacity_in(n, alloc);
15         v.extend_with(n, ExtendElement(elem));
16         v
17     }
18 }
19
20 impl SpecFromElem for i8 {
21     #[inline]
22     fn from_elem<A: Allocator>(elem: i8, n: usize, alloc: A) -> Vec<i8, A> {
23         if elem == 0 {
24             return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
25         }
26         unsafe {
27             let mut v = Vec::with_capacity_in(n, alloc);
28             ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
29             v.set_len(n);
30             v
31         }
32     }
33 }
34
35 impl SpecFromElem for u8 {
36     #[inline]
37     fn from_elem<A: Allocator>(elem: u8, n: usize, alloc: A) -> Vec<u8, A> {
38         if elem == 0 {
39             return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
40         }
41         unsafe {
42             let mut v = Vec::with_capacity_in(n, alloc);
43             ptr::write_bytes(v.as_mut_ptr(), elem, n);
44             v.set_len(n);
45             v
46         }
47     }
48 }
49
50 impl<T: Clone + IsZero> SpecFromElem for T {
51     #[inline]
52     fn from_elem<A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
53         if elem.is_zero() {
54             return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
55         }
56         let mut v = Vec::with_capacity_in(n, alloc);
57         v.extend_with(n, ExtendElement(elem));
58         v
59     }
60 }