### Rustdoc Scraped Examples: Example Usage Source: https://docs.rs/scopeguard/1.2.0/scrape-examples-help Shows an example of how a Rust function, like the one defined in `src/lib.rs`, can be called from an example file. Rustdoc includes such calls in the generated documentation. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Rust Scope Guard Hello World Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Demonstrates the basic usage of `scopeguard::guard` to execute a closure when the guard goes out of scope. This example shows how to create a guard with a simple closure that prints a message. ```Rust #![cfg_attr(not(any(test, feature = "use_std")), no_std)] #![doc(html_root_url = "https://docs.rs/scopeguard/1/")] //! A scope guard will run a given closure when it goes out of scope, //! even if the code between panics. //! (as long as panic doesn't abort) //! //! # Examples //! //! ## Hello World //! //! This example creates a scope guard with an example function: //! //! ``` //! extern crate scopeguard; //! //! fn f() { //! let _guard = scopeguard::guard((), |_| { //! println!("Hello Scope Exit!"); //! }); //! //! // rest of the code here. //! //! // Here, at the end of `_guard`'s scope, the guard's closure is called. //! // It is also called if we exit this scope through unwinding instead. //! } //! # fn main() { //! # f(); //! # } //! ``` ``` -------------------------------- ### Rustdoc Scraped Examples: Function Definition Source: https://docs.rs/scopeguard/1.2.0/scrape-examples-help Demonstrates a simple public function within a Rust crate's source code that Rustdoc can scrape for examples. This function serves as a target for example usage. ```rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### scopeguard::guard Usage Example Source: https://docs.rs/scopeguard/1.2.0/scopeguard/fn.guard An example demonstrating the usage of the `guard` function to manage a file resource. The `guard` function takes ownership of the file and a closure that syncs the file content upon dropping the guard, ensuring resource cleanup. ```rust use scopeguard::guard; use std::fs::File; use std::io::Write; fn g() { let f = File::create("newfile.txt").unwrap(); let mut file = guard(f, |f| { // write file at return or panic let _ = f.sync_all(); }); // access the file through the scope guard itself file.write_all(b"test me\n").unwrap(); } ``` -------------------------------- ### Rust Insertion Sort Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Demonstrates an insertion sort algorithm implementation in Rust, showing how to manage a 'hole' in a vector during sorting. It includes a `main` function to test the sorting logic. ```Rust //! // plug the hole in the vector with the value that was // taken out //! let index = hole.index; //! ptr::copy_nonoverlapping(&*hole.value, &mut hole.v[index], 1); //! }); //! //! // run algorithm that moves the hole in the vector here //! // move the hole until it's in a sorted position //! for i in 1..hole_guard.v.len() { //! if *hole_guard.value >= hole_guard.v[i] { //! // move the element back and the hole forward //! let index = hole_guard.index; //! hole_guard.v.swap(index, index + 1); //! hole_guard.index += 1; //! } else { //! break; //! } //! } //! //! // When the scope exits here, the Vec becomes whole again! //! } //! } //! //! fn main() { //! let string = String::from; //! let mut data = vec![string("c"), string("a"), string("b"), string("d")]; //! insertion_sort_first(&mut data); //! assert_eq!(data, vec!["a", "b", "c", "d"]); //! } ``` -------------------------------- ### Rust defer! Macro Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Demonstrates the basic usage of the `defer!` macro to execute a closure when the current scope exits. This is useful for simple cleanup tasks that should always run. ```rust use std::cell::Cell; // Assuming defer! macro is available // let drops = Cell::new(0); // defer!(drops.set(1000)); // assert_eq!(drops.get(), 0); // The closure `drops.set(1000)` will execute when the scope ends. ``` -------------------------------- ### Rust Scope Guard File Sync Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Shows how to use `scopeguard::guard` to manage a resource, specifically a file, ensuring that a cleanup operation (syncing the file) is performed when the scope exits. This pattern is useful for guaranteeing resource finalization. ```Rust extern crate scopeguard; use std::fs::* use std::io::{self, Write}; # // Mock file so that we don't actually write a file # struct MockFile; # impl MockFile { # fn create(_s: &str) -> io::Result { Ok(MockFile) } # fn write_all(&self, _b: &[u8]) -> io::Result<()> { Ok(()) } # fn sync_all(&self) -> io::Result<()> { Ok(()) } # } # use self::MockFile as File; fn try_main() -> io::Result<()> { let f = File::create("newfile.txt")?; let mut file = scopeguard::guard(f, |f| { // ensure we flush file at return or panic let _ = f.sync_all(); }); // Access the file through the scope guard itself file.write_all(b"test me\n").map(|_| ()) } fn main() { try_main().unwrap(); } ``` -------------------------------- ### ScopeGuard Usage Example Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Demonstrates the usage of ScopeGuard, including creating a guard with a closure, modifying the guarded value, and conditionally extracting the value using `into_inner`. ```rust extern crate scopeguard; use scopeguard::{guard, ScopeGuard}; fn conditional() -> bool { true } fn main() { let mut guard = guard(Vec::new(), |mut v| v.clear()); guard.push(1); if conditional() { // a condition maybe makes us decide to // “defuse” the guard and get back its inner parts let value = ScopeGuard::into_inner(guard); } else { // guard still exists in this branch } } ``` -------------------------------- ### Rust defer_on_success! Macro Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Illustrates the `defer_on_success!` macro, which executes a closure only if the scope exits normally (without a panic). This is useful for actions that should only occur on successful completion. ```rust use std::cell::Cell; use std::panic::catch_unwind; use std::panic::AssertUnwindSafe; // let drops = Cell::new(0); // { // defer_on_success!(drops.set(1)); // assert_eq!(drops.get(), 0); // } // assert_eq!(drops.get(), 1); // // let _ = catch_unwind(AssertUnwindSafe(|| { // defer_on_success!(drops.set(1)); // panic!("failure") // })); // assert_eq!(drops.get(), 0); // Closure does not run on panic ``` -------------------------------- ### Rust defer_on_unwind! Macro Example Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Shows the `defer_on_unwind!` macro, which executes a closure only if the scope exits due to a panic. This is ideal for cleanup actions specifically needed when an error or panic occurs. ```rust use std::cell::Cell; use std::panic::catch_unwind; use std::panic::AssertUnwindSafe; // let drops = Cell::new(0); // let _ = catch_unwind(AssertUnwindSafe(|| { // defer_on_unwind!(drops.set(1)); // assert_eq!(drops.get(), 0); // panic!("failure") // })); // assert_eq!(drops.get(), 1); // // { // defer_on_unwind!(drops.set(1)); // } // assert_eq!(drops.get(), 0); // Closure does not run on normal exit ``` -------------------------------- ### guard_on_unwind Function Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Creates a `ScopeGuard` that executes its closure only on unwind (i.e., when a panic occurs). Requires the `use_std` feature. An example shows manual defusing in no-std contexts. ```rust /// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. /// /// Requires crate feature `use_std`. /// /// ## Examples /// /// For performance reasons, or to emulate “only run guard on unwind” in /// no-std environments, we can also use the default guard and simply manually /// defuse it at the end of scope like the following example. (The performance /// reason would be if the [`OnUnwind`]'s call to [std::thread::panicking()] is /// an issue.) /// /// ``` /// extern crate scopeguard; /// /// use scopeguard::ScopeGuard; /// # fn main() { /// { /// let guard = scopeguard::guard((), |_| {}); /// /// // rest of the code here /// /// // we reached the end of scope without unwinding - defuse it /// ScopeGuard::into_inner(guard); /// } /// # } /// ``` #[cfg(feature = "use_std")] #[inline] #[must_use] pub fn guard_on_unwind(v: T, dropfn: F) -> ScopeGuard where F: FnOnce(T), { ScopeGuard::with_strategy(v, dropfn) } ``` -------------------------------- ### Using the defer! Macro Source: https://docs.rs/scopeguard/1.2.0/index Illustrates the use of the `defer!` macro from the scopeguard crate. This macro simplifies the creation of scope guards for immediate scope exit execution, making it convenient for deferred operations. It ensures the enclosed code runs on normal scope exit or during panic unwinding. ```Rust #[macro_use(defer)] extern crate scopeguard; use std::cell::Cell; fn main() { // use a cell to observe drops during and after the scope guard is active let drop_counter = Cell::new(0); { // Create a scope guard using `defer!` for the current scope defer! { drop_counter.set(1 + drop_counter.get()); } // Do regular operations here in the meantime. // Just before scope exit: it hasn't run yet. assert_eq!(drop_counter.get(), 0); // The following scope end is where the defer closure is called } assert_eq!(drop_counter.get(), 1); } ``` -------------------------------- ### Using the defer! Macro Source: https://docs.rs/scopeguard/1.2.0/scopeguard Illustrates the use of the `defer!` macro from the scopeguard crate. This macro simplifies the creation of scope guards for immediate scope exit execution, making it convenient for deferred operations. It ensures the enclosed code runs on normal scope exit or during panic unwinding. ```Rust #[macro_use(defer)] extern crate scopeguard; use std::cell::Cell; fn main() { // use a cell to observe drops during and after the scope guard is active let drop_counter = Cell::new(0); { // Create a scope guard using `defer!` for the current scope defer! { drop_counter.set(1 + drop_counter.get()); } // Do regular operations here in the meantime. // Just before scope exit: it hasn't run yet. assert_eq!(drop_counter.get(), 0); // The following scope end is where the defer closure is called } assert_eq!(drop_counter.get(), 1); } ``` -------------------------------- ### Using the defer! Macro Source: https://docs.rs/scopeguard/1.2.0/scopeguard/index Illustrates the use of the `defer!` macro from the scopeguard crate. This macro simplifies the creation of scope guards for immediate scope exit execution, making it convenient for deferred operations. It ensures the enclosed code runs on normal scope exit or during panic unwinding. ```Rust #[macro_use(defer)] extern crate scopeguard; use std::cell::Cell; fn main() { // use a cell to observe drops during and after the scope guard is active let drop_counter = Cell::new(0); { // Create a scope guard using `defer!` for the current scope defer! { drop_counter.set(1 + drop_counter.get()); } // Do regular operations here in the meantime. // Just before scope exit: it hasn't run yet. assert_eq!(drop_counter.get(), 0); // The following scope end is where the defer closure is called } assert_eq!(drop_counter.get(), 1); } ``` -------------------------------- ### Rust Strategy Trait and Methods Source: https://docs.rs/scopeguard/1.2.0/scopeguard/trait.Strategy Documentation for the `Strategy` trait in the scopeguard crate. It controls when associated code should run and includes the `should_run` method. The trait is not dyn compatible. ```Rust pub trait Strategy { // Required method fn should_run() -> bool; } ``` ```APIDOC Trait: Strategy Description: Controls in which cases the associated code should be run. Dyn Compatibility: This trait is not dyn compatible. Required Methods: - fn should_run() -> bool Description: Return `true` if the guard’s associated code should run (in the context where this method is called). Source: ../src/scopeguard/lib.rs.html#204 Implementors: - impl Strategy for Always - impl Strategy for OnSuccess - impl Strategy for OnUnwind ``` -------------------------------- ### Create ScopeGuard with Strategy Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Creates a ScopeGuard that owns a value `v` and executes a provided `dropfn` when the guard's destructor runs. The execution of `dropfn` is determined by an associated `Strategy`. ```rust pub fn with_strategy(v: T, dropfn: F) -> ScopeGuard ``` -------------------------------- ### Resource Management with scopeguard::guard in Rust Source: https://docs.rs/scopeguard/1.2.0/src/readme/readme.rs Illustrates using `scopeguard::guard` for RAII-style resource management. It takes a resource and a closure that will be executed with the resource when the guard goes out of scope, ensuring resources like files are properly handled. ```Rust use std::fs::File; use std::io::Write; use scopeguard::guard; fn g() { let f = File::create("newfile.txt").unwrap(); let mut file = guard(f, |f| { // write file at return or panic let _ = f.sync_all(); }); // access the file through the scope guard itself file.write_all(b"test me\n").unwrap(); } fn main() { g(); } ``` -------------------------------- ### Rust From and Into Trait Implementations Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Documents the identity implementations for `From for T` and `Into for T` where `U` implements `From`. The `from` method returns the argument unchanged, and `into` calls the corresponding `from` method. ```APIDOC impl From for T fn from(t: T) -> T - Returns the argument unchanged. - Source: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#774 impl Into for T where U: From fn into(self) -> U - Calls `U::from(self)`. - That is, this conversion is whatever the implementation of `From for U` chooses to do. - Source: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#767 ``` -------------------------------- ### Rust Defer Macros Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Provides macros (`defer!`, `defer_on_success!`, `defer_on_unwind!`) for creating `ScopeGuard` instances with different execution strategies. These macros simplify the process of deferring code execution until the scope exits. ```APIDOC /// Macro to create a `ScopeGuard` (always run). /// /// The macro takes statements, which are the body of a closure /// that will run when the scope is exited. #[macro_export] macro_rules! defer { ($($t:tt)*) => { let _guard = $crate::guard((), |()| { $($t)* }); }; } /// Macro to create a `ScopeGuard` (run on successful scope exit). /// /// The macro takes statements, which are the body of a closure /// that will run when the scope is exited. /// /// Requires crate feature `use_std`. #[cfg(feature = "use_std")] #[macro_export] macro_rules! defer_on_success { ($($t:tt)*) => { let _guard = $crate::guard_on_success((), |()| { $($t)* }); }; } /// Macro to create a `ScopeGuard` (run on unwinding from panic). /// /// The macro takes statements, which are the body of a closure /// that will run when the scope is exited. /// /// Requires crate feature `use_std`. #[cfg(feature = "use_std")] #[macro_export] macro_rules! defer_on_unwind { ($($t:tt)*) => { let _guard = $crate::guard_on_unwind((), |()| { $($t)* }); }; } ``` -------------------------------- ### ScopeGuard Methods and Implementations Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Lists available methods and trait implementations for the ScopeGuard struct. Methods include `into_inner` and `with_strategy`. Trait implementations cover Debug, Deref, DerefMut, Drop, Sync, and various blanket implementations. ```APIDOC ScopeGuard Methods and Implementations Methods: * `into_inner` * `with_strategy` Trait Implementations: * `Debug` for `ScopeGuard` * `Deref` for `ScopeGuard` * `DerefMut` for `ScopeGuard` * `Drop` for `ScopeGuard` * `Sync` for `ScopeGuard` Auto Trait Implementations: * `Freeze` for `ScopeGuard` * `RefUnwindSafe` for `ScopeGuard` * `Send` for `ScopeGuard` * `Unpin` for `ScopeGuard` * `UnwindSafe` for `ScopeGuard` Blanket Implementations: * `Any` for `T` * `Borrow` for `T` * `BorrowMut` for `T` * `From` for `T` * `Into` for `T` * `Receiver` for `P` * `TryFrom` for `T` * `TryInto` for `T` ``` -------------------------------- ### Rust ScopeGuard Basic Usage Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Demonstrates the fundamental use of the `guard` function to create a ScopeGuard. This guard ensures that a provided closure is executed when the guard goes out of scope, similar to `defer!`. ```rust use std::cell::Cell; // let value_drops = Cell::new(0); // let value = guard((), |()| value_drops.set(1 + value_drops.get())); // let closure_drops = Cell::new(0); // let guard = guard(value, |_| closure_drops.set(1 + closure_drops.get())); // assert_eq!(value_drops.get(), 0); // assert_eq!(closure_drops.get(), 0); // drop(guard); // Explicitly dropping the guard triggers the closure // assert_eq!(value_drops.get(), 1); // assert_eq!(closure_drops.get(), 1); ``` -------------------------------- ### File Ownership and Sync on Scope Exit Source: https://docs.rs/scopeguard/1.2.0/index Demonstrates using scopeguard to manage a file handle, ensuring that pending writes are synchronized to disk when the guard's scope is exited, even if an error occurs. ```rust extern crate scopeguard; use std::fs::File; use std::io::{self, Write}; fn try_main() -> io::Result<()> { let f = File::create("newfile.txt")?; let mut file = scopeguard::guard(f, |f| { // ensure we flush file at return or panic let _ = f.sync_all(); }); // Access the file through the scope guard itself file.write_all(b"test me\n").map(|_| ()) } fn main() { try_main().unwrap(); } ``` -------------------------------- ### File Ownership and Sync on Scope Exit Source: https://docs.rs/scopeguard/1.2.0/scopeguard Demonstrates using scopeguard to manage a file handle, ensuring that pending writes are synchronized to disk when the guard's scope is exited, even if an error occurs. ```rust extern crate scopeguard; use std::fs::File; use std::io::{self, Write}; fn try_main() -> io::Result<()> { let f = File::create("newfile.txt")?; let mut file = scopeguard::guard(f, |f| { // ensure we flush file at return or panic let _ = f.sync_all(); }); // Access the file through the scope guard itself file.write_all(b"test me\n").map(|_| ()) } fn main() { try_main().unwrap(); } ``` -------------------------------- ### File Ownership and Sync on Scope Exit Source: https://docs.rs/scopeguard/1.2.0/scopeguard/index Demonstrates using scopeguard to manage a file handle, ensuring that pending writes are synchronized to disk when the guard's scope is exited, even if an error occurs. ```rust extern crate scopeguard; use std::fs::File; use std::io::{self, Write}; fn try_main() -> io::Result<()> { let f = File::create("newfile.txt")?; let mut file = scopeguard::guard(f, |f| { // ensure we flush file at return or panic let _ = f.sync_all(); }); // Access the file through the scope guard itself file.write_all(b"test me\n").map(|_| ()) } fn main() { try_main().unwrap(); } ``` -------------------------------- ### Basic Scope Guard Usage Source: https://docs.rs/scopeguard/1.2.0/scopeguard/index Demonstrates the fundamental use of scopeguard::guard to execute a closure upon scope exit. This is useful for resource cleanup or logging, and it functions correctly even if the scope is exited via unwinding due to a panic. ```Rust extern crate scopeguard; fn f() { let _guard = scopeguard::guard((), |_| { println!("Hello Scope Exit!"); }); // rest of the code here. // Here, at the end of `_guard`'s scope, the guard's closure is called. // It is also called if we exit this scope through unwinding instead. } ``` -------------------------------- ### Basic Scope Guard Usage Source: https://docs.rs/scopeguard/1.2.0/index Demonstrates the fundamental use of scopeguard::guard to execute a closure upon scope exit. This is useful for resource cleanup or logging, and it functions correctly even if the scope is exited via unwinding due to a panic. ```Rust extern crate scopeguard; fn f() { let _guard = scopeguard::guard((), |_| { println!("Hello Scope Exit!"); }); // rest of the code here. // Here, at the end of `_guard`'s scope, the guard's closure is called. // It is also called if we exit this scope through unwinding instead. } ``` -------------------------------- ### Basic Scope Guard Usage Source: https://docs.rs/scopeguard/1.2.0/scopeguard Demonstrates the fundamental use of scopeguard::guard to execute a closure upon scope exit. This is useful for resource cleanup or logging, and it functions correctly even if the scope is exited via unwinding due to a panic. ```Rust extern crate scopeguard; fn f() { let _guard = scopeguard::guard((), |_| { println!("Hello Scope Exit!"); }); // rest of the code here. // Here, at the end of `_guard`'s scope, the guard's closure is called. // It is also called if we exit this scope through unwinding instead. } ``` -------------------------------- ### ScopeGuard::with_strategy Constructor Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Creates a `ScopeGuard` that owns a value `v` and will call `dropfn` when its destructor runs. The `Strategy` determines if the closure is executed. ```rust /// Create a `ScopeGuard` that owns `v` (accessible through deref) and calls /// `dropfn` when its destructor runs. /// /// The `Strategy` decides whether the scope guard's closure should run. #[inline] #[must_use] pub fn with_strategy(v: T, dropfn: F) -> ScopeGuard { ScopeGuard { value: ManuallyDrop::new(v), dropfn: ManuallyDrop::new(dropfn), strategy: PhantomData, } } ``` -------------------------------- ### Using defer! Macro in Rust Source: https://docs.rs/scopeguard/1.2.0/src/readme/readme.rs Demonstrates the `defer!` macro from the `scopeguard` crate. This macro executes a block of code when the current scope exits, either normally or via panic. It's useful for ensuring cleanup actions are performed. ```Rust extern crate scopeguard; use scopeguard::guard; fn f() { defer! { println!("Called at return or panic"); } panic!(); } fn main() { f(); } ``` -------------------------------- ### Generic Blanket Implementations: From and Into Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.Always This documentation covers the blanket implementations of `std::convert::From` and `std::convert::Into` for generic types. The `From` trait allows conversion from one type to another, while `Into` provides a convenient, symmetric way to perform these conversions, often used for type ergonomics. ```APIDOC impl From for T - Implementation of `From` for a type to itself. fn from(t: T) -> T - Returns the argument unchanged. - Parameters: - t: The value to convert. ``` ```APIDOC impl Into for T where U: From - Blanket implementation of `Into` for types `T` that can be converted into `U`. fn into(self) -> U - Calls `U::from(self)`. - This conversion is whatever the implementation of `From for U` chooses to do. - Parameters: - self: The value to convert. ``` -------------------------------- ### Rust Defer Macro for Scope Exit Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Illustrates the use of the `defer!` macro from the `scopeguard` crate. This macro allows executing code at the end of the current scope, providing a convenient way to handle cleanup or side effects, even during unwinding from a panic. ```Rust #[macro_use(defer)] extern crate scopeguard; use std::cell::Cell; fn main() { // use a cell to observe drops during and after the scope guard is active let drop_counter = Cell::new(0); { // Create a scope guard using `defer!` for the current scope defer! { drop_counter.set(1 + drop_counter.get()); } // Do regular operations here in the meantime. // Just before scope exit: it hasn't run yet. assert_eq!(drop_counter.get(), 0); // The following scope end is where the defer closure is called } assert_eq!(drop_counter.get(), 1); } ``` -------------------------------- ### Generic Type Blanket Implementations Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.OnSuccess Documents blanket implementations of core Rust traits for any generic type `T`. This includes traits like `Any`, `Borrow`, `BorrowMut`, `From`, `Into`, and `TryFrom`, showcasing common functionalities available for most types. ```APIDOC Generic Type Blanket Implementations: - impl Any for T where T: 'static + ?Sized - fn type_id(&self) -> TypeId - Gets the TypeId of self. - impl Borrow for T where T: ?Sized - fn borrow(&self) -> &T - Immutably borrows from an owned value. - impl BorrowMut for T where T: ?Sized - fn borrow_mut(&mut self) -> &mut T - Mutably borrows from an owned value. - impl From for T - fn from(t: T) -> T - Returns the argument unchanged. - impl Into for T where U: From - fn into(self) -> U - Calls U::from(self). - impl TryFrom for T (No methods detailed in source) These blanket implementations provide fundamental capabilities for types, enabling introspection, borrowing, conversion, and other common operations. ``` -------------------------------- ### defer_on_unwind Macro Source: https://docs.rs/scopeguard/1.2.0/scopeguard/macro.defer_on_unwind Macro to create a ScopeGuard that runs on unwinding from panic. It takes statements as the body of a closure that will run when the scope is exited. Requires crate feature `use_std`. ```APIDOC macro_rules! defer_on_unwind { ($($t:tt)*) => { ... }; } # Description: Macro to create a `ScopeGuard` (run on unwinding from panic). The macro takes statements, which are the body of a closure that will run when the scope is exited. # Requirements: Requires crate feature `use_std`. ``` -------------------------------- ### Rust ScopeGuard Debug Implementation Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Shows the `fmt::Debug` implementation for `ScopeGuard`, allowing it to be printed for debugging purposes. It displays the struct name and the debug representation of the contained value. ```rust use std::fmt; // Assuming ScopeGuard is defined and T: fmt::Debug // impl fmt::Debug for ScopeGuard // where // T: fmt::Debug, // F: FnOnce(T), // S: Strategy, // { // fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // f.debug_struct(stringify!(ScopeGuard)) // .field("value", &*self.value) // .finish() // } // } ``` -------------------------------- ### Rust TryFrom and TryInto Trait Implementations Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Documents the implementations of `TryFrom for T` and `TryInto for T`. `TryFrom` defines an `Error` type (here `Infallible`) and a `try_from` method for fallible conversions. `TryInto` is the reciprocal trait. ```APIDOC impl TryFrom for T where U: Into type Error = Infallible - The type returned in the event of a conversion error. - Source: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#813 fn try_from(value: U) -> Result>::Error> - Performs the conversion. - Source: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#817 impl TryInto for T where U: TryFrom - No methods shown, but provides the `try_into` method. - Source: https://doc.rust-lang.org/nightly/src/core/convert/mod.rs.html#798 ``` -------------------------------- ### Rust macro defer_on_success Source: https://docs.rs/scopeguard/1.2.0/scopeguard/macro.defer_on_success Macro to create a ScopeGuard that runs on successful scope exit. It accepts statements as the body of a closure to be executed upon scope exit. Requires the `use_std` crate feature. ```Rust macro_rules! defer_on_success { ($($t:tt)*) => { ... }; } ``` -------------------------------- ### OnSuccess Strategy Trait Implementation Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.OnSuccess Implements the Strategy trait for the OnSuccess enum. The should_run method determines if the guard's associated code should execute. ```APIDOC impl Strategy for OnSuccess should_run() -> bool Return `true` if the guard’s associated code should run (in the context where this method is called). ``` -------------------------------- ### ScopeGuard Debug Implementation Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Implements the Debug trait for ScopeGuard, allowing it to be formatted for debugging purposes. Requires the owned value `T` to also implement Debug. ```APIDOC impl Debug for ScopeGuard where T: Debug, F: FnOnce(T), S: Strategy fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### OnUnwind Strategy Implementation Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.OnUnwind Implements the Strategy trait for the OnUnwind enum. The should_run method determines if the guard's associated code should execute during unwinding. ```rust impl Strategy for OnUnwind { fn should_run() -> bool } ``` -------------------------------- ### OnUnwind Debug Implementation Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.OnUnwind Implements the Debug trait for the OnUnwind enum, allowing it to be formatted for debugging purposes. This implementation is sourced from the crate's lib.rs file. ```rust impl Debug for OnUnwind { fn fmt(&self, f: &mut Formatter<'_>) -> Result } ``` -------------------------------- ### Rust ScopeGuard Strategies Source: https://docs.rs/scopeguard/1.2.0/src/scopeguard/lib.rs Defines the `Strategy` trait and its implementations (`Always`, `OnUnwind`, `OnSuccess`) for controlling when associated code runs on scope exit. `OnUnwind` and `OnSuccess` require the `use_std` feature. ```APIDOC /// Controls in which cases the associated code should be run /// (in the context where this method is called). pub trait Strategy { /// Return `true` if the guard’s associated code should run /// (in the context where this method is called). fn should_run() -> bool; } /// Always run on scope exit. /// /// “Always” run: on regular exit from a scope or on unwinding from a panic. /// Can not run on abort, process exit, and other catastrophic events where /// destructors don’t run. #[derive(Debug)] pub enum Always {} /// Run on scope exit through unwinding. /// /// Requires crate feature `use_std`. #[cfg(feature = "use_std")] #[derive(Debug)] pub enum OnUnwind {} /// Run on regular scope exit, when not unwinding. /// /// Requires crate feature `use_std`. #[cfg(feature = "use_std")] #[derive(Debug)] pub enum OnSuccess {} impl Strategy for Always { #[inline(always)] fn should_run() -> bool { true } } #[cfg(feature = "use_std")] impl Strategy for OnUnwind { #[inline] fn should_run() -> bool { std::thread::panicking() } } #[cfg(feature = "use_std")] impl Strategy for OnSuccess { #[inline] fn should_run() -> bool { !std::thread::panicking() } } ``` -------------------------------- ### Rust TryInto Trait and try_into Method Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Details the `TryInto` trait in Rust, which provides a fallible conversion mechanism. It defines an associated `Error` type for conversion failures and the `try_into` method that returns a `Result` indicating success or failure. ```rust type Error = >::Error; fn try_into(self) -> Result>::Error>; ``` -------------------------------- ### Restoring Invariants with ScopeGuard Source: https://docs.rs/scopeguard/1.2.0/index Illustrates how scopeguard can safely restore a vector's invariant (all elements initialized) when temporarily violating it for optimization during an insertion sort-like operation. It handles potential panics during user-provided comparison logic. ```rust extern crate scopeguard; use std::mem::ManuallyDrop; use std::ptr; // This function, just for this example, takes the first element // and inserts it into the assumed sorted tail of the vector. // // For optimization purposes we temporarily violate an invariant of the // Vec, that it owns all of its elements. // // The safe approach is to use swap, which means two writes to memory, // the optimization is to use a “hole” which uses only one write of memory // for each position it moves. // // We *must* use a scope guard to run this code safely. We // are running arbitrary user code (comparison operators) that may panic. // The scope guard ensures we restore the invariant after successful // exit or during unwinding from panic. fn insertion_sort_first(v: &mut Vec) where T: PartialOrd { struct Hole<'a, T: 'a> { v: &'a mut Vec, index: usize, value: ManuallyDrop, } unsafe { // Create a moved-from location in the vector, a “hole”. let value = ptr::read(&v[0]); let mut hole = Hole { v: v, index: 0, value: ManuallyDrop::new(value) }; // Use a scope guard with a value. // At scope exit, plug the hole so that the vector is fully // initialized again. // The scope guard owns the hole, but we can access it through the guard. let mut hole_guard = scopeguard::guard(hole, |hole| { // plug the hole in the vector with the value that was // taken out let index = hole.index; ptr::copy_nonoverlapping(&*hole.value, &mut hole.v[index], 1); }); // run algorithm that moves the hole in the vector here // move the hole until it's in a sorted position for i in 1..hole_guard.v.len() { if *hole_guard.value >= hole_guard.v[i] { // move the element back and the hole forward let index = hole_guard.index; hole_guard.v.swap(index, index + 1); hole_guard.index += 1; } else { break; } } // When the scope exits here, the Vec becomes whole again! } } fn main() { let string = String::from; let mut data = vec![string("c"), string("a"), string("b"), string("d")]; insertion_sort_first(&mut data); assert_eq!(data, vec!["a", "b", "c", "d"]); } ``` -------------------------------- ### Generic Blanket Implementations (Rust) Source: https://docs.rs/scopeguard/1.2.0/scopeguard/struct.ScopeGuard Documents blanket implementations for generic types T, enabling standard traits like Any and Borrow for any type that meets the trait's bounds. This allows for common operations and introspection on generic data. ```rust impl Any for T where T: 'static + ?Sized fn type_id(&self) -> TypeId ``` ```rust impl Borrow for T where T: ?Sized fn borrow(&self) -> &T ``` ```rust impl BorrowMut for T where T: ?Sized fn borrow_mut(&mut self) -> &mut T ``` -------------------------------- ### Generic Blanket Implementations: TryFrom Source: https://docs.rs/scopeguard/1.2.0/scopeguard/enum.Always This entry describes the blanket implementation of the `std::convert::TryFrom` trait for generic types. `TryFrom` is used for fallible conversions, where a conversion might fail and return a `Result`. The provided snippet shows the trait signature but not specific implementations. ```APIDOC impl TryFrom for T - Blanket implementation of `TryFrom` for types `T` that can be fallibly converted from `U`. - Note: Specific conversion logic and error types depend on individual trait implementations. ```