From: Ian Jackson Date: Sat, 16 Nov 2024 18:51:40 +0000 (+0000) Subject: demo Borrowed X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ian/git?a=commitdiff_plain;h=3b205dd6a3fe4e3228b107f81f794ec892d72dd1;p=manually-boxed demo Borrowed --- diff --git a/src/test.rs b/src/test.rs index 7eddc91..7b17430 100644 --- a/src/test.rs +++ b/src/test.rs @@ -38,6 +38,13 @@ fn demo() { l.prepend(s("one")); l.check_consistency(); assert_eq!(l.head_and_tail_mut(), H::Both(&mut s("one"), &mut s("ho"))); + l.temporarily_prepend(s("t"), |l| { + l.check_consistency(); + assert_eq!(l.front(), Some(&s("t"))); + }); + l.check_consistency(); + assert_eq!(l.head_and_tail_mut(), H::Both(&mut s("one"), &mut s("ho"))); + write!(l.front_mut().unwrap(), "!").unwrap(); assert_eq!(l.pop_front(), Some(s("one!"))); l.check_consistency(); assert_eq!(l.front(), Some(&s("hi"))); l.check_consistency(); diff --git a/src/test/demo.rs b/src/test/demo.rs index 1a61116..da3304d 100644 --- a/src/test/demo.rs +++ b/src/test/demo.rs @@ -114,6 +114,33 @@ impl List { Some(deleted.data) } + // This is a bit unnatural, but it demonstrates Borrowed + pub fn temporarily_prepend( + &mut self, + data: T, + then: impl FnOnce(&Self) -> R, + ) -> R { + use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; + + let mut tmp_node = Node { + data, + next: None, + back: None, + }; + let tmp_node = unsafe { Borrowed::new(&mut tmp_node) }; + self.prepend_raw(*tmp_node); + let r = catch_unwind(AssertUnwindSafe(|| then(&self))); + let mut tok = &mut self.noalias; + let removed_again = Self::pop_front_inner( + tok.as_mut(), + &mut self.head, + &mut self.tail, + ); + assert_eq!(removed_again.map(|p| p.as_ptr()), Some(tmp_node.as_ptr())); + tmp_node.retained(); + r.unwrap_or_else(|p| resume_unwind(p)) + } + pub fn head_and_tail_mut(&mut self) -> HeadAndTail<&mut T> { let Some(head) = self.head else { return HeadAndTail::None };