Skip to content

Commit

Permalink
Add Tid::from_datetime
Browse files Browse the repository at this point in the history
  • Loading branch information
DrChat committed Feb 1, 2025
1 parent 74e4573 commit 0ca1cce
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions atrium-api/src/types/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,15 +456,23 @@ impl Tid {
///
/// Clock IDs 0-31 can be used as an ad-hoc clock ID if you are not concerned
/// with this parameter.
pub fn now(cid: u32) -> Self {
let now = chrono::Utc::now().timestamp_micros() as u64;
pub fn from_datetime(cid: u32, time: chrono::DateTime<chrono::Utc>) -> Self {
let time = time.timestamp_micros() as u64;

// The TID is laid out as follows:
// 0TTTTTTTTTTTTTTT TTTTTTTTTTTTTTTT TTTTTTTTTTTTTTTT TTTTTTCCCCCCCCCC
let tid = (now << 10) & 0x7FFF_FFFF_FFFF_FC00 | (cid as u64) & 0x3FF;
let tid = (time << 10) & 0x7FFF_FFFF_FFFF_FC00 | (cid as u64) & 0x3FF;
Self(s32_encode(tid))
}

/// Construct a new [Tid] that represents the current time.
///
/// Clock IDs 0-31 can be used as an ad-hoc clock ID if you are not concerned
/// with this parameter.
pub fn now(cid: u32) -> Self {
Self::from_datetime(cid, chrono::Utc::now())
}

/// Returns the TID as a string slice.
pub fn as_str(&self) -> &str {
self.0.as_str()
Expand Down Expand Up @@ -801,6 +809,12 @@ mod tests {
assert_eq!(s32_encode(1), "2222222222223");
}

#[test]
fn tid_construct() {
let tid = Tid::from_datetime(0, chrono::DateTime::from_timestamp(1738430999, 0).unwrap());
assert_eq!(tid.as_str(), "3lh5234mwy222");
}

#[test]
fn valid_tid() {
for valid in ["3jzfcijpj2z2a", "7777777777777", "3zzzzzzzzzzzz"] {
Expand Down

0 comments on commit 0ca1cce

Please sign in to comment.