Skip to content

claim trait to allow non-fallible cloning #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/claim.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use alloc::rc::Rc;
use alloc::sync::Arc;
use core::convert::Infallible;
use core::marker::PhantomData;

/// A marker trait for infallible cloneable objects.
/// Only implement this for your type if you can guarantee that cloning it
/// is guaranteed not to panic.
///
/// For details on the idea, read the [Claiming, auto and
/// otherwise](https://smallcultfollowing.com/babysteps/blog/2024/06/21/claim-auto-and-otherwise/)
/// blog post.
pub trait Claim: Clone {}

// Anything which is trivially copiable is automatically infallible
// We need to list these out since the compiler will not allow us to `impl <T: Copy> impl Claim {}`
macro_rules! impl_claim_for {
($($t:ty),*) => {
$(
impl Claim for $t {}
)*
};
}

// Generate impls for simple types
impl_claim_for! {
(), u8, u16, u32, u64, u128, usize,
i8, i16, i32, i64, i128, isize,
f32, f64, bool, char
}

impl<T: ?Sized> Claim for *const T {}
impl<T: ?Sized> Claim for *mut T {}
impl<T: Copy, const N: usize> Claim for [T; N] {}
impl<T: ?Sized> Claim for PhantomData<T> {}
impl<T: ?Sized> Claim for &T {}

// A few other common impls, non-exhaustive
impl<T> Claim for Arc<T> {}
impl<T> Claim for Rc<T> {}
impl Claim for Infallible {}
impl<T: Claim> Claim for Option<T> {}
impl<T: Claim, E: Claim> Claim for Result<T, E> {}
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;

pub 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
Loading