#counter #id #identifier #count

simple-counter

Macro for generating thread-local static counters. Useful for basic ID generation.

1 unstable release

Uses old Rust 2015

0.1.0 Jul 17, 2018

#1676 in Rust patterns

Download history 150/week @ 2024-03-11 122/week @ 2024-03-18 187/week @ 2024-03-25 223/week @ 2024-04-01 73/week @ 2024-04-08 85/week @ 2024-04-15 121/week @ 2024-04-22 106/week @ 2024-04-29 75/week @ 2024-05-06 116/week @ 2024-05-13 121/week @ 2024-05-20 106/week @ 2024-05-27 106/week @ 2024-06-03 133/week @ 2024-06-10 91/week @ 2024-06-17 115/week @ 2024-06-24

458 downloads per month
Used in 6 crates (2 directly)

MIT license

5KB
53 lines

simple-counter

Provides a single macro for generating thread-local global counters by creating a new module with a thread-local static Cell. Currently intended to be used with integer types. Useful for basic ID generation.

Usage

Add the following dependency to your Cargo.toml file:

[dependencies]
simple-counter = "0.1.0"

And make sure to use the #[macro_use] annotation when importing:

#[macro_use]
extern crate simple_counter;

generate_counter!(Counter, usize);

fn main() {

  // Starts at 0 by default
  assert_eq!(Counter::next(), 0);
  assert_eq!(Counter::next(), 1);
  assert_eq!(Counter::next(), 2);

  // Can be set to arbitrary value
  Counter::set(1000);
  assert_eq!(Counter::next(), 1000);
  assert_eq!(Counter::next(), 1001);
  assert_eq!(Counter::next(), 1002);

  // Or reset to 0
  Counter::reset();
  assert_eq!(Counter::next(), 0);
}

Example

Here's a simple unique temp generator for a compiler:

#[macro_use]
extern crate simple_counter;

generate_counter!(TempID, usize);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Temp {
    id: usize,
    name: String,
}

impl Temp {
    pub fn from_str(name: &'static str) -> Self {
        Temp {
            id: TempID::next(),
            name: name.to_string(),
        }
    }
}

No runtime deps