VecRef::try_map and VecRefMut::try_map

pull/1/head
Shad Amethyst 2 years ago
parent 4c1cae2537
commit 7806c473b1
Signed by: amethyst
GPG Key ID: D970C8DD1D6DEE36

@ -1,6 +1,6 @@
[package]
name = "veccell"
version = "0.2.0"
version = "0.2.1"
edition = "2021"
authors = [ "Shad Amethyst <adrien.burgun@orange.fr>" ]
description = "Provides VecCell, a variant of Vec with interior mutability."

@ -271,3 +271,28 @@ fn test_range() {
std::mem::drop(elem);
}
#[test]
fn test_try_map() {
let mut vec: VecCell<Box<i32>> = VecCell::new();
for x in -10..10 {
vec.push(Box::new(x));
}
let ref_mut = vec.borrow_mut(5).unwrap();
assert!(VecRefMut::try_map(ref_mut, |_value| Err::<&mut (), ()>(())).is_err());
let ref_mut = vec.borrow_mut(5).unwrap();
let ref_mut: Result<VecRefMut<'_, i32>, ()> = VecRefMut::try_map(ref_mut, |value| Ok(value.as_mut()));
assert!(ref_mut.is_ok());
assert_eq!(ref_mut.unwrap(), -5);
let borrow = vec.borrow(6).unwrap();
assert!(VecRef::try_map(borrow, |_value| Err::<&(), ()>(())).is_err());
let borrow = vec.borrow(4).unwrap();
let borrow: Result<VecRef<'_, i32>, ()> = VecRef::try_map(borrow, |value| Ok(value.as_ref()));
assert!(borrow.is_ok());
assert_eq!(borrow.unwrap(), -6);
}

@ -99,6 +99,17 @@ impl<'a, T: ?Sized> VecRef<'a, T> {
VecRef::from(f(original.value), original.borrows.clone())
// original is dropped here
}
/// Variant of [`VecRef::map`], where the callback (`f`) may fail.
///
/// `f` must return a `Result`; if it returns `Ok(x)`, then `try_map` returns `Ok(VecRef(x))`.
/// Otherwise, it returns `Err(err)`.
pub fn try_map<'b, U: ?Sized, F, E>(original: VecRef<'b, T>, f: F) -> Result<VecRef<'b, U>, E>
where
F: FnOnce(&T) -> Result<&U, E>
{
Ok(VecRef::from(f(original.value)?, original.borrows.clone()))
}
}
impl<'a, T: ?Sized> Deref for VecRef<'a, T> {

@ -103,6 +103,21 @@ impl<'a, T: ?Sized> VecRefMut<'a, T> {
mut_borrow
}
}
/// Variant of [`VecRefMut::map`], where the callback (`f`) may fail.
///
/// `f` must return a `Result`; if it returns `Ok(x)`, then `try_map` returns `Ok(VecRefMut(x))`.
/// Otherwise, it returns `Err(err)`.
pub fn try_map<'b, U: ?Sized, F, E>(original: VecRefMut<'b, T>, f: F) -> Result<VecRefMut<'b, U>, E>
where
F: FnOnce(&mut T) -> Result<&mut U, E>
{
let VecRefMut { value, mut_borrow } = original;
Ok(VecRefMut {
value: f(value)?,
mut_borrow: mut_borrow
})
}
}
impl<'a, T: ?Sized> Deref for VecRefMut<'a, T> {

Loading…
Cancel
Save