| 1 |
//! UUID support for BSON. |
| 2 |
//! |
| 3 |
//! ## The [`crate::Uuid`] type |
| 4 |
//! |
| 5 |
//! The BSON format supports UUIDs via the "binary" type with the UUID subtype (4). |
| 6 |
//! To facilitate working with these UUID-subtyped binary values, this crate provides a |
| 7 |
//! [`crate::Uuid`] type, whose `serde` implementation automatically serializes to and deserializes |
| 8 |
//! from binary values with subtype 4. |
| 9 |
//! |
| 10 |
//! The popular [`uuid`](https://docs.rs/uuid) crate also provides a |
| 11 |
//! [UUID type](https://docs.rs/uuid/latest/uuid/struct.Uuid.html), |
| 12 |
//! though its `serde` implementation does not produce or parse subtype 4 |
| 13 |
//! binary values. Instead, when serialized with `bson::to_bson`, it produces as a string, and when |
| 14 |
//! serialized with `bson::to_vec`, it produces a binary value with subtype _0_ rather than 4. |
| 15 |
//! Because of this, it is highly recommended to use the [`crate::Uuid`] type when working with BSON |
| 16 |
//! instead of the `uuid` crate's [`Uuid`], since [`crate::Uuid`] correctly produces subtype 4 |
| 17 |
//! binary values via either serialization function. |
| 18 |
//! |
| 19 |
//! e.g. |
| 20 |
//! |
| 21 |
//! ``` rust |
| 22 |
//! # #[cfg(feature = "uuid-1")] |
| 23 |
//! # { |
| 24 |
//! # use uuid as uuid; |
| 25 |
//! use serde::{Serialize, Deserialize}; |
| 26 |
//! use bson::doc; |
| 27 |
//! |
| 28 |
//! #[derive(Serialize, Deserialize)] |
| 29 |
//! struct Foo { |
| 30 |
//! /// serializes as a String or subtype 0 BSON binary, depending |
| 31 |
//! /// on whether `bson::to_bson` or `bson::to_vec` is used. |
| 32 |
//! uuid: uuid::Uuid, |
| 33 |
//! |
| 34 |
//! /// serializes as a BSON binary with subtype 4 when either is used. |
| 35 |
//! bson_uuid: bson::Uuid, |
| 36 |
//! |
| 37 |
//! /// serializes as a BSON binary with subtype 4 when either is used. |
| 38 |
//! /// this requires the "uuid-1" feature flag |
| 39 |
//! #[serde(with = "bson::serde_helpers::uuid_1_as_binary")] |
| 40 |
//! uuid_as_bson: uuid::Uuid, |
| 41 |
//! } |
| 42 |
//! # }; |
| 43 |
//! ``` |
| 44 |
//! |
| 45 |
//! ## The `uuid-1` feature flag |
| 46 |
//! |
| 47 |
//! To facilitate the conversion between [`crate::Uuid`] values and the `uuid` crate's [`Uuid`] |
| 48 |
//! values, the `uuid-1` feature flag can be enabled. This flag exposes a number of convenient |
| 49 |
//! conversions, including the `crate::Uuid::to_uuid_1` method and the `From<uuid::Uuid>` |
| 50 |
//! implementation for [`Bson`], which allows the `uuid` crate's [`Uuid`] values to be used in the |
| 51 |
//! `doc!` and `bson!` macros. |
| 52 |
//! |
| 53 |
//! ``` |
| 54 |
//! # #[cfg(feature = "uuid-1")] |
| 55 |
//! # { |
| 56 |
//! # use uuid as uuid; |
| 57 |
//! use bson::doc; |
| 58 |
//! |
| 59 |
//! // this automatic conversion does not require any feature flags |
| 60 |
//! let query = doc! { |
| 61 |
//! "uuid": bson::Uuid::new(), |
| 62 |
//! }; |
| 63 |
//! |
| 64 |
//! // but this automatic conversion requires the "uuid-1" feature flag |
| 65 |
//! let query = doc! { |
| 66 |
//! "uuid": uuid::Uuid::new_v4(), |
| 67 |
//! }; |
| 68 |
//! |
| 69 |
//! // this also requires the "uuid-1" feature flag. |
| 70 |
//! let uuid = bson::Uuid::new().to_uuid_1(); |
| 71 |
//! # }; |
| 72 |
//! ``` |
| 73 |
//! |
| 74 |
//! For backwards compatibility, a `uuid-0_8` feature flag can be enabled, which provides the same |
| 75 |
//! API for interoperation with version 0.8 of the `uuid` crate. |
| 76 |
//! |
| 77 |
//! ## The `serde_with-3` feature flag |
| 78 |
//! |
| 79 |
//! The `serde_with-3` feature can be enabled to support more ergonomic serde attributes for |
| 80 |
//! (de)serializing [`uuid::Uuid`] from/to BSON via the [`serde_with`](https://docs.rs/serde_with/1.11.0/serde_with/) |
| 81 |
//! crate. The main benefit of this compared to the regular `serde_helpers` is that `serde_with-3` |
| 82 |
//! can handle nested [`uuid::Uuid`] values (e.g. in [`Option`]), whereas the former only works on |
| 83 |
//! fields that are exactly [`uuid::Uuid`]. |
| 84 |
//! ``` |
| 85 |
//! # #[cfg(all(feature = "uuid-1", feature = "serde_with-3"))] |
| 86 |
//! # { |
| 87 |
//! # use uuid as uuid; |
| 88 |
//! use serde::{Deserialize, Serialize}; |
| 89 |
//! use bson::doc; |
| 90 |
//! |
| 91 |
//! #[serde_with_3::serde_as] |
| 92 |
//! #[derive(Deserialize, Serialize, PartialEq, Debug)] |
| 93 |
//! struct Foo { |
| 94 |
//! /// Serializes as a BSON binary rather than using [`uuid::Uuid`]'s serialization |
| 95 |
//! #[serde_as(as = "Option<bson::Uuid>")] |
| 96 |
//! as_bson: Option<uuid::Uuid>, |
| 97 |
//! } |
| 98 |
//! |
| 99 |
//! let foo = Foo { |
| 100 |
//! as_bson: Some(uuid::Uuid::new_v4()), |
| 101 |
//! }; |
| 102 |
//! |
| 103 |
//! let expected = doc! { |
| 104 |
//! "as_bson": bson::Uuid::from(foo.as_bson.unwrap()), |
| 105 |
//! }; |
| 106 |
//! |
| 107 |
//! assert_eq!(bson::to_document(&foo)?, expected); |
| 108 |
//! # } |
| 109 |
//! # Ok::<(), Box<dyn std::error::Error>>(()) |
| 110 |
//! ``` |
| 111 |
//! |
| 112 |
//! ## Using [`crate::Uuid`] with non-BSON formats |
| 113 |
//! |
| 114 |
//! [`crate::Uuid`]'s `serde` implementation is the same as [`uuid::Uuid`]'s |
| 115 |
//! for non-BSON formats such as JSON: |
| 116 |
//! |
| 117 |
//! ``` rust |
| 118 |
//! # #[cfg(feature = "uuid-1")] |
| 119 |
//! # { |
| 120 |
//! # use uuid as uuid; |
| 121 |
//! # use serde::{Serialize, Deserialize}; |
| 122 |
//! # #[derive(Serialize, Deserialize)] |
| 123 |
//! # struct Foo { |
| 124 |
//! # uuid: uuid::Uuid, |
| 125 |
//! # bson_uuid: bson::Uuid, |
| 126 |
//! # } |
| 127 |
//! use serde_json::json; |
| 128 |
//! |
| 129 |
//! let uuid = uuid::Uuid::new_v4(); |
| 130 |
//! let bson_uuid: bson::Uuid = uuid.into(); |
| 131 |
//! let foo = Foo { uuid, bson_uuid, }; |
| 132 |
//! |
| 133 |
//! let json = serde_json::to_value(&foo)?; |
| 134 |
//! assert_eq!(json, json!({ "uuid": uuid.to_string(), "bson_uuid": uuid.to_string() })); |
| 135 |
//! # } |
| 136 |
//! # Ok::<(), Box::<dyn std::error::Error>>(()) |
| 137 |
//! ``` |
| 138 |
#[cfg(test)] |
| 139 |
mod test; |
| 140 |
|
| 141 |
use std::{ |
| 142 |
fmt::{self, Display}, |
| 143 |
str::FromStr, |
| 144 |
}; |
| 145 |
|
| 146 |
use serde::{Deserialize, Serialize}; |
| 147 |
|
| 148 |
use crate::{de::BsonVisitor, spec::BinarySubtype, Binary, Bson}; |
| 149 |
|
| 150 |
/// Special type name used in the [`Uuid`] serialization implementation to indicate a BSON |
| 151 |
/// UUID is being serialized or deserialized. The BSON serializers/deserializers will handle this |
| 152 |
/// name specially, but other serializers/deserializers will just ignore it and use [`uuid::Uuid`]'s |
| 153 |
/// serde integration. |
| 154 |
pub(crate) const UUID_NEWTYPE_NAME: &str = "$__bson_private_uuid"; |
| 155 |
|
| 156 |
/// A struct modeling a BSON UUID value (i.e. a Binary value with subtype 4). |
| 157 |
/// |
| 158 |
/// This type should be used instead of [`uuid::Uuid`](https://docs.rs/uuid/latest/uuid/struct.Uuid.html) |
| 159 |
/// when serializing to or deserializing from BSON, since |
| 160 |
/// [`uuid::Uuid`](https://docs.rs/uuid/latest/uuid/struct.Uuid.html)'s `serde` implementation doesn't |
| 161 |
/// produce or parse BSON UUIDs. |
| 162 |
/// |
| 163 |
/// To enable interop with the [`Uuid`] type from the `uuid` crate, enable the `uuid-0_8` feature |
| 164 |
/// flag. |
| 165 |
/// |
| 166 |
/// For more information on the usage of this type, see the [`uuid`] module-level documentation. |
| 167 |
/// |
| 168 |
/// Note: due to an issue in serde (see [here](https://github.com/serde-rs/serde/issues/2106)), this type |
| 169 |
/// will also allow deserialization from 16 byte + subtype 0 Binary values in BSON if part of a |
| 170 |
/// `#[serde(flatten)]` chain. This behavior shouldn't be relied upon as it may be fixed at some |
| 171 |
/// point in the future. |
| 172 |
#[derive(Clone, Copy, PartialEq, Hash, Eq, PartialOrd, Ord)] |
| 173 |
pub struct Uuid { |
| 174 |
uuid: uuid::Uuid, |
| 175 |
} |
| 176 |
|
| 177 |
impl Uuid { |
| 178 |
/// Creates a random UUID. |
| 179 |
/// |
| 180 |
/// This uses the operating system's RNG as the source of random numbers. If you'd like to use a |
| 181 |
/// custom generator, generate random bytes and pass them to [`Uuid::from_bytes`] instead. |
| 182 |
pub fn new() -> Self { |
| 183 |
Self { |
| 184 |
uuid: uuid::Uuid::new_v4(), |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
/// Creates a [`Uuid`] using the supplied big-endian bytes. |
| 189 |
pub const fn from_bytes(bytes: [u8; 16]) -> Self { |
| 190 |
Self::from_external_uuid(uuid::Uuid::from_bytes(bytes)) |
| 191 |
} |
| 192 |
|
| 193 |
/// Creates a [`Uuid`] from the provided hex string. |
| 194 |
pub fn parse_str(input: impl AsRef<str>) -> Result<Self> { |
| 195 |
let uuid = uuid::Uuid::parse_str(input.as_ref()).map_err(|e| Error::InvalidUuidString { |
| 196 |
message: e.to_string(), |
| 197 |
})?; |
| 198 |
Ok(Self::from_external_uuid(uuid)) |
| 199 |
} |
| 200 |
|
| 201 |
pub(crate) const fn from_external_uuid(uuid: uuid::Uuid) -> Self { |
| 202 |
Self { uuid } |
| 203 |
} |
| 204 |
|
| 205 |
/// Returns an array of 16 bytes containing the [`Uuid`]'s data. |
| 206 |
pub const fn bytes(self) -> [u8; 16] { |
| 207 |
*self.uuid.as_bytes() |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
impl Default for Uuid { |
| 212 |
fn default() -> Self { |
| 213 |
Self::new() |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
#[cfg(feature = "uuid-0_8")] |
| 218 |
#[cfg_attr(docsrs, doc(cfg(feature = "uuid-0_8")))] |
| 219 |
impl Uuid { |
| 220 |
/// Create a [`Uuid`] from a [`uuid::Uuid`](https://docs.rs/uuid/0.8/uuid/struct.Uuid.html) from |
| 221 |
/// the [`uuid`](https://docs.rs/uuid/0.8) crate. |
| 222 |
pub fn from_uuid_0_8(uuid: uuid_0_8::Uuid) -> Self { |
| 223 |
Self::from_external_uuid(uuid::Uuid::from_u128(uuid.as_u128())) |
| 224 |
} |
| 225 |
|
| 226 |
/// Convert this [`Uuid`] to a [`uuid::Uuid`](https://docs.rs/uuid/0.8/uuid/struct.Uuid.html) from |
| 227 |
/// the [`uuid`](https://docs.rs/uuid/0.8) crate. |
| 228 |
pub fn to_uuid_0_8(self) -> uuid_0_8::Uuid { |
| 229 |
uuid_0_8::Uuid::from_bytes(self.uuid.into_bytes()) |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
#[cfg(feature = "uuid-1")] |
| 234 |
#[cfg_attr(docsrs, doc(cfg(feature = "uuid-1")))] |
| 235 |
impl Uuid { |
| 236 |
/// Create a [`Uuid`] from a [`uuid::Uuid`](https://docs.rs/uuid/0.8/uuid/struct.Uuid.html) from |
| 237 |
/// the [`uuid`](https://docs.rs/uuid/0.8) crate. |
| 238 |
pub fn from_uuid_1(uuid: uuid::Uuid) -> Self { |
| 239 |
Self::from_external_uuid(uuid) |
| 240 |
} |
| 241 |
|
| 242 |
/// Convert this [`Uuid`] to a [`uuid::Uuid`](https://docs.rs/uuid/0.8/uuid/struct.Uuid.html) from |
| 243 |
/// the [`uuid`](https://docs.rs/uuid/0.8) crate. |
| 244 |
pub fn to_uuid_1(self) -> uuid::Uuid { |
| 245 |
self.uuid |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
impl Serialize for Uuid { |
| 250 |
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 251 |
where |
| 252 |
S: serde::Serializer, |
| 253 |
{ |
| 254 |
serializer.serialize_newtype_struct(UUID_NEWTYPE_NAME, &self.uuid) |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
impl<'de> Deserialize<'de> for Uuid { |
| 259 |
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> |
| 260 |
where |
| 261 |
D: serde::Deserializer<'de>, |
| 262 |
{ |
| 263 |
match deserializer.deserialize_newtype_struct(UUID_NEWTYPE_NAME, BsonVisitor)? { |
| 264 |
// Need to support deserializing from generic subtypes for non-BSON formats. |
| 265 |
// When using the BSON deserializer, the newtype name will ensure the subtype is only |
| 266 |
// ever BinarySubtype::Uuid. |
| 267 |
Bson::Binary(b) |
| 268 |
if matches!(b.subtype, BinarySubtype::Uuid | BinarySubtype::Generic) => |
| 269 |
{ |
| 270 |
let uuid = |
| 271 |
uuid::Uuid::from_slice(b.bytes.as_slice()).map_err(serde::de::Error::custom)?; |
| 272 |
Ok(Self::from_external_uuid(uuid)) |
| 273 |
} |
| 274 |
Bson::Binary(b) if b.subtype == BinarySubtype::UuidOld => { |
| 275 |
Err(serde::de::Error::custom( |
| 276 |
"received legacy UUID (subtype 3) but expected regular UUID (subtype 4)", |
| 277 |
)) |
| 278 |
} |
| 279 |
Bson::String(s) => { |
| 280 |
let uuid = uuid::Uuid::from_str(s.as_str()).map_err(serde::de::Error::custom)?; |
| 281 |
Ok(Self::from_external_uuid(uuid)) |
| 282 |
} |
| 283 |
b => Err(serde::de::Error::invalid_type(b.as_unexpected(), &"a UUID")), |
| 284 |
} |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
impl Display for Uuid { |
| 289 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 290 |
self.uuid.fmt(f) |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
impl std::fmt::Debug for Uuid { |
| 295 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 296 |
std::fmt::Debug::fmt(&self.uuid, f) |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
impl From<Uuid> for Binary { |
| 301 |
fn from(uuid: Uuid) -> Self { |
| 302 |
Binary { |
| 303 |
subtype: BinarySubtype::Uuid, |
| 304 |
bytes: uuid.bytes().to_vec(), |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
impl From<Uuid> for Bson { |
| 310 |
fn from(u: Uuid) -> Self { |
| 311 |
Bson::Binary(u.into()) |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
#[cfg(feature = "uuid-0_8")] |
| 316 |
impl From<uuid_0_8::Uuid> for Uuid { |
| 317 |
fn from(u: uuid_0_8::Uuid) -> Self { |
| 318 |
Self::from_uuid_0_8(u) |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
#[cfg(feature = "uuid-0_8")] |
| 323 |
impl From<Uuid> for uuid_0_8::Uuid { |
| 324 |
fn from(s: Uuid) -> Self { |
| 325 |
s.to_uuid_0_8() |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
#[cfg(feature = "uuid-1")] |
| 330 |
impl From<uuid::Uuid> for Uuid { |
| 331 |
fn from(u: uuid::Uuid) -> Self { |
| 332 |
Self::from_uuid_1(u) |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
#[cfg(feature = "uuid-1")] |
| 337 |
impl From<Uuid> for uuid::Uuid { |
| 338 |
fn from(s: Uuid) -> Self { |
| 339 |
s.to_uuid_1() |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
/// Enum of the possible representations to use when converting between [`Uuid`] and [`Binary`]. |
| 344 |
/// This enum is necessary because the different drivers used to have different ways of encoding |
| 345 |
/// UUIDs, with the BSON subtype: 0x03 (UUID old). |
| 346 |
/// If a UUID has been serialized with a particular representation, it MUST |
| 347 |
/// be deserialized with the same representation. |
| 348 |
/// |
| 349 |
/// Example: |
| 350 |
/// ``` |
| 351 |
/// use bson::{Binary, uuid::{Uuid, UuidRepresentation}}; |
| 352 |
/// |
| 353 |
/// let uuid = Uuid::parse_str("00112233445566778899AABBCCDDEEFF")?; |
| 354 |
/// let bin = Binary::from_uuid_with_representation(uuid, UuidRepresentation::PythonLegacy); |
| 355 |
/// |
| 356 |
/// // This conversion fails, since the binary holds a PythonLegacy UUID, so we're required to specify |
| 357 |
/// // that. |
| 358 |
/// assert!(bin.to_uuid().is_err()); |
| 359 |
/// |
| 360 |
/// // This conversion succeeds, since we specified the correct representation. |
| 361 |
/// let new_uuid = bin.to_uuid_with_representation(UuidRepresentation::PythonLegacy)?; |
| 362 |
/// assert_eq!(new_uuid, uuid); |
| 363 |
/// |
| 364 |
/// # Ok::<(), Box::<dyn std::error::Error>>(()) |
| 365 |
/// ``` |
| 366 |
#[non_exhaustive] |
| 367 |
#[derive(PartialEq, Clone, Copy, Debug)] |
| 368 |
pub enum UuidRepresentation { |
| 369 |
/// The canonical representation of UUIDs in BSON (binary with subtype 0x04) |
| 370 |
Standard, |
| 371 |
/// The legacy representation of UUIDs in BSON used by the C# driver (binary subtype 0x03) |
| 372 |
CSharpLegacy, |
| 373 |
/// The legacy representation of UUIDs in BSON used by the Java driver (binary subtype 0x03) |
| 374 |
JavaLegacy, |
| 375 |
/// The legacy representation of UUIDs in BSON used by the Python driver, which is the same |
| 376 |
/// format as STANDARD, but has binary subtype 0x03 |
| 377 |
PythonLegacy, |
| 378 |
} |
| 379 |
|
| 380 |
impl Binary { |
| 381 |
/// Serializes a [`Uuid`] into BSON [`Binary`] type |
| 382 |
pub fn from_uuid(uuid: Uuid) -> Self { |
| 383 |
Binary::from(uuid) |
| 384 |
} |
| 385 |
|
| 386 |
/// Serializes a [`Uuid`] into BSON binary type and takes the desired representation as a |
| 387 |
/// parameter. `Binary::from_uuid_with_representation(uuid, UuidRepresentation::Standard)` is |
| 388 |
/// equivalent to `Binary::from_uuid(uuid)`. |
| 389 |
/// |
| 390 |
/// See the documentation for [`UuidRepresentation`] for more information on the possible |
| 391 |
/// representations. |
| 392 |
pub fn from_uuid_with_representation(uuid: Uuid, rep: UuidRepresentation) -> Self { |
| 393 |
match rep { |
| 394 |
UuidRepresentation::Standard => Binary::from_uuid(uuid), |
| 395 |
UuidRepresentation::CSharpLegacy => { |
| 396 |
let mut bytes = uuid.bytes().to_vec(); |
| 397 |
bytes[0..4].reverse(); |
| 398 |
bytes[4..6].reverse(); |
| 399 |
bytes[6..8].reverse(); |
| 400 |
Binary { |
| 401 |
subtype: BinarySubtype::UuidOld, |
| 402 |
bytes, |
| 403 |
} |
| 404 |
} |
| 405 |
UuidRepresentation::PythonLegacy => Binary { |
| 406 |
subtype: BinarySubtype::UuidOld, |
| 407 |
bytes: uuid.bytes().to_vec(), |
| 408 |
}, |
| 409 |
UuidRepresentation::JavaLegacy => { |
| 410 |
let mut bytes = uuid.bytes().to_vec(); |
| 411 |
bytes[0..8].reverse(); |
| 412 |
bytes[8..16].reverse(); |
| 413 |
Binary { |
| 414 |
subtype: BinarySubtype::UuidOld, |
| 415 |
bytes, |
| 416 |
} |
| 417 |
} |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
/// Deserializes a BSON [`Binary`] type into a [`Uuid`] according to the provided |
| 422 |
/// representation. If the representation does not match the [`Binary`], an error will be |
| 423 |
/// returned. |
| 424 |
/// |
| 425 |
/// See the documentation for [`UuidRepresentation`] for more information on the possible |
| 426 |
/// representations. |
| 427 |
pub fn to_uuid_with_representation(&self, rep: UuidRepresentation) -> Result<Uuid> { |
| 428 |
// If representation is non-standard, then its subtype must be UuidOld |
| 429 |
if rep != UuidRepresentation::Standard && self.subtype != BinarySubtype::UuidOld { |
| 430 |
return Err(Error::RepresentationMismatch { |
| 431 |
requested_representation: rep, |
| 432 |
actual_binary_subtype: self.subtype, |
| 433 |
expected_binary_subtype: BinarySubtype::UuidOld, |
| 434 |
}); |
| 435 |
} |
| 436 |
// If representation is standard, then its subtype must be Uuid |
| 437 |
if rep == UuidRepresentation::Standard && self.subtype != BinarySubtype::Uuid { |
| 438 |
return Err(Error::RepresentationMismatch { |
| 439 |
requested_representation: rep, |
| 440 |
actual_binary_subtype: self.subtype, |
| 441 |
expected_binary_subtype: BinarySubtype::Uuid, |
| 442 |
}); |
| 443 |
} |
| 444 |
// Must be 16 bytes long |
| 445 |
if self.bytes.len() != 16 { |
| 446 |
return Err(Error::InvalidLength { |
| 447 |
length: self.bytes.len(), |
| 448 |
}); |
| 449 |
} |
| 450 |
let mut buf = [0u8; 16]; |
| 451 |
buf.copy_from_slice(&self.bytes); |
| 452 |
Ok(match rep { |
| 453 |
UuidRepresentation::Standard => Uuid::from_bytes(buf), |
| 454 |
UuidRepresentation::CSharpLegacy => { |
| 455 |
buf[0..4].reverse(); |
| 456 |
buf[4..6].reverse(); |
| 457 |
buf[6..8].reverse(); |
| 458 |
Uuid::from_bytes(buf) |
| 459 |
} |
| 460 |
UuidRepresentation::PythonLegacy => Uuid::from_bytes(buf), |
| 461 |
UuidRepresentation::JavaLegacy => { |
| 462 |
buf[0..8].reverse(); |
| 463 |
buf[8..16].reverse(); |
| 464 |
Uuid::from_bytes(buf) |
| 465 |
} |
| 466 |
}) |
| 467 |
} |
| 468 |
|
| 469 |
/// Deserializes a BSON [`Binary`] type into a [`Uuid`] using the standard |
| 470 |
/// representation. |
| 471 |
pub fn to_uuid(&self) -> Result<Uuid> { |
| 472 |
self.to_uuid_with_representation(UuidRepresentation::Standard) |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
macro_rules! trait_impls { |
| 477 |
($feat:meta, $u:ty) => { |
| 478 |
#[cfg($feat)] |
| 479 |
#[cfg_attr(docsrs, doc(cfg($feat)))] |
| 480 |
impl From<$u> for Binary { |
| 481 |
fn from(uuid: $u) -> Self { |
| 482 |
Binary { |
| 483 |
subtype: BinarySubtype::Uuid, |
| 484 |
bytes: uuid.as_bytes().to_vec(), |
| 485 |
} |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
#[cfg(all($feat, feature = "serde_with"))] |
| 490 |
#[cfg_attr(docsrs, doc(cfg(all($feat, feature = "serde_with"))))] |
| 491 |
impl<'de> serde_with::DeserializeAs<'de, $u> for crate::Uuid { |
| 492 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<$u, D::Error> |
| 493 |
where |
| 494 |
D: serde::Deserializer<'de>, |
| 495 |
{ |
| 496 |
let uuid = Uuid::deserialize(deserializer)?; |
| 497 |
Ok(uuid.into()) |
| 498 |
} |
| 499 |
} |
| 500 |
|
| 501 |
#[cfg(all($feat, feature = "serde_with"))] |
| 502 |
#[cfg_attr(docsrs, doc(cfg(all($feat, feature = "serde_with"))))] |
| 503 |
impl serde_with::SerializeAs<$u> for crate::Uuid { |
| 504 |
fn serialize_as<S>(source: &$u, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 505 |
where |
| 506 |
S: serde::Serializer, |
| 507 |
{ |
| 508 |
let uuid = Uuid::from(*source); |
| 509 |
uuid.serialize(serializer) |
| 510 |
} |
| 511 |
} |
| 512 |
|
| 513 |
#[cfg(all($feat, feature = "serde_with-3"))] |
| 514 |
#[cfg_attr(docsrs, doc(cfg(all($feat, feature = "serde_with-3"))))] |
| 515 |
impl<'de> serde_with_3::DeserializeAs<'de, $u> for crate::Uuid { |
| 516 |
fn deserialize_as<D>(deserializer: D) -> std::result::Result<$u, D::Error> |
| 517 |
where |
| 518 |
D: serde::Deserializer<'de>, |
| 519 |
{ |
| 520 |
let uuid = Uuid::deserialize(deserializer)?; |
| 521 |
Ok(uuid.into()) |
| 522 |
} |
| 523 |
} |
| 524 |
|
| 525 |
#[cfg(all($feat, feature = "serde_with-3"))] |
| 526 |
#[cfg_attr(docsrs, doc(cfg(all($feat, feature = "serde_with-3"))))] |
| 527 |
impl serde_with_3::SerializeAs<$u> for crate::Uuid { |
| 528 |
fn serialize_as<S>(source: &$u, serializer: S) -> std::result::Result<S::Ok, S::Error> |
| 529 |
where |
| 530 |
S: serde::Serializer, |
| 531 |
{ |
| 532 |
let uuid = Uuid::from(*source); |
| 533 |
uuid.serialize(serializer) |
| 534 |
} |
| 535 |
} |
| 536 |
}; |
| 537 |
} |
| 538 |
trait_impls!(feature = "uuid-0_8", uuid_0_8::Uuid); |
| 539 |
trait_impls!(feature = "uuid-1", uuid::Uuid); |
| 540 |
|
| 541 |
/// Errors that can occur during [`Uuid`] construction and generation. |
| 542 |
#[derive(Clone, Debug)] |
| 543 |
#[non_exhaustive] |
| 544 |
pub enum Error { |
| 545 |
/// Error returned when an invalid string is provided to [`Uuid::parse_str`]. |
| 546 |
#[non_exhaustive] |
| 547 |
InvalidUuidString { message: String }, |
| 548 |
|
| 549 |
/// Error returned when the representation specified does not match the underlying |
| 550 |
/// [`crate::Binary`] value in [`crate::Binary::to_uuid_with_representation`]. |
| 551 |
#[non_exhaustive] |
| 552 |
RepresentationMismatch { |
| 553 |
/// The subtype that was expected given the requested representation. |
| 554 |
expected_binary_subtype: BinarySubtype, |
| 555 |
|
| 556 |
/// The actual subtype of the binary value. |
| 557 |
actual_binary_subtype: BinarySubtype, |
| 558 |
|
| 559 |
/// The requested representation. |
| 560 |
requested_representation: UuidRepresentation, |
| 561 |
}, |
| 562 |
|
| 563 |
/// Error returned from [`crate::Binary::to_uuid`] if the underling data is not 16 bytes long. |
| 564 |
#[non_exhaustive] |
| 565 |
InvalidLength { |
| 566 |
/// The actual length of the data. |
| 567 |
length: usize, |
| 568 |
}, |
| 569 |
} |
| 570 |
|
| 571 |
/// Alias for `Result<T, bson::uuid::Error>`. |
| 572 |
pub type Result<T> = std::result::Result<T, Error>; |
| 573 |
|
| 574 |
impl fmt::Display for Error { |
| 575 |
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 576 |
match self { |
| 577 |
Error::InvalidUuidString { message } => { |
| 578 |
write!(fmt, "{}", message) |
| 579 |
} |
| 580 |
Error::RepresentationMismatch { |
| 581 |
expected_binary_subtype, |
| 582 |
actual_binary_subtype, |
| 583 |
requested_representation, |
| 584 |
} => { |
| 585 |
write!( |
| 586 |
fmt, |
| 587 |
"expected {:?} when converting to UUID with {:?}, isntead got {:?}", |
| 588 |
expected_binary_subtype, requested_representation, actual_binary_subtype |
| 589 |
) |
| 590 |
} |
| 591 |
Error::InvalidLength { length } => { |
| 592 |
write!( |
| 593 |
fmt, |
| 594 |
"expected UUID to contain 16 bytes, instead got {}", |
| 595 |
length |
| 596 |
) |
| 597 |
} |
| 598 |
} |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
impl std::error::Error for Error {} |