kcl_lib/execution/
id_generator.rs

1//! A generator for ArtifactIds that can be stable across executions.
2
3use crate::execution::ModuleId;
4
5const NAMESPACE_KCL: uuid::Uuid = uuid::uuid!("8bda3118-75eb-58c7-a866-bef1dcb495e7");
6
7/// A generator for ArtifactIds that can be stable across executions.
8#[derive(Debug, Clone, Default, PartialEq)]
9pub struct IdGenerator {
10    module_id: Option<ModuleId>,
11    next_id: u64,
12}
13
14impl IdGenerator {
15    pub fn new(module_id: Option<ModuleId>) -> Self {
16        Self { module_id, next_id: 0 }
17    }
18
19    pub fn next_uuid(&mut self) -> uuid::Uuid {
20        let next_id = self.next_id;
21
22        let next = format!(
23            "{} {}",
24            self.module_id.map(|id| id.to_string()).unwrap_or("none".to_string()),
25            next_id
26        );
27        let next_uuid = uuid::Uuid::new_v5(&NAMESPACE_KCL, next.as_bytes());
28
29        self.next_id += 1;
30
31        next_uuid
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_id_generator() {
41        let mut generator = IdGenerator::new(Some(ModuleId::default()));
42
43        let uuid1 = generator.next_uuid();
44        let uuid2 = generator.next_uuid();
45
46        assert_ne!(uuid1, uuid2);
47    }
48
49    #[test]
50    // Test that the same generator produces the same UUIDs.
51    fn test_id_generator_stable() {
52        let mut generator = IdGenerator::new(Some(ModuleId::default()));
53
54        let uuid1 = generator.next_uuid();
55        let uuid2 = generator.next_uuid();
56
57        let mut generator = IdGenerator::new(Some(ModuleId::default()));
58
59        let uuid3 = generator.next_uuid();
60        let uuid4 = generator.next_uuid();
61
62        assert_eq!(uuid1, uuid3);
63        assert_eq!(uuid2, uuid4);
64    }
65
66    #[test]
67    // Generate 20 uuids and make sure all are unique.
68    fn test_id_generator_unique() {
69        let mut generator = IdGenerator::new(Some(ModuleId::default()));
70
71        let mut uuids = Vec::new();
72
73        for _ in 0..20 {
74            uuids.push(generator.next_uuid());
75        }
76
77        for i in 0..uuids.len() {
78            for j in i + 1..uuids.len() {
79                assert_ne!(uuids[i], uuids[j]);
80            }
81        }
82    }
83}