Skip to content

Commit 0ca1cce

Browse files
committed
Add Tid::from_datetime
1 parent 74e4573 commit 0ca1cce

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

atrium-api/src/types/string.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -456,15 +456,23 @@ impl Tid {
456456
///
457457
/// Clock IDs 0-31 can be used as an ad-hoc clock ID if you are not concerned
458458
/// with this parameter.
459-
pub fn now(cid: u32) -> Self {
460-
let now = chrono::Utc::now().timestamp_micros() as u64;
459+
pub fn from_datetime(cid: u32, time: chrono::DateTime<chrono::Utc>) -> Self {
460+
let time = time.timestamp_micros() as u64;
461461

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

468+
/// Construct a new [Tid] that represents the current time.
469+
///
470+
/// Clock IDs 0-31 can be used as an ad-hoc clock ID if you are not concerned
471+
/// with this parameter.
472+
pub fn now(cid: u32) -> Self {
473+
Self::from_datetime(cid, chrono::Utc::now())
474+
}
475+
468476
/// Returns the TID as a string slice.
469477
pub fn as_str(&self) -> &str {
470478
self.0.as_str()
@@ -801,6 +809,12 @@ mod tests {
801809
assert_eq!(s32_encode(1), "2222222222223");
802810
}
803811

812+
#[test]
813+
fn tid_construct() {
814+
let tid = Tid::from_datetime(0, chrono::DateTime::from_timestamp(1738430999, 0).unwrap());
815+
assert_eq!(tid.as_str(), "3lh5234mwy222");
816+
}
817+
804818
#[test]
805819
fn valid_tid() {
806820
for valid in ["3jzfcijpj2z2a", "7777777777777", "3zzzzzzzzzzzz"] {

0 commit comments

Comments
 (0)