Crate drop_code

Source
Expand description

A macro that allows you to implement code that will be automatically executed after the function code has finished, be it the end of the function or even a panic state.

§Short example

use drop_code::drop_code;

#[allow(unreachable_code)]
fn main() {
	drop_code! {
		println!("Code that must be executed in any situation."); // 3
	}

	println!("your code"); // 1
	panic!("panic info"); // 2
}

§Full syntax example

use drop_code::drop_code;

struct AlwaysDropLogic {}

impl AlwaysDropLogic {
	fn drop_logic(&mut self) {
		println!("#[] drop_logic!");
	}

	fn valid_logic(&mut self) {
		println!("#[] valid_logic!");
	}
}

fn main() {
	let mut adl = AlwaysDropLogic {};
	drop_code!(#[inline(always)]: (mut adl: AlwaysDropLogic) {
		adl.drop_logic();
	});

	adl.valid_logic();
	// out:
	// #[] valid_logic!
	// #[] drop_logic!
}

§How does this work?

The drop_code macro generates a hidden structure and defines the code for the Drop trait, the user can pass any data to the structure to create more complex code. The Drop trait mechanism ensures that critical operations are executed when an object is destroyed, making it easier to reliably handle important code in Rust applications, but note that the order of code execution is determined by Rust’s rules and conventions. Note that this code is executed even during a panic, but only if you have not disabled stack unwinding.

Macros§

drop_code
Macro for ensuring critical code execution on function return or panics in Rust, making it easy to include essential code for reliable operation.