screeps_utils/
object.rs

1use chrono::{DateTime, LocalResult, TimeZone, Utc};
2use screeps::RawObjectId;
3
4/// Get the date and time of an object's creation, according to its
5/// MongoDB-style object ID.
6///
7/// Only valid when the backend server environment is using MongoDB as a
8/// backend, which includes the timestamp an object is created as part of the
9/// ID.
10pub fn creation_datetime(object_id: RawObjectId) -> Option<DateTime<Utc>> {
11    let id_packed: u128 = object_id.into();
12
13    match Utc.timestamp_opt((id_packed >> 96) as i64, 0) {
14        LocalResult::Single(dt) => Some(dt),
15        _ => None,
16    }
17}
18
19#[cfg(test)]
20mod test {
21    use std::str::FromStr;
22
23    use super::*;
24
25    #[test]
26    fn id_to_datetime() {
27        // Creep Worker12129506 is legendary: the oldest known creep on MMO - forever
28        // renewed by Orlet, long may he *pew!*
29        let id = RawObjectId::from_str("5bb64cc4f1ee994d0023982b").unwrap();
30        // The start of the creep's ID, 5bb64cc4, corresponds to a timestamp of
31        // Thu Oct 04 2018 17:24:20 GMT+0000
32        let date = DateTime::parse_from_rfc3339("2018-10-04 17:24:20Z").unwrap();
33        assert_eq!(date, creation_datetime(id).unwrap());
34    }
35}