Fork of daniellemaywood.uk/gleam — Wasm codegen work
958 B
43 lines
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: 2022 The Gleam contributors
3
4use std::sync::{
5 Arc,
6 atomic::{AtomicU64, Ordering},
7};
8
9/// A generator of unique ids. Only one should be used per compilation run to
10/// ensure ids do not get reused.
11#[derive(Debug, Clone, Default)]
12pub struct UniqueIdGenerator {
13 id: Arc<AtomicU64>,
14}
15
16impl UniqueIdGenerator {
17 pub fn new() -> Self {
18 Self::default()
19 }
20
21 pub fn next(&self) -> u64 {
22 self.id.fetch_add(1, Ordering::Relaxed)
23 }
24}
25
26#[test]
27fn id_geneation() {
28 let ids = UniqueIdGenerator::new();
29 let ids2 = ids.clone();
30
31 assert_eq!(ids.next(), 0);
32 assert_eq!(ids.next(), 1);
33 assert_eq!(ids.next(), 2);
34
35 // Cloned ones use the same counter
36 assert_eq!(ids2.next(), 3);
37 assert_eq!(ids2.next(), 4);
38 assert_eq!(ids2.next(), 5);
39
40 // The original is updated
41 assert_eq!(ids.next(), 6);
42 assert_eq!(ids.next(), 7);
43}