1
Fork 0

Rename .cap() methods to .capacity()

... but leave the old names in there for backwards compatibility.
This commit is contained in:
Matthias Geier 2019-04-27 21:28:40 +02:00
parent c751c7a4f4
commit 0967d28be7
6 changed files with 99 additions and 92 deletions

View file

@ -98,7 +98,7 @@ impl<T> VecDeque<T> {
// For zero sized types, we are always at maximum capacity // For zero sized types, we are always at maximum capacity
MAXIMUM_ZST_CAPACITY MAXIMUM_ZST_CAPACITY
} else { } else {
self.buf.cap() self.buf.capacity()
} }
} }
@ -314,10 +314,10 @@ impl<T> VecDeque<T> {
} }
/// Frobs the head and tail sections around to handle the fact that we /// Frobs the head and tail sections around to handle the fact that we
/// just reallocated. Unsafe because it trusts old_cap. /// just reallocated. Unsafe because it trusts old_capacity.
#[inline] #[inline]
unsafe fn handle_cap_increase(&mut self, old_cap: usize) { unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
let new_cap = self.cap(); let new_capacity = self.cap();
// Move the shortest contiguous section of the ring buffer // Move the shortest contiguous section of the ring buffer
// T H // T H
@ -336,15 +336,15 @@ impl<T> VecDeque<T> {
if self.tail <= self.head { if self.tail <= self.head {
// A // A
// Nop // Nop
} else if self.head < old_cap - self.tail { } else if self.head < old_capacity - self.tail {
// B // B
self.copy_nonoverlapping(old_cap, 0, self.head); self.copy_nonoverlapping(old_capacity, 0, self.head);
self.head += old_cap; self.head += old_capacity;
debug_assert!(self.head > self.tail); debug_assert!(self.head > self.tail);
} else { } else {
// C // C
let new_tail = new_cap - (old_cap - self.tail); let new_tail = new_capacity - (old_capacity - self.tail);
self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail); self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail);
self.tail = new_tail; self.tail = new_tail;
debug_assert!(self.head < self.tail); debug_assert!(self.head < self.tail);
} }
@ -551,7 +551,7 @@ impl<T> VecDeque<T> {
if new_cap > old_cap { if new_cap > old_cap {
self.buf.reserve_exact(used_cap, new_cap - used_cap); self.buf.reserve_exact(used_cap, new_cap - used_cap);
unsafe { unsafe {
self.handle_cap_increase(old_cap); self.handle_capacity_increase(old_cap);
} }
} }
} }
@ -641,7 +641,7 @@ impl<T> VecDeque<T> {
if new_cap > old_cap { if new_cap > old_cap {
self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?; self.buf.try_reserve_exact(used_cap, new_cap - used_cap)?;
unsafe { unsafe {
self.handle_cap_increase(old_cap); self.handle_capacity_increase(old_cap);
} }
} }
Ok(()) Ok(())
@ -1873,7 +1873,7 @@ impl<T> VecDeque<T> {
let old_cap = self.cap(); let old_cap = self.cap();
self.buf.double(); self.buf.double();
unsafe { unsafe {
self.handle_cap_increase(old_cap); self.handle_capacity_increase(old_cap);
} }
debug_assert!(!self.is_full()); debug_assert!(!self.is_full());
} }
@ -2708,9 +2708,9 @@ impl<T> From<Vec<T>> for VecDeque<T> {
// We need to extend the buf if it's not a power of two, too small // We need to extend the buf if it's not a power of two, too small
// or doesn't have at least one free space // or doesn't have at least one free space
if !buf.cap().is_power_of_two() || (buf.cap() < (MINIMUM_CAPACITY + 1)) || if !buf.capacity().is_power_of_two() || (buf.capacity() < (MINIMUM_CAPACITY + 1)) ||
(buf.cap() == len) { (buf.capacity() == len) {
let cap = cmp::max(buf.cap() + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); let cap = cmp::max(buf.capacity() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
buf.reserve_exact(len, cap - len); buf.reserve_exact(len, cap - len);
} }
@ -3096,8 +3096,8 @@ mod tests {
fn test_vec_from_vecdeque() { fn test_vec_from_vecdeque() {
use crate::vec::Vec; use crate::vec::Vec;
fn create_vec_and_test_convert(cap: usize, offset: usize, len: usize) { fn create_vec_and_test_convert(capacity: usize, offset: usize, len: usize) {
let mut vd = VecDeque::with_capacity(cap); let mut vd = VecDeque::with_capacity(capacity);
for _ in 0..offset { for _ in 0..offset {
vd.push_back(0); vd.push_back(0);
vd.pop_front(); vd.pop_front();

View file

@ -34,7 +34,7 @@ use crate::boxed::Box;
/// that might occur with zero-sized types. /// that might occur with zero-sized types.
/// ///
/// However this means that you need to be careful when round-tripping this type /// However this means that you need to be careful when round-tripping this type
/// with a `Box<[T]>`: `cap()` won't yield the len. However `with_capacity`, /// with a `Box<[T]>`: `capacity()` won't yield the len. However `with_capacity`,
/// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity /// `shrink_to_fit`, and `from_box` will actually set RawVec's private capacity
/// field. This allows zero-sized types to not be special-cased by consumers of /// field. This allows zero-sized types to not be special-cased by consumers of
/// this type. /// this type.
@ -65,25 +65,25 @@ impl<T, A: Alloc> RawVec<T, A> {
/// Like `with_capacity` but parameterized over the choice of /// Like `with_capacity` but parameterized over the choice of
/// allocator for the returned RawVec. /// allocator for the returned RawVec.
#[inline] #[inline]
pub fn with_capacity_in(cap: usize, a: A) -> Self { pub fn with_capacity_in(capacity: usize, a: A) -> Self {
RawVec::allocate_in(cap, false, a) RawVec::allocate_in(capacity, false, a)
} }
/// Like `with_capacity_zeroed` but parameterized over the choice /// Like `with_capacity_zeroed` but parameterized over the choice
/// of allocator for the returned RawVec. /// of allocator for the returned RawVec.
#[inline] #[inline]
pub fn with_capacity_zeroed_in(cap: usize, a: A) -> Self { pub fn with_capacity_zeroed_in(capacity: usize, a: A) -> Self {
RawVec::allocate_in(cap, true, a) RawVec::allocate_in(capacity, true, a)
} }
fn allocate_in(cap: usize, zeroed: bool, mut a: A) -> Self { fn allocate_in(capacity: usize, zeroed: bool, mut a: A) -> Self {
unsafe { unsafe {
let elem_size = mem::size_of::<T>(); let elem_size = mem::size_of::<T>();
let alloc_size = cap.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow()); let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow()); alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
// handles ZSTs and `cap = 0` alike // handles ZSTs and `capacity = 0` alike
let ptr = if alloc_size == 0 { let ptr = if alloc_size == 0 {
NonNull::<T>::dangling() NonNull::<T>::dangling()
} else { } else {
@ -102,7 +102,7 @@ impl<T, A: Alloc> RawVec<T, A> {
RawVec { RawVec {
ptr: ptr.into(), ptr: ptr.into(),
cap, cap: capacity,
a, a,
} }
} }
@ -120,8 +120,8 @@ impl<T> RawVec<T, Global> {
} }
/// Creates a RawVec (on the system heap) with exactly the /// Creates a RawVec (on the system heap) with exactly the
/// capacity and alignment requirements for a `[T; cap]`. This is /// capacity and alignment requirements for a `[T; capacity]`. This is
/// equivalent to calling RawVec::new when `cap` is 0 or T is /// equivalent to calling RawVec::new when `capacity` is 0 or T is
/// zero-sized. Note that if `T` is zero-sized this means you will /// zero-sized. Note that if `T` is zero-sized this means you will
/// *not* get a RawVec with the requested capacity! /// *not* get a RawVec with the requested capacity!
/// ///
@ -135,14 +135,14 @@ impl<T> RawVec<T, Global> {
/// ///
/// Aborts on OOM /// Aborts on OOM
#[inline] #[inline]
pub fn with_capacity(cap: usize) -> Self { pub fn with_capacity(capacity: usize) -> Self {
RawVec::allocate_in(cap, false, Global) RawVec::allocate_in(capacity, false, Global)
} }
/// Like `with_capacity` but guarantees the buffer is zeroed. /// Like `with_capacity` but guarantees the buffer is zeroed.
#[inline] #[inline]
pub fn with_capacity_zeroed(cap: usize) -> Self { pub fn with_capacity_zeroed(capacity: usize) -> Self {
RawVec::allocate_in(cap, true, Global) RawVec::allocate_in(capacity, true, Global)
} }
} }
@ -154,10 +154,10 @@ impl<T, A: Alloc> RawVec<T, A> {
/// The ptr must be allocated (via the given allocator `a`), and with the given capacity. The /// The ptr must be allocated (via the given allocator `a`), and with the given capacity. The
/// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems). /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
/// If the ptr and capacity come from a RawVec created via `a`, then this is guaranteed. /// If the ptr and capacity come from a RawVec created via `a`, then this is guaranteed.
pub unsafe fn from_raw_parts_in(ptr: *mut T, cap: usize, a: A) -> Self { pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, a: A) -> Self {
RawVec { RawVec {
ptr: Unique::new_unchecked(ptr), ptr: Unique::new_unchecked(ptr),
cap, cap: capacity,
a, a,
} }
} }
@ -171,10 +171,10 @@ impl<T> RawVec<T, Global> {
/// The ptr must be allocated (on the system heap), and with the given capacity. The /// The ptr must be allocated (on the system heap), and with the given capacity. The
/// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems). /// capacity cannot exceed `isize::MAX` (only a concern on 32-bit systems).
/// If the ptr and capacity come from a RawVec, then this is guaranteed. /// If the ptr and capacity come from a RawVec, then this is guaranteed.
pub unsafe fn from_raw_parts(ptr: *mut T, cap: usize) -> Self { pub unsafe fn from_raw_parts(ptr: *mut T, capacity: usize) -> Self {
RawVec { RawVec {
ptr: Unique::new_unchecked(ptr), ptr: Unique::new_unchecked(ptr),
cap, cap: capacity,
a: Global, a: Global,
} }
} }
@ -191,7 +191,7 @@ impl<T> RawVec<T, Global> {
impl<T, A: Alloc> RawVec<T, A> { impl<T, A: Alloc> RawVec<T, A> {
/// Gets a raw pointer to the start of the allocation. Note that this is /// Gets a raw pointer to the start of the allocation. Note that this is
/// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must /// Unique::empty() if `capacity = 0` or T is zero-sized. In the former case, you must
/// be careful. /// be careful.
pub fn ptr(&self) -> *mut T { pub fn ptr(&self) -> *mut T {
self.ptr.as_ptr() self.ptr.as_ptr()
@ -201,7 +201,7 @@ impl<T, A: Alloc> RawVec<T, A> {
/// ///
/// This will always be `usize::MAX` if `T` is zero-sized. /// This will always be `usize::MAX` if `T` is zero-sized.
#[inline(always)] #[inline(always)]
pub fn cap(&self) -> usize { pub fn capacity(&self) -> usize {
if mem::size_of::<T>() == 0 { if mem::size_of::<T>() == 0 {
!0 !0
} else { } else {
@ -209,6 +209,12 @@ impl<T, A: Alloc> RawVec<T, A> {
} }
} }
// For backwards compatibility
#[inline(always)]
pub fn cap(&self) -> usize {
self.capacity()
}
/// Returns a shared reference to the allocator backing this RawVec. /// Returns a shared reference to the allocator backing this RawVec.
pub fn alloc(&self) -> &A { pub fn alloc(&self) -> &A {
&self.a &self.a
@ -240,7 +246,7 @@ impl<T, A: Alloc> RawVec<T, A> {
/// This function is ideal for when pushing elements one-at-a-time because /// This function is ideal for when pushing elements one-at-a-time because
/// you don't need to incur the costs of the more general computations /// you don't need to incur the costs of the more general computations
/// reserve needs to do to guard against overflow. You do however need to /// reserve needs to do to guard against overflow. You do however need to
/// manually check if your `len == cap`. /// manually check if your `len == capacity`.
/// ///
/// # Panics /// # Panics
/// ///
@ -267,7 +273,7 @@ impl<T, A: Alloc> RawVec<T, A> {
/// ///
/// impl<T> MyVec<T> { /// impl<T> MyVec<T> {
/// pub fn push(&mut self, elem: T) { /// pub fn push(&mut self, elem: T) {
/// if self.len == self.buf.cap() { self.buf.double(); } /// if self.len == self.buf.capacity() { self.buf.double(); }
/// // double would have aborted or panicked if the len exceeded /// // double would have aborted or panicked if the len exceeded
/// // `isize::MAX` so this is safe to do unchecked now. /// // `isize::MAX` so this is safe to do unchecked now.
/// unsafe { /// unsafe {
@ -381,20 +387,20 @@ impl<T, A: Alloc> RawVec<T, A> {
} }
/// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting.
pub fn try_reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) pub fn try_reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize)
-> Result<(), CollectionAllocErr> { -> Result<(), CollectionAllocErr> {
self.reserve_internal(used_cap, needed_extra_cap, Fallible, Exact) self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Exact)
} }
/// Ensures that the buffer contains at least enough space to hold /// Ensures that the buffer contains at least enough space to hold
/// `used_cap + needed_extra_cap` elements. If it doesn't already, /// `used_capacity + needed_extra_capacity` elements. If it doesn't already,
/// will reallocate the minimum possible amount of memory necessary. /// will reallocate the minimum possible amount of memory necessary.
/// Generally this will be exactly the amount of memory necessary, /// Generally this will be exactly the amount of memory necessary,
/// but in principle the allocator is free to give back more than /// but in principle the allocator is free to give back more than
/// we asked for. /// we asked for.
/// ///
/// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe /// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break. /// code *you* write that relies on the behavior of this function may break.
/// ///
@ -407,22 +413,23 @@ impl<T, A: Alloc> RawVec<T, A> {
/// # Aborts /// # Aborts
/// ///
/// Aborts on OOM /// Aborts on OOM
pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) { pub fn reserve_exact(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Exact) { match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Exact) {
Err(CapacityOverflow) => capacity_overflow(), Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => unreachable!(), Err(AllocErr) => unreachable!(),
Ok(()) => { /* yay */ } Ok(()) => { /* yay */ }
} }
} }
/// Calculates the buffer's new size given that it'll hold `used_cap + /// Calculates the buffer's new size given that it'll hold `used_capacity +
/// needed_extra_cap` elements. This logic is used in amortized reserve methods. /// needed_extra_capacity` elements. This logic is used in amortized reserve methods.
/// Returns `(new_capacity, new_alloc_size)`. /// Returns `(new_capacity, new_alloc_size)`.
fn amortized_new_size(&self, used_cap: usize, needed_extra_cap: usize) fn amortized_new_size(&self, used_capacity: usize, needed_extra_capacity: usize)
-> Result<usize, CollectionAllocErr> { -> Result<usize, CollectionAllocErr> {
// Nothing we can really do about these checks :( // Nothing we can really do about these checks :(
let required_cap = used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?; let required_cap = used_capacity.checked_add(needed_extra_capacity)
.ok_or(CapacityOverflow)?;
// Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`. // Cannot overflow, because `cap <= isize::MAX`, and type of `cap` is `usize`.
let double_cap = self.cap * 2; let double_cap = self.cap * 2;
// `double_cap` guarantees exponential growth. // `double_cap` guarantees exponential growth.
@ -430,18 +437,18 @@ impl<T, A: Alloc> RawVec<T, A> {
} }
/// The same as `reserve`, but returns on errors instead of panicking or aborting. /// The same as `reserve`, but returns on errors instead of panicking or aborting.
pub fn try_reserve(&mut self, used_cap: usize, needed_extra_cap: usize) pub fn try_reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize)
-> Result<(), CollectionAllocErr> { -> Result<(), CollectionAllocErr> {
self.reserve_internal(used_cap, needed_extra_cap, Fallible, Amortized) self.reserve_internal(used_capacity, needed_extra_capacity, Fallible, Amortized)
} }
/// Ensures that the buffer contains at least enough space to hold /// Ensures that the buffer contains at least enough space to hold
/// `used_cap + needed_extra_cap` elements. If it doesn't already have /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
/// enough capacity, will reallocate enough space plus comfortable slack /// enough capacity, will reallocate enough space plus comfortable slack
/// space to get amortized `O(1)` behavior. Will limit this behavior /// space to get amortized `O(1)` behavior. Will limit this behavior
/// if it would needlessly cause itself to panic. /// if it would needlessly cause itself to panic.
/// ///
/// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe /// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break. /// code *you* write that relies on the behavior of this function may break.
/// ///
@ -487,20 +494,20 @@ impl<T, A: Alloc> RawVec<T, A> {
/// # vector.push_all(&[1, 3, 5, 7, 9]); /// # vector.push_all(&[1, 3, 5, 7, 9]);
/// # } /// # }
/// ``` /// ```
pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) { pub fn reserve(&mut self, used_capacity: usize, needed_extra_capacity: usize) {
match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Amortized) { match self.reserve_internal(used_capacity, needed_extra_capacity, Infallible, Amortized) {
Err(CapacityOverflow) => capacity_overflow(), Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => unreachable!(), Err(AllocErr) => unreachable!(),
Ok(()) => { /* yay */ } Ok(()) => { /* yay */ }
} }
} }
/// Attempts to ensure that the buffer contains at least enough space to hold /// Attempts to ensure that the buffer contains at least enough space to hold
/// `used_cap + needed_extra_cap` elements. If it doesn't already have /// `used_capacity + needed_extra_capacity` elements. If it doesn't already have
/// enough capacity, will reallocate in place enough space plus comfortable slack /// enough capacity, will reallocate in place enough space plus comfortable slack
/// space to get amortized `O(1)` behavior. Will limit this behaviour /// space to get amortized `O(1)` behavior. Will limit this behaviour
/// if it would needlessly cause itself to panic. /// if it would needlessly cause itself to panic.
/// ///
/// If `used_cap` exceeds `self.cap()`, this may fail to actually allocate /// If `used_capacity` exceeds `self.capacity()`, this may fail to actually allocate
/// the requested space. This is not really unsafe, but the unsafe /// the requested space. This is not really unsafe, but the unsafe
/// code *you* write that relies on the behavior of this function may break. /// code *you* write that relies on the behavior of this function may break.
/// ///
@ -511,7 +518,7 @@ impl<T, A: Alloc> RawVec<T, A> {
/// * Panics if the requested capacity exceeds `usize::MAX` bytes. /// * Panics if the requested capacity exceeds `usize::MAX` bytes.
/// * Panics on 32-bit platforms if the requested capacity exceeds /// * Panics on 32-bit platforms if the requested capacity exceeds
/// `isize::MAX` bytes. /// `isize::MAX` bytes.
pub fn reserve_in_place(&mut self, used_cap: usize, needed_extra_cap: usize) -> bool { pub fn reserve_in_place(&mut self, used_capacity: usize, needed_extra_capacity: usize) -> bool {
unsafe { unsafe {
// NOTE: we don't early branch on ZSTs here because we want this // NOTE: we don't early branch on ZSTs here because we want this
// to actually catch "asking for more than usize::MAX" in that case. // to actually catch "asking for more than usize::MAX" in that case.
@ -520,20 +527,20 @@ impl<T, A: Alloc> RawVec<T, A> {
// Don't actually need any more capacity. If the current `cap` is 0, we can't // Don't actually need any more capacity. If the current `cap` is 0, we can't
// reallocate in place. // reallocate in place.
// Wrapping in case they give a bad `used_cap` // Wrapping in case they give a bad `used_capacity`
let old_layout = match self.current_layout() { let old_layout = match self.current_layout() {
Some(layout) => layout, Some(layout) => layout,
None => return false, None => return false,
}; };
if self.cap().wrapping_sub(used_cap) >= needed_extra_cap { if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
return false; return false;
} }
let new_cap = self.amortized_new_size(used_cap, needed_extra_cap) let new_cap = self.amortized_new_size(used_capacity, needed_extra_capacity)
.unwrap_or_else(|_| capacity_overflow()); .unwrap_or_else(|_| capacity_overflow());
// Here, `cap < used_cap + needed_extra_cap <= new_cap` // Here, `cap < used_capacity + needed_extra_capacity <= new_cap`
// (regardless of whether `self.cap - used_cap` wrapped). // (regardless of whether `self.cap - used_capacity` wrapped).
// Therefore we can safely call grow_in_place. // Therefore we can safely call grow_in_place.
let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0; let new_layout = Layout::new::<T>().repeat(new_cap).unwrap().0;
@ -632,8 +639,8 @@ use ReserveStrategy::*;
impl<T, A: Alloc> RawVec<T, A> { impl<T, A: Alloc> RawVec<T, A> {
fn reserve_internal( fn reserve_internal(
&mut self, &mut self,
used_cap: usize, used_capacity: usize,
needed_extra_cap: usize, needed_extra_capacity: usize,
fallibility: Fallibility, fallibility: Fallibility,
strategy: ReserveStrategy, strategy: ReserveStrategy,
) -> Result<(), CollectionAllocErr> { ) -> Result<(), CollectionAllocErr> {
@ -646,15 +653,15 @@ impl<T, A: Alloc> RawVec<T, A> {
// panic. // panic.
// Don't actually need any more capacity. // Don't actually need any more capacity.
// Wrapping in case they gave a bad `used_cap`. // Wrapping in case they gave a bad `used_capacity`.
if self.cap().wrapping_sub(used_cap) >= needed_extra_cap { if self.capacity().wrapping_sub(used_capacity) >= needed_extra_capacity {
return Ok(()); return Ok(());
} }
// Nothing we can really do about these checks :( // Nothing we can really do about these checks :(
let new_cap = match strategy { let new_cap = match strategy {
Exact => used_cap.checked_add(needed_extra_cap).ok_or(CapacityOverflow)?, Exact => used_capacity.checked_add(needed_extra_capacity).ok_or(CapacityOverflow)?,
Amortized => self.amortized_new_size(used_cap, needed_extra_cap)?, Amortized => self.amortized_new_size(used_capacity, needed_extra_capacity)?,
}; };
let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?; let new_layout = Layout::array::<T>(new_cap).map_err(|_| CapacityOverflow)?;
@ -692,7 +699,7 @@ impl<T> RawVec<T, Global> {
/// Note that this will correctly reconstitute any `cap` changes /// Note that this will correctly reconstitute any `cap` changes
/// that may have been performed. (see description of type for details) /// that may have been performed. (see description of type for details)
pub unsafe fn into_box(self) -> Box<[T]> { pub unsafe fn into_box(self) -> Box<[T]> {
// NOTE: not calling `cap()` here, actually using the real `cap` field! // NOTE: not calling `capacity()` here, actually using the real `cap` field!
let slice = slice::from_raw_parts_mut(self.ptr(), self.cap); let slice = slice::from_raw_parts_mut(self.ptr(), self.cap);
let output: Box<[T]> = Box::from_raw(slice); let output: Box<[T]> = Box::from_raw(slice);
mem::forget(self); mem::forget(self);
@ -796,29 +803,29 @@ mod tests {
let mut v: RawVec<u32> = RawVec::new(); let mut v: RawVec<u32> = RawVec::new();
// First `reserve` allocates like `reserve_exact` // First `reserve` allocates like `reserve_exact`
v.reserve(0, 9); v.reserve(0, 9);
assert_eq!(9, v.cap()); assert_eq!(9, v.capacity());
} }
{ {
let mut v: RawVec<u32> = RawVec::new(); let mut v: RawVec<u32> = RawVec::new();
v.reserve(0, 7); v.reserve(0, 7);
assert_eq!(7, v.cap()); assert_eq!(7, v.capacity());
// 97 if more than double of 7, so `reserve` should work // 97 if more than double of 7, so `reserve` should work
// like `reserve_exact`. // like `reserve_exact`.
v.reserve(7, 90); v.reserve(7, 90);
assert_eq!(97, v.cap()); assert_eq!(97, v.capacity());
} }
{ {
let mut v: RawVec<u32> = RawVec::new(); let mut v: RawVec<u32> = RawVec::new();
v.reserve(0, 12); v.reserve(0, 12);
assert_eq!(12, v.cap()); assert_eq!(12, v.capacity());
v.reserve(12, 3); v.reserve(12, 3);
// 3 is less than half of 12, so `reserve` must grow // 3 is less than half of 12, so `reserve` must grow
// exponentially. At the time of writing this test grow // exponentially. At the time of writing this test grow
// factor is 2, so new capacity is 24, however, grow factor // factor is 2, so new capacity is 24, however, grow factor
// of 1.5 is OK too. Hence `>= 18` in assert. // of 1.5 is OK too. Hence `>= 18` in assert.
assert!(v.cap() >= 12 + 12 / 2); assert!(v.capacity() >= 12 + 12 / 2);
} }
} }

View file

@ -432,7 +432,7 @@ impl<T> Vec<T> {
#[inline] #[inline]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.buf.cap() self.buf.capacity()
} }
/// Reserves capacity for at least `additional` more elements to be inserted /// Reserves capacity for at least `additional` more elements to be inserted
@ -878,7 +878,7 @@ impl<T> Vec<T> {
assert!(index <= len); assert!(index <= len);
// space for the new element // space for the new element
if len == self.buf.cap() { if len == self.buf.capacity() {
self.reserve(1); self.reserve(1);
} }
@ -1019,7 +1019,7 @@ impl<T> Vec<T> {
pub fn push(&mut self, value: T) { pub fn push(&mut self, value: T) {
// This will panic or abort if we would allocate > isize::MAX bytes // This will panic or abort if we would allocate > isize::MAX bytes
// or if the length increment would overflow for zero-sized types. // or if the length increment would overflow for zero-sized types.
if self.len == self.buf.cap() { if self.len == self.buf.capacity() {
self.reserve(1); self.reserve(1);
} }
unsafe { unsafe {
@ -1750,7 +1750,7 @@ impl<T> IntoIterator for Vec<T> {
} else { } else {
begin.add(self.len()) as *const T begin.add(self.len()) as *const T
}; };
let cap = self.buf.cap(); let cap = self.buf.capacity();
mem::forget(self); mem::forget(self);
IntoIter { IntoIter {
buf: NonNull::new_unchecked(begin), buf: NonNull::new_unchecked(begin),

View file

@ -99,7 +99,7 @@ impl<T> TypedArenaChunk<T> {
// A pointer as large as possible for zero-sized elements. // A pointer as large as possible for zero-sized elements.
!0 as *mut T !0 as *mut T
} else { } else {
self.start().add(self.storage.cap()) self.start().add(self.storage.capacity())
} }
} }
} }
@ -270,7 +270,7 @@ impl<T> TypedArena<T> {
self.end.set(last_chunk.end()); self.end.set(last_chunk.end());
return; return;
} else { } else {
new_capacity = last_chunk.storage.cap(); new_capacity = last_chunk.storage.capacity();
loop { loop {
new_capacity = new_capacity.checked_mul(2).unwrap(); new_capacity = new_capacity.checked_mul(2).unwrap();
if new_capacity >= currently_used_cap + n { if new_capacity >= currently_used_cap + n {
@ -405,7 +405,7 @@ impl DroplessArena {
self.end.set(last_chunk.end()); self.end.set(last_chunk.end());
return; return;
} else { } else {
new_capacity = last_chunk.storage.cap(); new_capacity = last_chunk.storage.capacity();
loop { loop {
new_capacity = new_capacity.checked_mul(2).unwrap(); new_capacity = new_capacity.checked_mul(2).unwrap();
if new_capacity >= used_bytes + needed_bytes { if new_capacity >= used_bytes + needed_bytes {

View file

@ -16,7 +16,7 @@ union RawArray<T> {
} }
impl<T> RawArray<T> { impl<T> RawArray<T> {
fn cap() -> usize { fn capacity() -> usize {
if mem::size_of::<T>() == 0 { if mem::size_of::<T>() == 0 {
usize::max_value() usize::max_value()
} else { } else {
@ -55,7 +55,7 @@ impl<T> RawArray<T> {
pub unsafe fn ptr_rotate<T>(mut left: usize, mid: *mut T, mut right: usize) { pub unsafe fn ptr_rotate<T>(mut left: usize, mid: *mut T, mut right: usize) {
loop { loop {
let delta = cmp::min(left, right); let delta = cmp::min(left, right);
if delta <= RawArray::<T>::cap() { if delta <= RawArray::<T>::capacity() {
// We will always hit this immediately for ZST. // We will always hit this immediately for ZST.
break; break;
} }

View file

@ -161,20 +161,20 @@ fn wakeup<T>(token: SignalToken, guard: MutexGuard<'_, State<T>>) {
} }
impl<T> Packet<T> { impl<T> Packet<T> {
pub fn new(cap: usize) -> Packet<T> { pub fn new(capacity: usize) -> Packet<T> {
Packet { Packet {
channels: AtomicUsize::new(1), channels: AtomicUsize::new(1),
lock: Mutex::new(State { lock: Mutex::new(State {
disconnected: false, disconnected: false,
blocker: NoneBlocked, blocker: NoneBlocked,
cap, cap: capacity,
canceled: None, canceled: None,
queue: Queue { queue: Queue {
head: ptr::null_mut(), head: ptr::null_mut(),
tail: ptr::null_mut(), tail: ptr::null_mut(),
}, },
buf: Buffer { buf: Buffer {
buf: (0..cap + if cap == 0 {1} else {0}).map(|_| None).collect(), buf: (0..capacity + if capacity == 0 {1} else {0}).map(|_| None).collect(),
start: 0, start: 0,
size: 0, size: 0,
}, },
@ -189,7 +189,7 @@ impl<T> Packet<T> {
loop { loop {
let mut guard = self.lock.lock().unwrap(); let mut guard = self.lock.lock().unwrap();
// are we ready to go? // are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() { if guard.disconnected || guard.buf.size() < guard.buf.capacity() {
return guard; return guard;
} }
// no room; actually block // no room; actually block
@ -231,7 +231,7 @@ impl<T> Packet<T> {
let mut guard = self.lock.lock().unwrap(); let mut guard = self.lock.lock().unwrap();
if guard.disconnected { if guard.disconnected {
Err(super::TrySendError::Disconnected(t)) Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() { } else if guard.buf.size() == guard.buf.capacity() {
Err(super::TrySendError::Full(t)) Err(super::TrySendError::Full(t))
} else if guard.cap == 0 { } else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't // With capacity 0, even though we have buffer space we can't
@ -249,7 +249,7 @@ impl<T> Packet<T> {
// If the buffer has some space and the capacity isn't 0, then we // If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up // just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one. // any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap()); assert!(guard.buf.size() < guard.buf.capacity());
guard.buf.enqueue(t); guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) { match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard), BlockedReceiver(token) => wakeup(token, guard),
@ -475,7 +475,7 @@ impl<T> Buffer<T> {
} }
fn size(&self) -> usize { self.size } fn size(&self) -> usize { self.size }
fn cap(&self) -> usize { self.buf.len() } fn capacity(&self) -> usize { self.buf.len() }
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////