1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use std::{fmt, fmt::Write, str::FromStr};

use arrayvec::ArrayString;
use js_sys::JsString;
use serde::{
    de::{Error, Visitor},
    Deserialize, Serialize,
};

use super::errors::RawObjectIdParseError;

const MAX_PACKED_VAL: u128 = (1 << (32 * 3)) - 1;

/// Represents an Object ID using a packed 12-byte representation
///
/// Each object id in screeps is represented by a Mongo GUID, which,
/// while not guaranteed, is unlikely to change. This takes advantage of that by
/// storing a packed representation.
///
/// # Ordering
///
/// To facilitate use as a key in a [`BTreeMap`] or other similar data
/// structures, `ObjectId` implements [`PartialOrd`] and [`Ord`].
///
/// `RawObjectId`'s are ordered by the corresponding order of their underlying
/// byte values. See [`ObjectId`] documentation for more information.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [`Ord`]: std::cmp::Ord
/// [`PartialOrd`]: std::cmp::PartialOrd
/// [`ObjectId`]: super::ObjectId
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RawObjectId {
    packed: u128,
}

impl fmt::Debug for RawObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawObjectId")
            .field("packed", &self.packed)
            .field("real", &self.to_string())
            .finish()
    }
}

impl fmt::Display for RawObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:0width$x}",
            self.packed >> 32,
            width = (self.packed as u32) as usize
        )
    }
}

impl Serialize for RawObjectId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if serializer.is_human_readable() {
            serializer.collect_str(&self.to_array_string())
        } else {
            serializer.serialize_bytes(&self.packed.to_be_bytes())
        }
    }
}

struct RawObjectIdVisitor;

impl<'de> Visitor<'de> for RawObjectIdVisitor {
    type Value = RawObjectId;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a string or bytes representing an object id")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        RawObjectId::from_str(v).map_err(|e| E::custom(format!("Could not parse object id: {e}")))
    }

    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
    where
        E: Error,
    {
        v.try_into()
            .map(u128::from_be_bytes)
            .map(RawObjectId::from_packed)
            .map_err(|e| E::custom(format!("Could not parse object id: {e}")))
    }
}

impl<'de> Deserialize<'de> for RawObjectId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            deserializer.deserialize_str(RawObjectIdVisitor)
        } else {
            deserializer.deserialize_bytes(RawObjectIdVisitor)
        }
    }
}

impl FromStr for RawObjectId {
    type Err = RawObjectIdParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // get the actual integer value of the id, which we'll store in the most
        // significant 96 bits of the u128
        let u128_id = u128::from_str_radix(s, 16)?;
        // and the length, which we know can't be greater than 24 without going over
        // MAX_PACKED_VAL
        let pad_length = s.len() as u128;

        if u128_id > MAX_PACKED_VAL || pad_length > 24 {
            return Err(RawObjectIdParseError::value_too_large(u128_id));
        }

        Ok(Self::from(u128_id << 32 | pad_length))
    }
}

impl TryFrom<JsString> for RawObjectId {
    type Error = RawObjectIdParseError;

    fn try_from(js_id: JsString) -> Result<Self, Self::Error> {
        let id: String = js_id.into();
        RawObjectId::from_str(&id)
    }
}

impl RawObjectId {
    /// Creates an object ID from its packed representation.
    ///
    /// The input to this function is the bytes representing the up-to-24 hex
    /// digits in the object id.
    pub const fn from_packed(packed: u128) -> Self {
        RawObjectId { packed }
    }

    /// Formats this object ID as a string on the stack.
    ///
    /// This is equivalent to [`ToString::to_string`], but involves no
    /// allocation.
    pub fn to_array_string(&self) -> ArrayString<24> {
        let mut res = ArrayString::new();
        write!(res, "{self}").expect("expected formatting into a fixed-sized buffer to succeed");
        res
    }
}

impl From<RawObjectId> for ArrayString<24> {
    fn from(id: RawObjectId) -> Self {
        id.to_array_string()
    }
}

impl From<RawObjectId> for String {
    fn from(id: RawObjectId) -> Self {
        id.to_string()
    }
}

impl From<RawObjectId> for u128 {
    fn from(id: RawObjectId) -> Self {
        id.packed
    }
}

impl From<u128> for RawObjectId {
    fn from(packed: u128) -> Self {
        Self::from_packed(packed)
    }
}

#[cfg(test)]
mod test {
    use super::RawObjectId;

    const TEST_IDS: &[&str] = &[
        "0",
        "1",
        // max allowed ID
        "ffffffffffffffffffffffff",
        // 24 char, leading 0 (#278)
        "06aebab343040c9baaa22322",
        "000000000000000000000001",
        "100000000000000000000000",
        // potential bad u128 from float?
        "5bbcab1d9099fc012e632dbc",
        "5bbcab1d9099fc012e632dbd",
        "10000000000000000",
        "1000000000000000",
        "bc03381d32f6790",
        // 15 char, leading 0 (#244)
        "0df4aea318bd552",
        "000000000000f00",
        "100000000",
        "10000000",
    ];

    #[test]
    fn rust_display_rust_fromstr_roundtrip() {
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            assert_eq!(&*parsed.to_string(), *id);
        }
    }

    #[test]
    fn rust_to_array_string_rust_fromstr_roundtrip() {
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            assert_eq!(&*parsed.to_array_string(), *id);
        }
    }

    #[test]
    fn rust_to_u128_from_u128_roundtrip() {
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            let int = u128::from(parsed);
            let reparsed: RawObjectId = int.into();
            assert_eq!(parsed, reparsed);
            assert_eq!(reparsed.to_string(), *id);
        }
    }

    #[test]
    fn rust_to_serde_json_from_serde_json_roundtrip() {
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            let serialized = serde_json::to_string(&parsed).unwrap();
            let reparsed: RawObjectId = serde_json::from_str(&serialized).unwrap();
            assert_eq!(parsed, reparsed);
            assert_eq!(reparsed.to_string(), *id);
        }
    }

    #[test]
    fn rust_vec_to_serde_json_from_serde_json_roundtrip() {
        let mut ids_parsed = vec![];
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            ids_parsed.push(parsed);
        }
        let serialized = serde_json::to_string(&ids_parsed).unwrap();
        let ids_reparsed: Vec<RawObjectId> = serde_json::from_str(&serialized).unwrap();
        assert_eq!(ids_parsed, ids_reparsed);
    }

    #[test]
    fn rust_to_serde_bincode_from_serde_bincode_roundtrip() {
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            let serialized = bincode::serialize(&parsed).unwrap();
            let reparsed: RawObjectId = bincode::deserialize(&serialized).unwrap();
            assert_eq!(parsed, reparsed);
            assert_eq!(reparsed.to_string(), *id);
        }
    }

    #[test]
    fn rust_vec_to_serde_bincode_from_serde_bincode_roundtrip() {
        let mut ids_parsed = vec![];
        for id in TEST_IDS {
            let parsed: RawObjectId = id.parse().unwrap();
            ids_parsed.push(parsed);
        }
        let serialized = bincode::serialize(&ids_parsed).unwrap();
        let ids_reparsed: Vec<RawObjectId> = bincode::deserialize(&serialized).unwrap();
        assert_eq!(ids_parsed, ids_reparsed);
    }

    const INVALID_IDS: &[&str] = &[
        // empty string
        "",
        // negative number
        "-1",
        "-0",
        // longer than 24 characters
        "1000000000000000000000000",
        // valid number but padded beyond what we can store in 96 bits
        "000000000000000000000000f",
        // u128::MAX
        "340282366920938463463374607431768211455",
        // even longer
        "000000000000000000000000000000000000000999000340282366920938463463374607431768211455",
        // bad characters
        "g",
        "💣",
        "\n",
    ];

    #[test]
    fn invalid_values_do_not_parse() {
        for id in INVALID_IDS {
            let res: Result<RawObjectId, _> = id.parse();
            assert!(res.is_err());
        }
    }
}