| 1 |
//! Module containing functionality related to BSON ObjectIds. |
| 2 |
//! For more information, see the documentation for the [`ObjectId`] type. |
| 3 |
|
| 4 |
use std::{ |
| 5 |
error, |
| 6 |
fmt, |
| 7 |
result, |
| 8 |
str::FromStr, |
| 9 |
sync::atomic::{AtomicUsize, Ordering}, |
| 10 |
}; |
| 11 |
|
| 12 |
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] |
| 13 |
use std::{convert::TryInto, time::SystemTime}; |
| 14 |
|
| 15 |
use hex::{self, FromHexError}; |
| 16 |
use once_cell::sync::Lazy; |
| 17 |
use rand::{random, thread_rng, Rng}; |
| 18 |
|
| 19 |
const TIMESTAMP_SIZE: usize = 4; |
| 20 |
const PROCESS_ID_SIZE: usize = 5; |
| 21 |
const COUNTER_SIZE: usize = 3; |
| 22 |
|
| 23 |
const TIMESTAMP_OFFSET: usize = 0; |
| 24 |
const PROCESS_ID_OFFSET: usize = TIMESTAMP_OFFSET + TIMESTAMP_SIZE; |
| 25 |
const COUNTER_OFFSET: usize = PROCESS_ID_OFFSET + PROCESS_ID_SIZE; |
| 26 |
|
| 27 |
const MAX_U24: usize = 0xFF_FFFF; |
| 28 |
|
| 29 |
static OID_COUNTER: Lazy<AtomicUsize> = |
| 30 |
Lazy::new(|| AtomicUsize::new(thread_rng().gen_range(0..=MAX_U24))); |
| 31 |
|
| 32 |
/// Errors that can occur during [`ObjectId`] construction and generation. |
| 33 |
#[derive(Clone, Debug)] |
| 34 |
#[non_exhaustive] |
| 35 |
pub enum Error { |
| 36 |
/// An invalid character was found in the provided hex string. Valid characters are: `0...9`, |
| 37 |
/// `a...f`, or `A...F`. |
| 38 |
#[non_exhaustive] |
| 39 |
InvalidHexStringCharacter { c: char, index: usize, hex: String }, |
| 40 |
|
| 41 |
/// An [`ObjectId`]'s hex string representation must be an exactly 12-byte (24-char) |
| 42 |
/// hexadecimal string. |
| 43 |
#[non_exhaustive] |
| 44 |
InvalidHexStringLength { length: usize, hex: String }, |
| 45 |
} |
| 46 |
|
| 47 |
/// Alias for Result<T, oid::Error>. |
| 48 |
pub type Result<T> = result::Result<T, Error>; |
| 49 |
|
| 50 |
impl fmt::Display for Error { |
| 51 |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 52 |
match self { |
| 53 |
Error::InvalidHexStringCharacter { c, index, hex } => { |
| 54 |
write!( |
| 55 |
fmt, |
| 56 |
"invalid character '{}' was found at index {} in the provided hex string: \ |
| 57 |
\"{}\"", |
| 58 |
c, index, hex |
| 59 |
) |
| 60 |
} |
| 61 |
Error::InvalidHexStringLength { length, hex } => { |
| 62 |
write!( |
| 63 |
fmt, |
| 64 |
"provided hex string representation must be exactly 12 bytes, instead got: \ |
| 65 |
\"{}\", length {}", |
| 66 |
hex, length |
| 67 |
) |
| 68 |
} |
| 69 |
} |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
impl error::Error for Error {} |
| 74 |
|
| 75 |
/// A wrapper around a raw 12-byte ObjectId. |
| 76 |
/// |
| 77 |
/// ## `serde` integration |
| 78 |
/// When serialized to BSON via `serde`, this type produces a BSON ObjectId. In non-BSON formats, it |
| 79 |
/// will serialize to and deserialize from that format's equivalent of the [extended JSON representation](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) of a BSON ObjectId. |
| 80 |
/// |
| 81 |
/// [`ObjectId`]s can be deserialized from hex strings in all formats. |
| 82 |
/// |
| 83 |
/// e.g. |
| 84 |
/// ```rust |
| 85 |
/// use serde::{Serialize, Deserialize}; |
| 86 |
/// use bson::oid::ObjectId; |
| 87 |
/// |
| 88 |
/// #[derive(Serialize, Deserialize)] |
| 89 |
/// struct Foo { |
| 90 |
/// oid: ObjectId, |
| 91 |
/// } |
| 92 |
/// |
| 93 |
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 94 |
/// let f = Foo { oid: ObjectId::new() }; |
| 95 |
/// println!("bson: {}", bson::to_document(&f)?); |
| 96 |
/// println!("json: {}", serde_json::to_string(&f)?); |
| 97 |
/// # Ok(()) |
| 98 |
/// # } |
| 99 |
/// ``` |
| 100 |
/// Produces the following output: |
| 101 |
/// ```text |
| 102 |
/// bson: { "oid": ObjectId("63ceed18f71dda7d8cf21e8e") } |
| 103 |
/// json: {"oid":{"$oid":"63ceed18f71dda7d8cf21e8e"}} |
| 104 |
/// ``` |
| 105 |
/// |
| 106 |
/// ### `serde_helpers` |
| 107 |
/// The `bson` crate provides a number of useful helpers for serializing and deserializing |
| 108 |
/// various types to and from different formats. For example, to serialize an |
| 109 |
/// [`ObjectId`] as a hex string, you can use |
| 110 |
/// [`crate::serde_helpers::serialize_object_id_as_hex_string`]. |
| 111 |
/// Check out the [`crate::serde_helpers`] module documentation for a list of all of the helpers |
| 112 |
/// offered by the crate. |
| 113 |
/// |
| 114 |
/// e.g. |
| 115 |
/// ```rust |
| 116 |
/// use serde::{Serialize, Deserialize}; |
| 117 |
/// use bson::oid::ObjectId; |
| 118 |
/// |
| 119 |
/// #[derive(Serialize, Deserialize)] |
| 120 |
/// struct Foo { |
| 121 |
/// // Serializes as a BSON ObjectId or extJSON in non-BSON formats |
| 122 |
/// oid: ObjectId, |
| 123 |
/// |
| 124 |
/// // Serializes as a hex string in all formats |
| 125 |
/// #[serde(serialize_with = "bson::serde_helpers::serialize_object_id_as_hex_string")] |
| 126 |
/// oid_as_hex: ObjectId, |
| 127 |
/// } |
| 128 |
/// # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { |
| 129 |
/// let f = Foo { oid: ObjectId::new(), oid_as_hex: ObjectId::new() }; |
| 130 |
/// println!("bson: {}", bson::to_document(&f)?); |
| 131 |
/// println!("json: {}", serde_json::to_string(&f)?); |
| 132 |
/// # Ok(()) |
| 133 |
/// # } |
| 134 |
/// ``` |
| 135 |
/// Produces the following output: |
| 136 |
/// ```text |
| 137 |
/// bson: { "oid": ObjectId("63ceeffd37518221cdc6cda2"), "oid_as_hex": "63ceeffd37518221cdc6cda3" } |
| 138 |
/// json: {"oid":{"$oid":"63ceeffd37518221cdc6cda2"},"oid_as_hex":"63ceeffd37518221cdc6cda3"} |
| 139 |
/// ``` |
| 140 |
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)] |
| 141 |
pub struct ObjectId { |
| 142 |
id: [u8; 12], |
| 143 |
} |
| 144 |
|
| 145 |
impl Default for ObjectId { |
| 146 |
fn default() -> Self { |
| 147 |
Self::new() |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
impl FromStr for ObjectId { |
| 152 |
type Err = Error; |
| 153 |
|
| 154 |
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { |
| 155 |
Self::parse_str(s) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
impl From<[u8; 12]> for ObjectId { |
| 160 |
fn from(bytes: [u8; 12]) -> Self { |
| 161 |
Self { id: bytes } |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
impl ObjectId { |
| 166 |
/// Generates a new [`ObjectId`], represented in bytes. |
| 167 |
/// See the [docs](http://www.mongodb.com/docs/manual/reference/object-id/) |
| 168 |
/// for more information. |
| 169 |
pub fn new() -> ObjectId { |
| 170 |
let timestamp = ObjectId::gen_timestamp(); |
| 171 |
let process_id = ObjectId::gen_process_id(); |
| 172 |
let counter = ObjectId::gen_count(); |
| 173 |
|
| 174 |
let mut buf: [u8; 12] = [0; 12]; |
| 175 |
buf[TIMESTAMP_OFFSET..(TIMESTAMP_SIZE + TIMESTAMP_OFFSET)] |
| 176 |
.clone_from_slice(×tamp[..TIMESTAMP_SIZE]); |
| 177 |
buf[PROCESS_ID_OFFSET..(PROCESS_ID_SIZE + PROCESS_ID_OFFSET)] |
| 178 |
.clone_from_slice(&process_id[..PROCESS_ID_SIZE]); |
| 179 |
buf[COUNTER_OFFSET..(COUNTER_SIZE + COUNTER_OFFSET)] |
| 180 |
.clone_from_slice(&counter[..COUNTER_SIZE]); |
| 181 |
|
| 182 |
ObjectId::from_bytes(buf) |
| 183 |
} |
| 184 |
|
| 185 |
/// Constructs a new ObjectId wrapper around the raw byte representation. |
| 186 |
pub const fn from_bytes(bytes: [u8; 12]) -> ObjectId { |
| 187 |
ObjectId { id: bytes } |
| 188 |
} |
| 189 |
|
| 190 |
/// Creates an ObjectID using a 12-byte (24-char) hexadecimal string. |
| 191 |
pub fn parse_str(s: impl AsRef<str>) -> Result<ObjectId> { |
| 192 |
let s = s.as_ref(); |
| 193 |
|
| 194 |
let bytes: Vec<u8> = hex::decode(s.as_bytes()).map_err(|e| match e { |
| 195 |
FromHexError::InvalidHexCharacter { c, index } => Error::InvalidHexStringCharacter { |
| 196 |
c, |
| 197 |
index, |
| 198 |
hex: s.to_string(), |
| 199 |
}, |
| 200 |
FromHexError::InvalidStringLength | FromHexError::OddLength => { |
| 201 |
Error::InvalidHexStringLength { |
| 202 |
length: s.len(), |
| 203 |
hex: s.to_string(), |
| 204 |
} |
| 205 |
} |
| 206 |
})?; |
| 207 |
if bytes.len() != 12 { |
| 208 |
Err(Error::InvalidHexStringLength { |
| 209 |
length: s.len(), |
| 210 |
hex: s.to_string(), |
| 211 |
}) |
| 212 |
} else { |
| 213 |
let mut byte_array: [u8; 12] = [0; 12]; |
| 214 |
byte_array[..].copy_from_slice(&bytes[..]); |
| 215 |
Ok(ObjectId::from_bytes(byte_array)) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// Retrieves the timestamp from an [`ObjectId`]. |
| 220 |
pub fn timestamp(&self) -> crate::DateTime { |
| 221 |
let mut buf = [0; 4]; |
| 222 |
buf.copy_from_slice(&self.id[0..4]); |
| 223 |
let seconds_since_epoch = u32::from_be_bytes(buf); |
| 224 |
|
| 225 |
// This doesn't overflow since u32::MAX * 1000 < i64::MAX |
| 226 |
crate::DateTime::from_millis(seconds_since_epoch as i64 * 1000) |
| 227 |
} |
| 228 |
|
| 229 |
/// Returns the raw byte representation of an ObjectId. |
| 230 |
pub const fn bytes(&self) -> [u8; 12] { |
| 231 |
self.id |
| 232 |
} |
| 233 |
|
| 234 |
/// Convert this [`ObjectId`] to its hex string representation. |
| 235 |
pub fn to_hex(self) -> String { |
| 236 |
hex::encode(self.id) |
| 237 |
} |
| 238 |
|
| 239 |
/// Generates a new timestamp representing the current seconds since epoch. |
| 240 |
/// Represented in Big Endian. |
| 241 |
fn gen_timestamp() -> [u8; 4] { |
| 242 |
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))] |
| 243 |
let timestamp: u32 = (js_sys::Date::now() / 1000.0) as u32; |
| 244 |
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] |
| 245 |
let timestamp: u32 = SystemTime::now() |
| 246 |
.duration_since(SystemTime::UNIX_EPOCH) |
| 247 |
.expect("system clock is before 1970") |
| 248 |
.as_secs() |
| 249 |
.try_into() |
| 250 |
.unwrap(); // will succeed until 2106 since timestamp is unsigned |
| 251 |
timestamp.to_be_bytes() |
| 252 |
} |
| 253 |
|
| 254 |
/// Generate a random 5-byte array. |
| 255 |
fn gen_process_id() -> [u8; 5] { |
| 256 |
static BUF: Lazy<[u8; 5]> = Lazy::new(random); |
| 257 |
|
| 258 |
*BUF |
| 259 |
} |
| 260 |
|
| 261 |
/// Gets an incremental 3-byte count. |
| 262 |
/// Represented in Big Endian. |
| 263 |
fn gen_count() -> [u8; 3] { |
| 264 |
let u_counter = OID_COUNTER.fetch_add(1, Ordering::SeqCst); |
| 265 |
|
| 266 |
// Mod result instead of OID_COUNTER to prevent threading issues. |
| 267 |
let u = u_counter % (MAX_U24 + 1); |
| 268 |
|
| 269 |
// Convert usize to writable u64, then extract the first three bytes. |
| 270 |
let u_int = u as u64; |
| 271 |
|
| 272 |
let buf = u_int.to_be_bytes(); |
| 273 |
let buf_u24: [u8; 3] = [buf[5], buf[6], buf[7]]; |
| 274 |
buf_u24 |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
impl fmt::Display for ObjectId { |
| 279 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 280 |
f.write_str(&self.to_hex()) |
| 281 |
} |
| 282 |
} |
| 283 |
|
| 284 |
impl fmt::Debug for ObjectId { |
| 285 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 286 |
f.debug_tuple("ObjectId").field(&self.to_hex()).finish() |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
#[cfg(test)] |
| 291 |
use crate::tests::LOCK; |
| 292 |
|
| 293 |
#[test] |
| 294 |
fn count_generated_is_big_endian() { |
| 295 |
let _guard = LOCK.run_exclusively(); |
| 296 |
let start = 1_122_866; |
| 297 |
OID_COUNTER.store(start, Ordering::SeqCst); |
| 298 |
|
| 299 |
// Test count generates correct value 1122866 |
| 300 |
let count_bytes = ObjectId::gen_count(); |
| 301 |
|
| 302 |
let mut buf: [u8; 4] = [0; 4]; |
| 303 |
buf[1..=COUNTER_SIZE].clone_from_slice(&count_bytes[..COUNTER_SIZE]); |
| 304 |
|
| 305 |
let count = u32::from_be_bytes(buf); |
| 306 |
assert_eq!(start as u32, count); |
| 307 |
|
| 308 |
// Test OID formats count correctly as big endian |
| 309 |
let oid = ObjectId::new(); |
| 310 |
|
| 311 |
assert_eq!(0x11u8, oid.bytes()[COUNTER_OFFSET]); |
| 312 |
assert_eq!(0x22u8, oid.bytes()[COUNTER_OFFSET + 1]); |
| 313 |
assert_eq!(0x33u8, oid.bytes()[COUNTER_OFFSET + 2]); |
| 314 |
} |
| 315 |
|
| 316 |
#[test] |
| 317 |
fn test_counter_overflow_u24_max() { |
| 318 |
let _guard = LOCK.run_exclusively(); |
| 319 |
let start = MAX_U24; |
| 320 |
OID_COUNTER.store(start, Ordering::SeqCst); |
| 321 |
let oid = ObjectId::new(); |
| 322 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET]); |
| 323 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET + 1]); |
| 324 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET + 2]); |
| 325 |
// Test counter overflows to 0 when set to MAX_24 + 1 |
| 326 |
let oid_new = ObjectId::new(); |
| 327 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET]); |
| 328 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET + 1]); |
| 329 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET + 2]); |
| 330 |
} |
| 331 |
|
| 332 |
#[test] |
| 333 |
fn test_counter_overflow_usize_max() { |
| 334 |
let _guard = LOCK.run_exclusively(); |
| 335 |
let start = usize::max_value(); |
| 336 |
OID_COUNTER.store(start, Ordering::SeqCst); |
| 337 |
// Test counter overflows to u24_max when set to usize_max |
| 338 |
let oid = ObjectId::new(); |
| 339 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET]); |
| 340 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET + 1]); |
| 341 |
assert_eq!(0xFFu8, oid.bytes()[COUNTER_OFFSET + 2]); |
| 342 |
// Test counter overflows to 0 when set to usize_max + 1 |
| 343 |
let oid_new = ObjectId::new(); |
| 344 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET]); |
| 345 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET + 1]); |
| 346 |
assert_eq!(0x00u8, oid_new.bytes()[COUNTER_OFFSET + 2]); |
| 347 |
} |
| 348 |
|
| 349 |
#[cfg(test)] |
| 350 |
mod test { |
| 351 |
use time::macros::datetime; |
| 352 |
|
| 353 |
#[test] |
| 354 |
fn test_display() { |
| 355 |
let id = super::ObjectId::parse_str("53e37d08776f724e42000000").unwrap(); |
| 356 |
|
| 357 |
assert_eq!(format!("{}", id), "53e37d08776f724e42000000") |
| 358 |
} |
| 359 |
|
| 360 |
#[test] |
| 361 |
fn test_debug() { |
| 362 |
let id = super::ObjectId::parse_str("53e37d08776f724e42000000").unwrap(); |
| 363 |
|
| 364 |
assert_eq!( |
| 365 |
format!("{:?}", id), |
| 366 |
"ObjectId(\"53e37d08776f724e42000000\")" |
| 367 |
); |
| 368 |
assert_eq!( |
| 369 |
format!("{:#?}", id), |
| 370 |
"ObjectId(\n \"53e37d08776f724e42000000\",\n)" |
| 371 |
); |
| 372 |
} |
| 373 |
|
| 374 |
#[test] |
| 375 |
fn test_timestamp() { |
| 376 |
let id = super::ObjectId::parse_str("000000000000000000000000").unwrap(); |
| 377 |
// "Jan 1st, 1970 00:00:00 UTC" |
| 378 |
assert_eq!(datetime!(1970-01-01 0:00 UTC), id.timestamp().to_time_0_3()); |
| 379 |
|
| 380 |
let id = super::ObjectId::parse_str("7FFFFFFF0000000000000000").unwrap(); |
| 381 |
// "Jan 19th, 2038 03:14:07 UTC" |
| 382 |
assert_eq!( |
| 383 |
datetime!(2038-01-19 3:14:07 UTC), |
| 384 |
id.timestamp().to_time_0_3() |
| 385 |
); |
| 386 |
|
| 387 |
let id = super::ObjectId::parse_str("800000000000000000000000").unwrap(); |
| 388 |
// "Jan 19th, 2038 03:14:08 UTC" |
| 389 |
assert_eq!( |
| 390 |
datetime!(2038-01-19 3:14:08 UTC), |
| 391 |
id.timestamp().to_time_0_3() |
| 392 |
); |
| 393 |
|
| 394 |
let id = super::ObjectId::parse_str("FFFFFFFF0000000000000000").unwrap(); |
| 395 |
// "Feb 7th, 2106 06:28:15 UTC" |
| 396 |
assert_eq!( |
| 397 |
datetime!(2106-02-07 6:28:15 UTC), |
| 398 |
id.timestamp().to_time_0_3() |
| 399 |
); |
| 400 |
} |
| 401 |
} |