working on tick()

This commit is contained in:
cbax 2024-09-25 14:35:32 +00:00
parent f4a9ddf8dc
commit f030cec3d0

View file

@ -1,3 +1,5 @@
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug)]
pub enum Version {
ENHANCED,
@ -62,7 +64,7 @@ impl<T> Icechip<T> {
// the offset will get subtracted from the unix epoch before being used in the Icechip.
pub fn set_epoch_offset(mut self, offset: u64) {
self.epoch = Some(offset);
self.epoch = Some(UNIX_EPOCH - offset);
}
pub fn tick(&self) -> Icechip<T> {
@ -70,7 +72,68 @@ impl<T> Icechip<T> {
- if current timestamp in relation to self does not equal self, return an updated value, else increment the sequence
- if sequence is going to overflow, sleep 1 ms
*/
todo!();
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(o) => {
match self.version {
Version::ENHANCED => {
let curr_ts = match self.epoch {
Some(s) => (o - s).checked_shl(23).unwrap().checked_shr(23).unwrap(),
None => o.checked_shl(23).unwrap().checked_shr(23).unwrap(),
}
if self.timestamp == curr_ts {
if (self.sequence_id + 1) > 1023 {
std::thread::sleep(std::time::Duration::from_millis(1));
return self.tick();
} else {
return Icechip {
version: self.version.clone(),
timestamp: self.timestamp.clone(),
machine_id: self.machine_id.clone(),
sequence_id: self.sequence_id.clone() + 1,
epoch: self.epoch.clone()
}
}
} else {
return Icechip {
version: self.version.clone(),
timestamp: curr_ts.clone(),
machine_id: self.machine_id.clone(),
sequence_id: 0,
epoch: self.epoch.clone()
}
}
},
Version::EXTENDED => {
if self.timestamp == o {
if (self.sequence_id + 1) > u32::MAX {
std::thread::sleep(std::time:Duration::from_millis(1));
return self.tick();
} else {
return Icechip {
version: self.version.clone(),
timestamp: self.timestamp.clone(),
machine_id: self.machine_id.clone(),
sequence_id: self.sequence_id.clone() + 1,
epoch: self.epoch.clone()
}
}
} else {
return Icechip {
version: self.version.clone(),
timestamp: o.clone(),
machine_id: self.machine_id.clone(),
sequence_id: 0,
epoch: self.epoch.clone()
}
}
},
}
},
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(1));
return self.tick();
}
}
}
pub fn with_id(machine_id: u32, version: Version) -> Icechip<T> {