Skip to content

Commit

Permalink
Store original ArrayVec inside UnderfilledError
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickariel committed Dec 20, 2024
1 parent dcd84f5 commit 09b6854
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 14 deletions.
4 changes: 2 additions & 2 deletions src/arrayvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -693,9 +693,9 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
/// capacity (see [`capacity`]).
///
/// [`capacity`]: #method.capacity
pub fn into_inner(self) -> Result<[T; CAP], UnderfilledError> {
pub fn into_inner(self) -> Result<[T; CAP], UnderfilledError<T, CAP>> {
if self.len() < self.capacity() {
Err(UnderfilledError::new(self.capacity(), self.len()))
Err(UnderfilledError::new(self))
} else {
unsafe { Ok(self.into_inner_unchecked()) }
}
Expand Down
25 changes: 14 additions & 11 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use std::any::Any;
#[cfg(feature="std")]
use std::error::Error;

use crate::ArrayVec;

/// Error value indicating insufficient capacity
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub struct CapacityError<T = ()> {
Expand Down Expand Up @@ -48,23 +50,24 @@ impl<T> fmt::Debug for CapacityError<T> {
}

/// Error value indicating that capacity is not completely filled
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct UnderfilledError {
capacity: usize,
len: usize,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct UnderfilledError<T, const CAP: usize>(ArrayVec<T, CAP>);

impl<T, const CAP: usize> UnderfilledError<T, CAP> {
pub const fn new(inner: ArrayVec<T, CAP>) -> Self {
Self(inner)
}

impl UnderfilledError {
pub const fn new(capacity: usize, len: usize) -> Self {
Self { capacity, len }
pub fn take_vec(self) -> ArrayVec<T, CAP> {
self.0
}
}

#[cfg(feature="std")]
impl Error for UnderfilledError {}
impl<T: fmt::Debug, const CAP: usize> Error for UnderfilledError<T, CAP> {}

impl fmt::Display for UnderfilledError {
impl<T, const CAP: usize> fmt::Display for UnderfilledError<T, CAP> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "capacity is not filled: expected {}, got {}", self.capacity, self.len)
write!(f, "capacity is not filled: expected {}, got {}", CAP, self.0.len())
}
}
3 changes: 2 additions & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,8 @@ fn test_insert() {
fn test_into_inner_1() {
let mut v = ArrayVec::from([1, 2]);
v.pop();
assert_eq!(v.into_inner(), Err(UnderfilledError::new(2, 1)));
let u = v.clone();
assert_eq!(v.into_inner(), Err(UnderfilledError::new(u)));
}

#[test]
Expand Down

0 comments on commit 09b6854

Please sign in to comment.