with-thread-local

Crates.iowith-thread-local
lib.rswith-thread-local
version1.0.0
sourcesrc
created_at2023-01-11 12:06:32.857897
updated_at2023-01-11 12:06:32.857897
descriptionA micro crate that simplifies a bit the use of the std macro `thread_local!`
homepagehttps://github.com/cecton/with-thread-local
repositoryhttps://github.com/cecton/with-thread-local
max_upload_size
id756362
size19,700
Cecile Tonglet (cecton)

documentation

https://docs.rs/with-thread-local

README

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"]);
Commit count: 1

cargo fmt