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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
use std::{
cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd},
fmt,
hash::{Hash, Hasher},
marker::PhantomData,
str::FromStr,
};
use arrayvec::ArrayString;
use serde::{Deserialize, Serialize};
use stdweb::{Reference, UnsafeTypedArray};
use crate::{
objects::{HasId, SizedRoomObject},
traits::{TryFrom, TryInto},
ConversionError,
};
mod errors;
mod raw;
pub use errors::*;
pub use raw::*;
/// Represents an Object ID and a type that the ID points to.
///
/// 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 of 12 bytes.
///
/// This object ID is typed, but not strictly. It's completely safe to create an
/// ObjectId with an incorrect type, and all operations which use the type will
/// double-check at runtime.
///
/// With that said, using this can provide nice type inference, and should have
/// few disadvantages to the lower-level alternative, [`RawObjectId`].
///
/// # Conversion
///
/// Use `into` to convert between `ObjectId<T>` and [`RawObjectId`], and
/// [`ObjectId::into_type`] to change the type this `ObjectId` points to freely.
///
/// # Ordering
///
/// To facilitate use as a key in a [`BTreeMap`] or other similar data
/// structures, `ObjectId` implements [`PartialOrd`] and [`Ord`].
///
/// `ObjectId`'s are ordered by the corresponding order of their underlying
/// byte values. This agrees with:
///
/// - lexicographical ordering of the object id strings
/// - JavaScript's ordering of object id strings
/// - ordering of [`RawObjectId`]s
///
/// **Note:** when running on the official screeps server, or on a private
/// server backed by a MongoDB database, this ordering roughly corresponds to
/// creation order. The first four bytes of a MongoDB-created `ObjectId` [are
/// seconds since the epoch when the id was created][1], so up to a second
/// accuracy, these ids will be sorted by object creation time.
///
/// [`BTreeMap`]: std::collections::BTreeMap
/// [1]: https://docs.mongodb.com/manual/reference/method/ObjectId/
// Copy, Clone, Debug, PartialEq, Eq, Hash, PartialEq, Eq implemented manually below
#[derive(Serialize, Deserialize)]
#[serde(transparent, bound = "")]
pub struct ObjectId<T> {
raw: RawObjectId,
#[serde(skip)]
phantom: PhantomData<T>,
}
// traits implemented manually so they don't depend on `T` implementing them.
impl<T> Copy for ObjectId<T> {}
impl<T> Clone for ObjectId<T> {
fn clone(&self) -> ObjectId<T> {
ObjectId {
raw: self.raw.clone(),
phantom: PhantomData,
}
}
}
impl<T> fmt::Debug for ObjectId<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.raw.fmt(f)
}
}
impl<T> PartialEq for ObjectId<T> {
fn eq(&self, o: &ObjectId<T>) -> bool {
self.raw.eq(&o.raw)
}
}
impl<T> Eq for ObjectId<T> {}
impl<T> Hash for ObjectId<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.raw.hash(state)
}
}
impl<T> PartialOrd<ObjectId<T>> for ObjectId<T> {
#[inline]
fn partial_cmp(&self, other: &ObjectId<T>) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for ObjectId<T> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.raw.cmp(&other.raw)
}
}
impl<T> FromStr for ObjectId<T> {
type Err = RawObjectIdParseError;
fn from_str(s: &str) -> Result<Self, RawObjectIdParseError> {
let raw: RawObjectId = s.parse()?;
Ok(raw.into())
}
}
impl<T> TryFrom<u128> for ObjectId<T> {
type Error = RawObjectIdParseError;
fn try_from(val: u128) -> Result<Self, RawObjectIdParseError> {
let raw: RawObjectId = val.try_into()?;
Ok(raw.into())
}
}
impl<T> fmt::Display for ObjectId<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.raw.fmt(f)
}
}
impl<T> ObjectId<T> {
/// Changes the type this [`ObjectId`] points to, unchecked.
///
/// This will allow changing to any type - `ObjectId` makes no guarantees
/// about its ID matching the type of any object in the game that it
/// actually points to.
pub fn into_type<U>(self) -> ObjectId<U> {
RawObjectId::from(self).into()
}
/// 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.
///
/// See also [`RawObjectId::from_packed`].
pub fn from_packed(packed: [u32; 3]) -> Self {
RawObjectId::from_packed(packed).into()
}
/// Creates an object ID from a packed representation stored in JavaScript.
///
/// The input must be a reference to a length-3 array of integers.
///
/// Recommended to be used with the `object_id_to_packed` JavaScript utility
/// function, which takes in a string and returns the array of three
/// integers that this function expects.
///
/// # Example
///
/// ```no_run
/// use screeps::{prelude::*, traits::TryInto, Creep, ObjectId};
/// use stdweb::js;
///
/// let packed_obj_id = (js! {
/// let creep = _.sample(Game.creeps);
/// return object_id_to_packed(creep.id);
/// })
/// .try_into()
/// .unwrap();
///
/// let parsed: ObjectId<Creep> = ObjectId::from_packed_js_val(packed_obj_id).unwrap();
/// println!("found creep with id {}", parsed);
/// ```
///
/// See also [`RawObjectId::from_packed_js_val`].
pub fn from_packed_js_val(packed_val: Reference) -> Result<Self, ConversionError> {
RawObjectId::from_packed_js_val(packed_val).map(Into::into)
}
/// Converts this object ID to a `u128` number.
///
/// The returned number, when formatted as hex, will produce a string
/// parseable into this object id.
///
/// The returned number will be less than or equal to `2^96 - 1`, as that's
/// the maximum value that `RawObjectId` can hold.
pub fn to_u128(self) -> u128 {
self.raw.to_u128()
}
/// Formats this object ID as a string on the stack.
///
/// This is equivalent to [`ToString::to_string`], but involves no
/// allocation.
///
/// To use the produced string in stdweb, use `&*` to convert it to a string
/// slice.
///
/// This is less efficient than [`ObjectId::unsafe_as_uploaded`], but
/// easier to get right.
///
/// # Example
///
/// ```no_run
/// use screeps::{prelude::*, Creep, ObjectId};
/// use stdweb::js;
///
/// let object_id = screeps::game::creeps::values()[0].id();
///
/// let str_repr = object_id.to_array_string();
///
/// js! {
/// let id = @{&*str_repr};
/// console.log("we have a creep with the id " + id);
/// }
/// ```
///
/// See also [`RawObjectId::to_array_string`].
pub fn to_array_string(&self) -> ArrayString<[u8; 24]> {
self.raw.to_array_string()
}
/// Creates an array accessible from JavaScript which represents part of
/// this object id's packed representation.
///
/// Specifically, the resulting array will contain the first non-zero number
/// in this object id, and all following numbers. This allows for a more
/// efficient `object_id_from_packed` implementation.
///
/// # Safety
///
/// This is highly unsafe.
///
/// This creates an `UnsafeTypedArray` and does not use it in JS, so the
/// restrictions from [`UnsafeTypedArray`] apply. When you call into
/// JavaScript using it, you must "use" it immediately before calling into
/// any Rust code whatsoever.
///
/// There are other safety concerns as well, but all deriving from
/// [`UnsafeTypedArray`]. See [`UnsafeTypedArray`].
///
/// # Example
///
/// ```no_run
/// use screeps::{prelude::*, Creep, ObjectId};
/// use stdweb::js;
///
/// let object_id = screeps::game::creeps::values()[0].id();
///
/// let array_view = unsafe { object_id.unsafe_as_uploaded() };
///
/// js! {
/// let id = object_id_from_packed(@{array_view});
/// console.log("we have a creep with the id " + id);
/// }
/// ```
///
/// See also [`RawObjectId::unsafe_as_uploaded`].
pub unsafe fn unsafe_as_uploaded(&self) -> UnsafeTypedArray<'_, u32> {
self.raw.unsafe_as_uploaded()
}
/// Resolves this object ID into an object.
///
/// This is a shortcut for [`game::get_object_typed(id)`][1]
///
/// # Errors
///
/// Will return an error if this ID's type does not match the object it
/// points to.
///
/// Will return `Ok(None)` if the object no longer exists, or is in a room
/// we don't have vision for.
///
/// [1]: crate::game::get_object_typed
pub fn try_resolve(self) -> Result<Option<T>, ConversionError>
where
T: HasId + SizedRoomObject,
{
crate::game::get_object_typed(self)
}
/// Resolves this ID into an object, panicking on type mismatch.
///
/// This is a shortcut for [`id.try_resolve().expect(...)`][1]
///
/// # Panics
///
/// Will panic if this ID points to an object which is not of type `T`.
///
/// Will return `None` if this object no longer exists, or is in a room we
/// don't have vision for.
///
/// [1]: ObjectId::try_resolve
pub fn resolve(self) -> Option<T>
where
T: HasId + SizedRoomObject,
{
match self.try_resolve() {
Ok(v) => v,
Err(e) => panic!("error resolving id {}: {}", self, e),
}
}
}
impl<T> PartialEq<RawObjectId> for ObjectId<T> {
#[inline]
fn eq(&self, other: &RawObjectId) -> bool {
self.raw == *other
}
}
impl<T> PartialEq<ObjectId<T>> for RawObjectId {
#[inline]
fn eq(&self, other: &ObjectId<T>) -> bool {
*self == other.raw
}
}
impl<T> PartialOrd<RawObjectId> for ObjectId<T> {
#[inline]
fn partial_cmp(&self, other: &RawObjectId) -> Option<Ordering> {
Some(self.raw.cmp(other))
}
}
impl<T> PartialOrd<ObjectId<T>> for RawObjectId {
#[inline]
fn partial_cmp(&self, other: &ObjectId<T>) -> Option<Ordering> {
Some(self.cmp(&other.raw))
}
}
impl<T> From<RawObjectId> for ObjectId<T> {
fn from(raw: RawObjectId) -> Self {
ObjectId {
raw,
phantom: PhantomData,
}
}
}
impl<T> From<ObjectId<T>> for RawObjectId {
fn from(id: ObjectId<T>) -> Self {
id.raw
}
}
impl<T> From<ObjectId<T>> for ArrayString<[u8; 24]> {
fn from(id: ObjectId<T>) -> Self {
id.to_array_string()
}
}
impl<T> From<ObjectId<T>> for String {
fn from(id: ObjectId<T>) -> Self {
id.to_string()
}
}
impl<T> From<ObjectId<T>> for u128 {
fn from(id: ObjectId<T>) -> Self {
id.raw.into()
}
}
impl<T> From<[u32; 3]> for ObjectId<T> {
fn from(packed: [u32; 3]) -> Self {
Self::from_packed(packed)
}
}
impl<T> From<ObjectId<T>> for [u32; 3] {
fn from(id: ObjectId<T>) -> Self {
id.raw.into()
}
}