Crate lithium

Source
Expand description

Lightweight exceptions.

Lithium provides a custom exception mechanism as an alternative to Rust panics. Compared to Rust panics, this mechanism is allocation-free, avoids indirections and RTTI, and hence faster, if less applicable.

Under the default configuration, Lithium is more than 2x faster Rust panics on common Result-like usecases. See the benchmark.

§Usage

Throw an exception with throw, catch it with catch or the more low-level intercept. Unlike with Rust panics, non-Send and non-'static types can be used soundly.

Using the panic = "abort" strategy breaks Lithium; avoid doing that.

For interop, all crates that depend on Lithium need to use the same version:

[dependencies]
lithium = "1"

§Platform support

On stable Rust, Lithium uses the built-in panic mechanism, tweaking it to increase performance just a little bit.

On nightly Rust, Lithium uses a custom mechanism on the following targets:

TargetImplementationPerformanceno_std support
Linux, macOSItanium EH ABI2.5x faster than panicsYes
Windows (MSVC ABI)SEH1.5x faster than panicsYes
Windows (GNU ABI)Itanium EH ABI2.5x faster than panics, but slower than MSVCNo

Lithium strives to support all targets that Rust panics support. If Lithium does not work correctly on such a target, please open an issue.

no_std support can be enabled by using default-features = false (only on nightly). This requires an Itanium EH unwinder to be linked in on targets that use it as the implementation.

§Safety

Exceptions lack dynamic typing information. For soundness, the thrown and caught types must match exactly. Note that the functions are generic, and if the type is inferred wrong, UB will happen. Use turbofish to avoid this pitfall.

The matching types requirement only apply to exceptions that aren’t caught inside the catch/intercept callback. For example, this is sound:

use lithium::*;

struct A;
struct B;

unsafe {
    let _ = catch::<_, A>(|| {
        let _ = catch::<_, B>(|| throw(B));
        throw(A);
    });
}

The responsibility of holding this safety requirement is split between the throwing and the catching functions. All throwing functions must be unsafe, listing “only caught by type E” as a safety requirement. All catching functions that take a user-supplied callback must be unsafe too, listing “callback only throws type E” as a safety requirement.

Although seemingly redundant, this enables safe abstractions over exceptions when both the throwing and the catching functions are provided by one crate. As long as the exception types used by the crate match, all safe user-supplied callbacks are sound to call, because safe callbacks can only interact with exceptions in an isolated manner.

Structs§

Functions§