take_mut-0.2.2/.gitignore00006440000000000000000000000022126440611060013474 0ustar0000000000000000target Cargo.lock take_mut-0.2.2/Cargo.toml.orig00006440000000000000000000000435132541137620014407 0ustar0000000000000000[package] name = "take_mut" version = "0.2.2" authors = ["Sgeo "] license = "MIT" homepage = "https://github.com/Sgeo/take_mut" repository = "https://github.com/Sgeo/take_mut" description = "Take a T from a &mut T temporarily" categories = ["rust-patterns"]take_mut-0.2.2/Cargo.toml0000644000000014420007664 0ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "take_mut" version = "0.2.2" authors = ["Sgeo "] description = "Take a T from a &mut T temporarily" homepage = "https://github.com/Sgeo/take_mut" categories = ["rust-patterns"] license = "MIT" repository = "https://github.com/Sgeo/take_mut" take_mut-0.2.2/LICENSE00006440000000000000000000002106126600475360012527 0ustar0000000000000000The MIT License (MIT) Copyright (c) 2016 Sgeo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. take_mut-0.2.2/README.md00006440000000000000000000001462126601457430013004 0ustar0000000000000000# take_mut This crate provides (at this time) a single function, `take()`. `take()` allows for taking `T` out of a `&mut T`, doing anything with it including consuming it, and producing another `T` to put back in the `&mut T`. During `take()`, if a panic occurs, the entire process will be exited, as there's no valid `T` to put back into the `&mut T`. Contrast with `std::mem::replace()`, which allows for putting a different `T` into a `&mut T`, but requiring the new `T` to be available before being able to consume the old `T`. # Example ```rust struct Foo; let mut foo = Foo; take_mut::take(&mut foo, |foo| { // Can now consume the Foo, and provide a new value later drop(foo); // Do more stuff Foo // Return new Foo from closure, which goes back into the &mut Foo }); ```take_mut-0.2.2/src/lib.rs00006440000000000000000000010617131417102120013412 0ustar0000000000000000//! This crate provides several functions for handling `&mut T` including `take()`. //! //! `take()` allows for taking `T` out of a `&mut T`, doing anything with it including consuming it, and producing another `T` to put back in the `&mut T`. //! //! During `take()`, if a panic occurs, the entire process will be aborted, as there's no valid `T` to put back into the `&mut T`. //! Use `take_or_recover()` to replace the `&mut T` with a recovery value before continuing the panic. //! //! Contrast with `std::mem::replace()`, which allows for putting a different `T` into a `&mut T`, but requiring the new `T` to be available before being able to consume the old `T`. use std::panic; pub mod scoped; /// Allows use of a value pointed to by `&mut T` as though it was owned, as long as a `T` is made available afterwards. /// /// The closure must return a valid T. /// # Important /// Will abort the program if the closure panics. /// /// # Example /// ``` /// struct Foo; /// let mut foo = Foo; /// take_mut::take(&mut foo, |foo| { /// // Can now consume the Foo, and provide a new value later /// drop(foo); /// // Do more stuff /// Foo // Return new Foo from closure, which goes back into the &mut Foo /// }); /// ``` pub fn take(mut_ref: &mut T, closure: F) where F: FnOnce(T) -> T { use std::ptr; unsafe { let old_t = ptr::read(mut_ref); let new_t = panic::catch_unwind(panic::AssertUnwindSafe(|| closure(old_t))) .unwrap_or_else(|_| ::std::process::abort()); ptr::write(mut_ref, new_t); } } #[test] fn it_works() { #[derive(PartialEq, Eq, Debug)] enum Foo {A, B}; impl Drop for Foo { fn drop(&mut self) { match *self { Foo::A => println!("Foo::A dropped"), Foo::B => println!("Foo::B dropped") } } } let mut foo = Foo::A; take(&mut foo, |f| { drop(f); Foo::B }); assert_eq!(&foo, &Foo::B); } /// Allows use of a value pointed to by `&mut T` as though it was owned, as long as a `T` is made available afterwards. /// /// The closure must return a valid T. /// # Important /// Will replace `&mut T` with `recover` if the closure panics, then continues the panic. /// /// # Example /// ``` /// struct Foo; /// let mut foo = Foo; /// take_mut::take_or_recover(&mut foo, || Foo, |foo| { /// // Can now consume the Foo, and provide a new value later /// drop(foo); /// // Do more stuff /// Foo // Return new Foo from closure, which goes back into the &mut Foo /// }); /// ``` pub fn take_or_recover(mut_ref: &mut T, recover: R, closure: F) where F: FnOnce(T) -> T, R: FnOnce() -> T { use std::ptr; unsafe { let old_t = ptr::read(mut_ref); let new_t = panic::catch_unwind(panic::AssertUnwindSafe(|| closure(old_t))); match new_t { Err(err) => { let r = panic::catch_unwind(panic::AssertUnwindSafe(|| recover())) .unwrap_or_else(|_| ::std::process::abort()); ptr::write(mut_ref, r); panic::resume_unwind(err); } Ok(new_t) => ptr::write(mut_ref, new_t), } } } #[test] fn it_works_recover() { #[derive(PartialEq, Eq, Debug)] enum Foo {A, B}; impl Drop for Foo { fn drop(&mut self) { match *self { Foo::A => println!("Foo::A dropped"), Foo::B => println!("Foo::B dropped") } } } let mut foo = Foo::A; take_or_recover(&mut foo, || Foo::A, |f| { drop(f); Foo::B }); assert_eq!(&foo, &Foo::B); } #[test] fn it_works_recover_panic() { #[derive(PartialEq, Eq, Debug)] enum Foo {A, B, C}; impl Drop for Foo { fn drop(&mut self) { match *self { Foo::A => println!("Foo::A dropped"), Foo::B => println!("Foo::B dropped"), Foo::C => println!("Foo::C dropped") } } } let mut foo = Foo::A; let res = panic::catch_unwind(panic::AssertUnwindSafe(|| { take_or_recover(&mut foo, || Foo::C, |f| { drop(f); panic!("panic"); Foo::B }); })); assert!(res.is_err()); assert_eq!(&foo, &Foo::C); } take_mut-0.2.2/src/scoped.rs00006440000000000000000000012330131417104700014121 0ustar0000000000000000//! This module provides a scoped API, allowing for taking an arbitrary number of `&mut T` into `T` within one closure. //! The references are all required to outlive the closure. //! //! # Example //! ``` //! use take_mut::scoped; //! struct Foo; //! let mut foo = Foo; // Must outlive scope //! scoped::scope(|scope| { //! let (t, hole) = scope.take(&mut foo); //! drop(t); //! hole.fill(Foo); // If not called before the closure ends, causes an abort. //! }); //! ``` //! //! # Invalid Example (does not compile) //! ```ignore //! use take_mut::scoped; //! struct Foo; //! scoped::scope(|scope| { //! let mut foo = Foo; // Invalid because foo must come from outside the scope. //! let (t, hole) = scope.take(&mut foo); //! drop(t); //! hole.fill(Foo); //! }); //! ``` //! //! `Scope` also offers `take_or_recover`, which takes a function to call in the event the hole isn't filled. #![warn(missing_docs)] use std; use std::panic; use std::cell::Cell; use std::marker::PhantomData; /// Represents a scope within which, it is possible to take a `T` from a `&mut T` as long as the `&mut T` outlives the scope. pub struct Scope<'s> { active_holes: Cell, marker: PhantomData> } impl<'s> Scope<'s> { /// Takes a `(T, Hole<'c, 'm, T, F>)` from an `&'m mut T`. /// /// If the `Hole` is dropped without being filled, either due to panic or forgetting to fill, will run the `recovery` function to obtain a `T` to fill itself with. pub fn take_or_recover<'c, 'm: 's, T: 'm, F: FnOnce() -> T>(&'c self, mut_ref: &'m mut T, recovery: F) -> (T, Hole<'c, 'm, T, F>) { use std::ptr; let t: T; let hole: Hole<'c, 'm, T, F>; let num_of_holes = self.active_holes.get(); if num_of_holes == std::usize::MAX { panic!("Too many holes!"); } self.active_holes.set(num_of_holes + 1); unsafe { t = ptr::read(mut_ref as *mut T); hole = Hole { active_holes: &self.active_holes, hole: mut_ref as *mut T, phantom: PhantomData, recovery: Some(recovery) }; }; (t, hole) } /// Takes a `(T, Hole<'c, 'm, T, F>)` from an `&'m mut T`. pub fn take<'c, 'm: 's, T: 'm>(&'c self, mut_ref: &'m mut T) -> (T, Hole<'c, 'm, T, fn() -> T>) { #[allow(missing_docs)] fn panic() -> T { panic!("Failed to recover a Hole!") } self.take_or_recover(mut_ref, panic) } } /// Main function to create a `Scope`. /// /// If the given closure ends without all Holes filled, will abort the program. pub fn scope<'s, F, R>(f: F) -> R where F: FnOnce(&Scope<'s>) -> R { let this = Scope { active_holes: Cell::new(0), marker: PhantomData }; let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { f(&this) })); if this.active_holes.get() != 0 { std::process::abort(); } match result { Ok(r) => r, Err(p) => panic::resume_unwind(p), } } /// A `Hole<'c, 'm, T, F>` represents an unfilled `&'m mut T` which must be filled before the end of the `Scope` with lifetime `'c` and recovery closure `F`. /// /// An unfilled `Hole<'c, 'm, T, F> that is destructed will try to use `F` to fill the hole. /// /// If the scope ends without the `Hole` being filled, the program will `std::process::abort()`. #[must_use] pub struct Hole<'c, 'm, T: 'm, F: FnOnce() -> T> { active_holes: &'c Cell, hole: *mut T, phantom: PhantomData<&'m mut T>, recovery: Option, } impl<'c, 'm, T: 'm, F: FnOnce() -> T> Hole<'c, 'm, T, F> { /// Fills the Hole. pub fn fill(self, t: T) { use std::ptr; use std::mem; unsafe { ptr::write(self.hole, t); } let num_holes = self.active_holes.get(); self.active_holes.set(num_holes - 1); mem::forget(self); } } impl<'c, 'm, T: 'm, F: FnOnce() -> T> Drop for Hole<'c, 'm, T, F> { fn drop(&mut self) { use std::ptr; let t = (self.recovery.take().expect("No recovery function in Hole!"))(); unsafe { ptr::write(self.hole, t); } let num_holes = self.active_holes.get(); self.active_holes.set(num_holes - 1); } } #[test] fn scope_based_take() { #[derive(Debug)] struct Foo; #[derive(Debug)] struct Bar { a: Foo, b: Foo } let mut bar = Bar { a: Foo, b: Foo }; scope(|scope| { let (a, a_hole) = scope.take(&mut bar.a); let (b, b_hole) = scope.take(&mut bar.b); // Imagine consuming a and b a_hole.fill(Foo); b_hole.fill(Foo); }); println!("{:?}", &bar); } #[test] fn panic_on_recovered_panic() { use std::panic; struct Foo; let mut foo = Foo; let result = panic::catch_unwind(panic::AssertUnwindSafe(|| { scope(|scope| { let (t, hole) = scope.take_or_recover(&mut foo, || Foo); panic!("Oops!"); }); })); assert!(result.is_err()); }