From 99da4f0cfe700e97d2ca30dd221e746d2b3f84a7 Mon Sep 17 00:00:00 2001 From: Adam Cimarosti Date: Tue, 1 Oct 2024 13:27:18 +0100 Subject: [PATCH] AsRef / AsMut --- src/vec.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/vec.rs b/src/vec.rs index 8bfade4..bbfa611 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -5,6 +5,7 @@ use core::fmt::Debug; use core::ops::{Deref, DerefMut, Index, IndexMut}; use core::slice::SliceIndex; +#[derive(Clone)] pub struct Vec { inner: InnerVec, } @@ -257,6 +258,30 @@ __impl_slice_eq1! { [A: Allocator, const N: usize] [T; N], Vec } __impl_slice_eq1! { [A: Allocator, const N: usize] Vec, &[U; N] } __impl_slice_eq1! { [A: Allocator, const N: usize] &[T; N], Vec } +impl AsRef> for Vec { + fn as_ref(&self) -> &Vec { + self + } +} + +impl AsMut> for Vec { + fn as_mut(&mut self) -> &mut Vec { + self + } +} + +impl AsRef<[T]> for Vec { + fn as_ref(&self) -> &[T] { + self + } +} + +impl AsMut<[T]> for Vec { + fn as_mut(&mut self) -> &mut [T] { + self + } +} + #[cfg(test)] mod tests { use super::*; @@ -761,4 +786,54 @@ mod tests { assert_ne!(rhs, lhs); } } + + fn get_first_elem_vec(vec: impl AsRef>) -> T { + let vec = vec.as_ref(); + vec.first().unwrap().clone() + } + + fn get_first_elem_slice(slice: impl AsRef<[T]>) -> T { + let vec = slice.as_ref(); + vec.first().unwrap().clone() + } + + #[test] + fn test_as_ref() { + let wma = WatermarkAllocator::new(128); + let mut vec1 = Vec::new_in(wma); + vec1.extend(vec![1, 2, 3]).unwrap(); + let vec2 = vec1.clone(); + + assert_eq!(vec1, vec2); + let e0vec1 = get_first_elem_vec(vec1); + let e0vec2 = get_first_elem_slice(vec2); + assert_eq!(e0vec1, 1); + assert_eq!(e0vec2, 1); + } + + fn doubled_first_elem_vec(mut vec: impl AsMut>) -> i32 { + let vec = vec.as_mut(); + vec[0] *= 2; + vec[0] + } + + fn doubled_first_elem_slice(mut vec: impl AsMut<[i32]>) -> i32 { + let vec = vec.as_mut(); + vec[0] *= 2; + vec[0] + } + + #[test] + fn test_as_mut() { + let wma = WatermarkAllocator::new(128); + let mut vec1 = Vec::new_in(wma); + vec1.extend(vec![1, 2, 3]).unwrap(); + let vec2 = vec1.clone(); + + let d0vec1 = doubled_first_elem_vec(vec1); + let d0vec2 = doubled_first_elem_slice(vec2); + + assert_eq!(d0vec1, 2); + assert_eq!(d0vec2, 2); + } }