Skip to content

Commit

Permalink
Merge #172
Browse files Browse the repository at this point in the history
172: from_rng_bytes added r=kinggoesgaming a=Dylan-DPC

<!--
    As we are working towards a stable version of uuid, we require that you 
    open an issue, before submitting a pull request. If the pull request is 
    imcomplete, prepend the Title with WIP: 
-->

**I'm submitting a ...**
  - [ ] bug fix
  - [x] feature enhancement
  - [ ] deprecation or removal
  - [ ] refactor

# Description
<!-- Provide a summary of your changes in the Title above -->
As discussed in the issue, this method is a solution to avoid making `rand` a public dependency

# Motivation
To avoid making `rand` public dependency
<!-- Why is this change required -->

# Tests
<!-- How are these changes tested? -->
none, test added 

# Related Issue(s)
#170 
<!-- 
    As noted above, we require an issue for every PR. Please link to the issue
    here
-->
  • Loading branch information
bors[bot] committed Mar 20, 2018
2 parents eca7598 + d4c2963 commit 23ba888
Showing 1 changed file with 44 additions and 5 deletions.
49 changes: 44 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,11 +507,10 @@ impl Uuid {

let mut rng = rand::thread_rng();

let mut uuid = Uuid { bytes: [0; 16] };
rng.fill_bytes(&mut uuid.bytes);
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Random);
uuid
let mut bytes = [0; 16];
rng.fill_bytes(&mut bytes);

Uuid::from_random_bytes(bytes)
}

/// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
Expand Down Expand Up @@ -685,6 +684,33 @@ impl Uuid {
Uuid { bytes: b }
}

/// Creates a v4 Uuid from random bytes (e.g. bytes supplied from `Rand` crate)
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use uuid::Uuid;
/// use uuid::UuidBytes;
///
///
/// let bytes:UuidBytes = [70, 235, 208, 238, 14, 109, 67, 201, 185, 13, 204, 195, 90, 145, 63, 62];
/// let uuid = Uuid::from_random_bytes(bytes);
/// let uuid = uuid.hyphenated().to_string();
///
/// let expected_uuid = String::from("46ebd0ee-0e6d-43c9-b90d-ccc35a913f3e");
///
/// assert_eq!(expected_uuid, uuid);
/// ```
///
pub fn from_random_bytes(b: [u8; 16]) -> Uuid {
let mut uuid = Uuid { bytes: b };
uuid.set_variant(UuidVariant::RFC4122);
uuid.set_version(UuidVersion::Random);
uuid
}

/// Specifies the variant of the UUID structure
#[allow(dead_code)]
fn set_variant(&mut self, v: UuidVariant) {
Expand Down Expand Up @@ -1798,6 +1824,19 @@ mod tests {
assert_eq!(&b_in, b_out);
}

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

let u = Uuid::from_random_bytes(b);
let expected = "a1a2a3a4b1b241c291d2d3d4d5d6d7d8";

assert_eq!(u.simple().to_string(), expected);
}

#[test]
fn test_operator_eq() {
let u1 = new();
Expand Down

0 comments on commit 23ba888

Please sign in to comment.