Skip to content

Commit

Permalink
Merge pull request #599 from dfaust/to_bytes_le
Browse files Browse the repository at this point in the history
Add to_bytes_le method
  • Loading branch information
KodrAus authored May 25, 2022
2 parents 7a2d4e4 + b0ca5a0 commit 7d037f5
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,38 @@ impl Uuid {
self.0
}

/// Returns the bytes of the UUID in little-endian order.
///
/// The bytes will be flipped to convert into little-endian order. This is
/// based on the endianness of the UUID, rather than the target environment
/// so bytes will be flipped on both big and little endian machines.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
///
/// assert_eq!(
/// uuid.to_bytes_le(),
/// ([
/// 0xa4, 0xa3, 0xa2, 0xa1, 0xb2, 0xb1, 0xc2, 0xc1, 0xd1, 0xd2,
/// 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8
/// ])
/// );
/// # Ok(())
/// # }
/// ```
pub const fn to_bytes_le(&self) -> Bytes {
[
self.0[3], self.0[2], self.0[1], self.0[0], self.0[5], self.0[4],
self.0[7], self.0[6], self.0[8], self.0[9], self.0[10], self.0[11],
self.0[12], self.0[13], self.0[14], self.0[15],
]
}

/// Tests if the UUID is nil.
pub const fn is_nil(&self) -> bool {
self.as_u128() == 0
Expand Down Expand Up @@ -1370,6 +1402,23 @@ mod tests {
assert_eq!(&b_in, b_out);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_bytes_le_roundtrip() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3,
0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
];

let u1 = Uuid::from_bytes(b);

let b_le = u1.to_bytes_le();

let u2 = Uuid::from_bytes_le(b_le);

assert_eq!(u1, u2);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_iterbytes_impl_for_uuid() {
Expand Down

0 comments on commit 7d037f5

Please sign in to comment.