#thread-local #local #global #thread #variables

with-thread-local

A micro crate that simplifies a bit the use of the std macro thread_local!

1 stable release

1.0.0 Jan 11, 2023

#2642 in Rust patterns

MIT/Apache

7KB
51 lines

Rust Latest Version Rust 1.46+ License Docs.rs LOC Dependency Status

with-thread-local

A micro crate that simplifies a bit the use of the std macro thread_local!.

extern crate regex;

use with_thread_local::with_thread_local;
use regex::Regex;

let user_input = "cat";

let (is_a_pet, needs_a_walk) = with_thread_local! {
    static REGEX_PET: Regex = Regex::new(r"cat|dog").unwrap();
    static REGEX_WALK: Regex = Regex::new(r"dog").unwrap();

    {
        let is_a_pet = REGEX_PET.is_match(user_input);
        let needs_a_walk = REGEX_WALK.is_match(user_input);

        (is_a_pet, needs_a_walk)
    }
};

assert!(is_a_pet && !needs_a_walk);

You can also use its variant move to move variables inside the block. Though I admit I could not write a good example:

extern crate regex;

use with_thread_local::with_thread_local;
use regex::Regex;

let user_input = vec!["cat", "love", "dog"];

let output = with_thread_local! {
    static REGEX_PET: Regex = Regex::new(r"cat|dog").unwrap();

    move {
        user_input
            .into_iter()
            .filter(|s| REGEX_PET.is_match(s))
            .collect::<Vec<_>>()
    }
};

assert_eq!(output, ["cat", "dog"]);

No runtime deps