Safe, easy-to-use auto-increment integers
Serial (or auto-increment) integers make great unique identifiers because they do
not need to be large (i.e. using more memory) to prevent collisions. They are
always unique until they reach their max value, mimicking the behavior of
PostgreSQL's SERIAL
data type. Creating serial values has minimal performance
impact because it relies on simple adding rather than hashing or randomizing.
This crate provides a generator (that is also an iterator) that outputs serial values. By default, any unsigned integer from the standard library can be generated. This is essentially a counter, a simple iterator for integers. This crate is appropriately tiny.
For safety and stability, the generator "saturates" the values instead of overflowing. This guarantees that the output values are unique to that generator (except for the greatest possible value, e.g. u8::MAX or u32::MAX).
no_std
Use a generator to create unique identifiers.
```rust
let mut gen = SerialGenerator::
asserteq!(0, gen.generate()); asserteq!(1, gen.generate()); ```
To support concurrency, simply use a wrapper. You can also use static ref
for
generators that don't have an owner.
```rust fn main() { let usersmutex = Arc::new(Mutex::new(Vec::new())); let usersclone = Arc::clone(&users_mutex);
let handle = thread::spawn(move || {
let alice = User::new("alice@domain.xyz");
let mary = User::new("mary@domain.xyz");
let mut users = users_clone.lock().unwrap();
users.push(alice);
users.push(mary);
});
handle.join().unwrap();
let bob = User::new("bob@domain.xyz");
let fred = User::new("fred@domain.xyz");
let mut users = users_mutex.lock().unwrap();
users.push(bob);
users.push(fred);
assert_eq!(0, users[0].id);
assert_eq!(1, users[1].id);
assert_eq!(2, users[2].id);
assert_eq!(3, users[3].id);
}
lazystatic! {
static ref USERID_GEN: Mutex
struct User { id: u32, email: String, }
impl User { pub fn new(email: &str) -> Self { User { id: USERIDGEN.lock().unwrap().generate(), email: email.to_string(), } } } ```
Submit a patch. If you add a new implementation of Serial, add a submodule to
tests
using the provided functions.