Skip to content

Commit

Permalink
Add ZeroVec::owned_capacity (#3431)
Browse files Browse the repository at this point in the history
  • Loading branch information
sffc committed May 13, 2023
1 parent 90c8e14 commit a4ba914
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions utils/zerovec/src/zerovec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use core::fmt;
use core::iter::FromIterator;
use core::marker::PhantomData;
use core::mem;
use core::num::NonZeroUsize;
use core::ops::Deref;

/// A zero-copy, byte-aligned vector for fixed-width types.
Expand Down Expand Up @@ -554,6 +555,34 @@ where
Some(ZeroSlice::from_ule_slice(ule_slice))
}
}

/// If the ZeroVec is owned, returns the capacity of the vector.
///
/// Otherwise, if the ZeroVec is borrowed, returns `None`.
///
/// # Examples
///
/// ```
/// use zerovec::ZeroVec;
///
/// let mut zv = ZeroVec::<u8>::new_borrowed(&[0, 1, 2, 3]);
/// assert!(!zv.is_owned());
/// assert_eq!(zv.owned_capacity(), None);
///
/// // Convert to owned without appending anything
/// zv.with_mut(|v| ());
/// assert!(zv.is_owned());
/// assert_eq!(zv.owned_capacity(), Some(4.try_into().unwrap()));
///
/// // Double the size by appending
/// zv.with_mut(|v| v.push(0));
/// assert!(zv.is_owned());
/// assert_eq!(zv.owned_capacity(), Some(8.try_into().unwrap()));
/// ```
#[inline]
pub fn owned_capacity(&self) -> Option<NonZeroUsize> {
NonZeroUsize::try_from(self.vector.capacity).ok()
}
}

impl<'a> ZeroVec<'a, u8> {
Expand Down

0 comments on commit a4ba914

Please sign in to comment.