From 6e5f732a65a6398ff70403249df9e5abdc6f127c Mon Sep 17 00:00:00 2001 From: Moritz Hoffmann Date: Mon, 27 May 2024 14:36:55 -0400 Subject: [PATCH] Reborrow Signed-off-by: Moritz Hoffmann --- src/lib.rs | 43 +++++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a0aceec..3c39097 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -425,7 +425,7 @@ mod tests { hobbies: as Containerized>::Region, } - #[derive(Debug)] + #[derive(Debug, Clone, Copy)] struct PersonRef<'a> { name: <::Region as Region>::ReadItem<'a>, age: <::Region as Region>::ReadItem<'a>, @@ -759,21 +759,40 @@ mod tests { c.copy([[&vec![[[&1; 1]; 1]; 1]; 1]; 1]); } - fn owned_roundtrip(region: &mut R, index: R::Index) - where - for<'a> R: Region + Push<<::ReadItem<'a> as IntoOwned<'a>>::Owned>, - for<'a> R::ReadItem<'a>: IntoOwned<'a, Owned = O>, - { - let item = region.index(index); - let owned = item.into_owned(); - let index = region.push(owned); - assert_eq!(item, region.index(index)); - } - #[test] fn test_owned() { + fn owned_roundtrip(region: &mut R, index: R::Index) + where + for<'a> R: Region + Push<<::ReadItem<'a> as IntoOwned<'a>>::Owned>, + for<'a> R::ReadItem<'a>: IntoOwned<'a, Owned = O> + Eq + Debug, + { + let item = region.index(index); + let owned = item.into_owned(); + let index2 = region.push(owned); + let item = region.index(index); + assert_eq!(item, region.index(index2)); + } + let mut c = ::default(); let index = c.push("abc".to_string()); owned_roundtrip(&mut c, index); } + + /// Test that items and owned variants can be reborrowed to shorten their lifetimes. + fn _test_reborrow(item: R::ReadItem<'_>, owned: &R::Owned) + where + R: Region, + for<'a> R::ReadItem<'a>: Eq, + { + // The following line requires `reborrow` because otherwise owned must outlive '_. + // fn _test_reborrow(item: R::ReadItem<'_>, owned: &R::Owned) where R: Region, for<'a> R::ReadItem<'a>: Eq { + // ---- - let's call the lifetime of this reference `'1` + // | + // has type `::ReadItem<'2>` + // // The following line requires `reborrow` because otherwise owned must outlive '_. + // let _ = item == IntoOwned::borrow_as(owned); + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'2` + // let _ = item == IntoOwned::borrow_as(owned); + let _ = R::reborrow(item) == R::reborrow(IntoOwned::borrow_as(owned)); + } }