From bb1cc93797b8e8ef509b91d5af691c934b20fd59 Mon Sep 17 00:00:00 2001 From: Joseph Perez Date: Sun, 29 Oct 2023 08:28:39 +0100 Subject: [PATCH] feat: add `take` and `into_inner` methods to `GILOnceCell` --- src/sync.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/sync.rs b/src/sync.rs index 50bb80da..7f7e11c9 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -167,6 +167,20 @@ impl GILOnceCell { *inner = Some(value); Ok(()) } + + /// Takes the value out of the cell, moving it back to an uninitialized state. + /// + /// Has no effect and returns None if the cell has not yet been written. + pub fn take(&mut self) -> Option { + self.0.get_mut().take() + } + + /// Consumes the cell, returning the wrapped value. + /// + /// Returns None if the cell has not yet been written. + pub fn into_inner(self) -> Option { + self.0.into_inner() + } } impl GILOnceCell> { @@ -278,7 +292,7 @@ mod tests { #[test] fn test_once_cell() { Python::with_gil(|py| { - let cell = GILOnceCell::new(); + let mut cell = GILOnceCell::new(); assert!(cell.get(py).is_none()); @@ -289,6 +303,9 @@ mod tests { assert_eq!(cell.get(py), Some(&2)); assert_eq!(cell.get_or_try_init(py, || Err(5)), Ok(&2)); + + assert_eq!(cell.take(), Some(2)); + assert_eq!(cell.into_inner(), None) }) } }