don't
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat(atproto): tid generator

Signed-off-by: tjh <did:plc:65gha4t3avpfpzmvpbwovss7>

+62 -1
+14
crates/atproto/src/did.rs
··· 261 261 } 262 262 } 263 263 264 + impl From<Box<Did>> for std::borrow::Cow<'_, Did> { 265 + #[inline] 266 + fn from(value: Box<Did>) -> Self { 267 + std::borrow::Cow::Owned(value) 268 + } 269 + } 270 + 271 + impl<'a> From<&'a Did> for std::borrow::Cow<'a, Did> { 272 + #[inline] 273 + fn from(value: &'a Did) -> Self { 274 + std::borrow::Cow::Borrowed(value) 275 + } 276 + } 277 + 264 278 #[cfg(feature = "serde")] 265 279 mod serde_impl { 266 280 use super::Did;
+48 -1
crates/atproto/src/tid.rs
··· 1 1 use core::fmt; 2 + use std::sync::Mutex; 2 3 3 4 static LOOKUP: [u8; 32] = [ 4 5 b'2', b'3', b'4', b'5', b'6', b'7', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', ··· 13 12 /// Timestamp Identifier 14 13 /// 15 14 /// See: <https://atproto.com/specs/tid> 16 - #[derive(Default, Hash, PartialEq, Eq, PartialOrd, Ord)] 15 + #[derive(Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] 17 16 pub struct Tid(u64); 18 17 19 18 impl Tid { ··· 300 299 } 301 300 302 301 Ok(Tid(value)) 302 + } 303 + 304 + pub struct TidClock { 305 + ts: Mutex<u64>, 306 + id: u16, 307 + } 308 + 309 + impl TidClock { 310 + /// Create a new TID clock with the specified ID. 311 + pub const fn with_id(clock_id: u16) -> Self { 312 + if clock_id > Tid::MAX_CLOCK_ID { 313 + panic!("TID clock ID must be in the range 0..=1023"); 314 + } 315 + 316 + Self { 317 + id: clock_id, 318 + ts: Mutex::new(0), 319 + } 320 + } 321 + 322 + /// Generate a new TID from [`SystemTime::now()`]. 323 + /// 324 + /// # Panics 325 + /// 326 + /// Panics if the current date is later than 2255-06-05 23:47:34.740991 +00:00:00. 327 + /// 328 + pub fn next(&self) -> Tid { 329 + use std::time::SystemTime; 330 + 331 + // This will panic after 2554-07-21 23:34:33.709551615 +00:00:00, but 332 + // Tid::new() will start panicking around 200 years before. 333 + let mut new_ts: u64 = SystemTime::now() 334 + .duration_since(SystemTime::UNIX_EPOCH) 335 + .expect("SystemTime before UNIX epoch") 336 + .as_micros() 337 + .try_into() 338 + .unwrap(); 339 + 340 + let mut last = self.ts.lock().unwrap(); 341 + if *last >= new_ts { 342 + new_ts = *last + 1; 343 + } 344 + 345 + *last = new_ts; 346 + Tid::new(new_ts, self.id) 347 + } 303 348 } 304 349 305 350 #[cfg(test)]