pathfinding/id/
id_generator.rs1use std::sync::Arc;
2use tokio::sync::RwLock;
3use chrono::{Utc};
4use lazy_static::lazy_static;
5
6use crate::id::instance_id::{InstanceIdStruct, InstanceIdType};
7
8lazy_static! {
9 static ref ID_GENERATOR: Arc<RwLock<IdGenerator>> = IdGenerator::new();
10}
11
12pub struct IdGenerator {
13 last_instance_id_time: i64,
14 instance_id_value: u64
15}
16
17pub const MAX_VALUE_U64: u64 = u64::MAX;
18
19impl IdGenerator {
20
21 pub fn get_instance() -> Arc<RwLock<IdGenerator>> {
22 ID_GENERATOR.clone()
23 }
24
25 fn new() -> Arc<RwLock<Self>> {
26 Arc::new(RwLock::new(IdGenerator{last_instance_id_time:Utc::now().timestamp(), instance_id_value:0}))
27 }
28
29
30 pub fn generate_instance_id(&mut self) -> InstanceIdType {
31 let time = Utc::now().timestamp();
32 if time > self.last_instance_id_time {
33 self.last_instance_id_time = time;
34 self.instance_id_value = 0;
35 }
36 else {
37 self.instance_id_value += 1;
38 if self.instance_id_value > MAX_VALUE_U64 - 1
39 {
40 self.last_instance_id_time = self.last_instance_id_time + 1; self.instance_id_value = 0;
42
43 println!("instance id count per sec overflow: {} {}", time, self.last_instance_id_time);
44 }
45 }
46
47 InstanceIdStruct::new_from_more(self.last_instance_id_time, self.instance_id_value).into()
48 }
49}