3 releases

Uses new Rust 2024

new 0.1.2 Apr 28, 2025
0.1.1 Apr 21, 2025
0.1.0 Apr 17, 2025

#6 in #thread-local

Download history 143/week @ 2025-04-13 120/week @ 2025-04-20

263 downloads per month

MIT license

25KB
324 lines

Bypass

Thread-local dynamic variables.

crates.io Documentation MIT licensed


lib.rs:

Bypass: Thread-local dynamic variables

It is sometimes convenient to pass certain values by using an implicit environment. This crate implements such an environment. We "bypass" the standard way of passing values through arguments and return values, and instead store our values in a thread-local key-value store.

This effectively mimics the concept of "dynamic variables" in some other languages.

Examples

use bypass as by;

by::scope(|| {
    by::insert("some name", 123);
    some_function();
});

fn some_function() {
    let item: i32 = by::get("some name");
    println!("Fetched some name: {}", item);
}

This also allows us to pass data back by calling [insert] inside some_function, and calling [get] or [remove] after the function call completes.

Intended usage

Bypass is not intended to supplant the normal argument-and-return method of passing data around. Its main purpose is to provide a way to avoid tramp data - data that is only passed through a significant amount of functions without being used directly.

Passing such data along through every intermediary may be cumbersome and noisy. Bypass serves as an alternative mainly for such cases. Especially during the exploratory phase of programming, we may want to experiment with just making some value available somewhere else. Having to pass said value through many places can consume significant time. Bypass can be used instead to quickly get a prototype up and running.

Similarly, we can use bypass to "return" data from a deeply nested call where we are not interested in returning it through every stack frame manually.

Panics

Because of its intended usage being for semi-global configuration parameters, or during the construction of objects in deeply nested object chains, bypass will panic if a key is not found, or the type is not what we expected.

Logging

Keys can be either &'static str or a String. When strings are constructed (e.g. via format!), it may be hard to figure out where a key is inserted in a codebase. To debug this library you can set a logger via [debug]. This logger is local to the current thread.

If no logger is set then the default logger will be used that prints all operations to stderr. The default logger prints the code location from where each operation ([scope], [insert], [get], [remove]) is called using #[track_caller].

Dropping

Upon exiting a [scope], values that are part of that scope will be dropped in the lexicographic order of their associated keys.

Dependencies

~10KB