Skip to content

Commit

Permalink
claim trait to allow non-fallible cloning
Browse files Browse the repository at this point in the history
  • Loading branch information
amunra committed Oct 8, 2024
1 parent 80f3e20 commit b5e0c54
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
extern crate alloc;
extern crate core;

mod claim;
pub mod try_clone;
pub mod vec;
20 changes: 13 additions & 7 deletions src/vec.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::claim::Claim;
use crate::try_clone::TryClone;
use alloc::alloc::Allocator;
use alloc::collections::TryReserveError;
Expand Down Expand Up @@ -147,7 +148,7 @@ impl<T, A: Allocator> Vec<T, A> {
}
}

impl<T: Clone, A: Allocator> Vec<T, A> {
impl<T: Claim, A: Allocator> Vec<T, A> {
#[inline]
pub fn extend_from_slice(&mut self, slice: &[T]) -> Result<(), TryReserveError> {
self.reserve(slice.len())?;
Expand Down Expand Up @@ -186,7 +187,7 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
}
}

impl<T: Copy, A: Allocator + Clone> TryClone for Vec<T, A> {
impl<T: Claim, A: Allocator + Claim> TryClone for Vec<T, A> {
type Error = TryReserveError;

fn try_clone(&self) -> Result<Self, Self::Error> {
Expand Down Expand Up @@ -288,6 +289,7 @@ impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
#[cfg(test)]
mod tests {
use super::*;
use crate::claim::Claim;
use alloc::alloc::Global;
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
Expand All @@ -303,6 +305,8 @@ mod tests {
in_use: Arc<AtomicUsize>,
}

impl Claim for WatermarkAllocator {}

impl WatermarkAllocator {
pub(crate) fn in_use(&self) -> usize {
self.in_use.load(Ordering::SeqCst)
Expand Down Expand Up @@ -496,15 +500,17 @@ mod tests {
assert_eq!(vec[3], 4);
}

/// A type that implements `Clone` but not `Copy`.
/// A type that implements `Clone` and `Claim`, but not `Copy`.
#[derive(Clone, Eq, PartialEq)]
struct Cloneable(i32);
struct Claimable(i32);

impl Claim for Claimable {}

#[test]
fn test_extend_from_slice_clone() {
let wma = WatermarkAllocator::new(32);
let mut vec = Vec::new_in(wma);
vec.extend_from_slice(&[Cloneable(1), Cloneable(2), Cloneable(3), Cloneable(4)])
vec.extend_from_slice(&[Claimable(1), Claimable(2), Claimable(3), Claimable(4)])
.unwrap();
}

Expand Down Expand Up @@ -783,12 +789,12 @@ mod tests {
}
}

fn get_first_elem_vec<T: Clone, A: Allocator>(vec: impl AsRef<Vec<T, A>>) -> T {
fn get_first_elem_vec<T: Claim, A: Allocator>(vec: impl AsRef<Vec<T, A>>) -> T {
let vec = vec.as_ref();
vec.first().unwrap().clone()
}

fn get_first_elem_slice<T: Clone>(slice: impl AsRef<[T]>) -> T {
fn get_first_elem_slice<T: Claim>(slice: impl AsRef<[T]>) -> T {
let vec = slice.as_ref();
vec.first().unwrap().clone()
}
Expand Down

0 comments on commit b5e0c54

Please sign in to comment.