Skip to content

Commit

Permalink
Introduce from_iter1_with_capacity to vector collections.
Browse files Browse the repository at this point in the history
  • Loading branch information
olson-sean-k committed Oct 22, 2024
1 parent 01f3471 commit c3bd215
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
18 changes: 14 additions & 4 deletions src/vec1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,20 @@ impl<T> Vec1<T> {
}

pub fn from_one_with_capacity(item: T, capacity: usize) -> Self {
let mut items = Vec::with_capacity(capacity);
items.push(item);
// SAFETY: `items` must contain `item` and therefore is non-empty here, because `push`
// either pushes the item or panics.
Vec1::from_iter1_with_capacity([item], capacity)
}

pub fn from_iter1_with_capacity<U>(items: U, capacity: usize) -> Self
where
U: IntoIterator1<Item = T>,
{
let items = {
let mut xs = Vec::with_capacity(capacity);
xs.extend(items);
xs
};
// SAFETY: The input iterator `items` is non-empty and `extend` either pushes one or more
// items or panics, so `items` must be non-empty here.
unsafe { Vec1::from_vec_unchecked(items) }
}

Expand Down
18 changes: 14 additions & 4 deletions src/vec_deque1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,20 @@ impl<T> VecDeque1<T> {
}

pub fn from_one_with_capacity(item: T, capacity: usize) -> Self {
let mut items = VecDeque::with_capacity(capacity);
items.push_back(item);
// SAFETY: `items` must contain `item` and therefore is non-empty here, because `push_back`
// either pushes the item or panics.
VecDeque1::from_iter1_with_capacity([item], capacity)
}

pub fn from_iter1_with_capacity<U>(items: U, capacity: usize) -> Self
where
U: IntoIterator1<Item = T>,
{
let items = {
let mut xs = VecDeque::with_capacity(capacity);
xs.extend(items);
xs
};
// SAFETY: The input iterator `items` is non-empty and `extend` either pushes one or more
// items or panics, so `items` must be non-empty here.
unsafe { VecDeque1::from_vec_deque_unchecked(items) }
}

Expand Down

0 comments on commit c3bd215

Please sign in to comment.