1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
pub trait VecExt<T>
{
fn try_with_capacity(capacity: usize) -> Result<Vec<T>, AllocError>;
fn new_populated_by_copy(capacity: usize, copy: T) -> Result<Vec<T>, AllocError> where T: Copy;
fn new_populated_fallibly<Populator: FnOnce(usize) -> Result<T, AllocError> + Copy>(capacity: usize, populator: Populator) -> Result<Vec<T>, AllocError>;
#[doc(hidden)]
fn set_length(&mut self, length: usize);
}
impl<T> VecExt<T> for Vec<T>
{
#[inline(always)]
fn try_with_capacity(capacity: usize) -> Result<Vec<T>, AllocError>
{
let mut new_vec = Vec::new();
if new_vec.try_reserve_exact(capacity).is_err()
{
return Err(AllocError)
}
Ok(new_vec)
}
#[inline(always)]
fn new_populated_by_copy(capacity: usize, copy: T) -> Result<Vec<T>, AllocError>
where T: Copy
{
let mut vec = Self::try_with_capacity(capacity)?;
let pointer = vec.as_mut_ptr();
for index in 0 .. capacity
{
unsafe { pointer.add(index).write(copy) };
}
vec.set_length(capacity);
Ok(vec)
}
#[inline(always)]
fn new_populated_fallibly<Populator: FnOnce(usize) -> Result<T, AllocError> + Copy>(capacity: usize, populator: Populator) -> Result<Vec<T>, AllocError>
{
let mut vec = Self::try_with_capacity(capacity)?;
let pointer = vec.as_mut_ptr();
for index in 0 .. capacity
{
let element = match populator(index)
{
Err(AllocError) =>
{
vec.set_length(index);
return Err(AllocError)
}
Ok(child_or_auxillary) => child_or_auxillary,
};
unsafe { pointer.add(index).write(element) };
}
vec.set_length(capacity);
Ok(vec)
}
#[inline(always)]
fn set_length(&mut self, length: usize)
{
debug_assert!(length <= self.capacity());
unsafe { self.set_len(length) };
}
}