Skip to content

Commit

Permalink
Reduce duplicate in liballoc reserve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pickfire committed Aug 22, 2020
1 parent 5f6bd6e commit c5975e9
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions library/alloc/src/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
/// # }
/// ```
pub fn reserve(&mut self, len: usize, additional: usize) {
match self.try_reserve(len, additional) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { /* yay */ }
}
handle_reserve(self.try_reserve(len, additional));
}

/// The same as `reserve`, but returns on errors instead of panicking or aborting.
Expand Down Expand Up @@ -337,11 +333,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
///
/// Aborts on OOM.
pub fn reserve_exact(&mut self, len: usize, additional: usize) {
match self.try_reserve_exact(len, additional) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { /* yay */ }
}
handle_reserve(self.try_reserve_exact(len, additional));
}

/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
Expand All @@ -364,11 +356,7 @@ impl<T, A: AllocRef> RawVec<T, A> {
///
/// Aborts on OOM.
pub fn shrink_to_fit(&mut self, amount: usize) {
match self.shrink(amount) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { /* yay */ }
}
handle_reserve(self.shrink(amount));
}
}

Expand Down Expand Up @@ -510,6 +498,16 @@ unsafe impl<#[may_dangle] T, A: AllocRef> Drop for RawVec<T, A> {
}
}

// Central function for reserve error handling.
#[inline]
fn handle_reserve(result: Result<(), TryReserveError>) {
match result {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocError { layout, .. }) => handle_alloc_error(layout),
Ok(()) => { /* yay */ }
}
}

// We need to guarantee the following:
// * We don't ever allocate `> isize::MAX` byte-size objects.
// * We don't overflow `usize::MAX` and actually allocate too little.
Expand Down

0 comments on commit c5975e9

Please sign in to comment.