no_drop
A selection of guard types that guard against values being automatically dropped, ensuring a value is explicitly consumed.
Features
NoDropandNoDropMsg- Wraps a value in a guard type to ensure it is explicitly consumed before the guard is dropped.DropGuardandDropGuardMsg- A mutable drop guard that can be dynamically armed and disarmed.dbgandrlsmodules - identical API, provide panic protection in debug mode only or in all builds respectively.
Install
It's on crates.io.
Usage - NoDrop and NoDropMsg
Wrap a value in a guard type to ensure it is explicitly consumed before the guard is dropped.
use NoDrop;
let value = wrap;
// Extract the value safely
let inner = value.unwrap;
assert_eq!;
let value = wrap;
drop; // panic: "Value was dropped without being unwrapped"
For more descriptive error messages, use NoDropMsg with custom panic messages:
use NoDropMsg;
// msg can be an owned or borrowed value
let value = wrap;
drop; // panic: "forgot to process the answer"
Using as a Drop Guard
NoDrop and NoDropMsg support using unit type () instances, allowing you to use them as drop guards within another type, to ensure a specific method is called before the type is dropped. This can be useful to enforce a manual RAII pattern or to enforce a builder pattern.
use NoDrop;
// NoDrop implements Default and Debug
let t = new;
// do work.
t.finalize;
// Dropping without calling `finalize()` would panic.
For custom panic messages with drop guards, use NoDropMsg::guard
Usage - DropGuard and DropGuardMsg
Unlike NoDrop types, which are consumed when unwrapped, DropGuards can be dynamically armed and disarmed. This makes them ideal for protecting mutable state or critical sections that may be entered and exited, possibly multiple times.
use DropGuard;
let mut guard = new_armed;
// Check state
assert!;
// do work...
// Safely exit critical section
guard.disarm;
// Can rearm if needed
guard.arm;
guard.disarm; // Message is retained across arm/disarm cycles
For cases where you don't need a custom panic message, use DropGuardEmpty, which provides the same arm/disarm functionality with a default panic message
Debug vs Release Variants
NoDrop, NoDropMsg, DropGuard, DropGuardEmpty have debug-only and always-panicking variants:
dbg::NoDrop: Zero-cost in release builds, panics only in debug moderls::NoDrop: Always panics in both debug and release buildsdbg::NoDropMsg: Zero-cost in release builds, panics only in debug moderls::NoDropMsg: Always panics in both debug and release buildsdbg::DropGuard: Nearly zero-cost in release builds (onebool), panics only in debug moderls::DropGuard: Always panics in both debug and release buildsdbg::DropGuardEmpty: Nearly zero-cost in release builds (onebool), panics only in debug moderls::DropGuardEmpty: Always panics in both debug and release builds