2014-05-26 02:32:04 +01:00
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
2013-07-24 23:10:15 +10:00
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
/*!
|
|
|
|
Generate and parse UUIDs
|
|
|
|
|
|
|
|
Provides support for Universally Unique Identifiers (UUIDs). A UUID is a
|
|
|
|
unique 128-bit number, stored as 16 octets. UUIDs are used to assign unique
|
|
|
|
identifiers to entities without requiring a central allocating authority.
|
|
|
|
|
|
|
|
They are particularly useful in distributed systems, though can be used in
|
|
|
|
disparate areas, such as databases and network protocols. Typically a UUID is
|
2013-12-15 16:34:14 +11:00
|
|
|
displayed in a readable string form as a sequence of hexadecimal digits,
|
2013-07-24 23:10:15 +10:00
|
|
|
separated into groups by hyphens.
|
|
|
|
|
|
|
|
The uniqueness property is not strictly guaranteed, however for all practical
|
|
|
|
purposes, it can be assumed that an unintentional collision would be extremely
|
|
|
|
unlikely.
|
|
|
|
|
|
|
|
# Examples
|
|
|
|
|
|
|
|
To create a new random (V4) UUID and print it out in hexadecimal form:
|
|
|
|
|
2013-09-23 17:20:36 -07:00
|
|
|
```rust
|
2014-07-31 08:13:25 -07:00
|
|
|
# #![allow(deprecated)]
|
|
|
|
# extern crate uuid;
|
2014-02-03 20:02:47 +02:00
|
|
|
use uuid::Uuid;
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
2014-06-21 03:39:03 -07:00
|
|
|
println!("{}", uuid1.to_string());
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
2014-05-02 17:56:35 -07:00
|
|
|
```
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
# Strings
|
|
|
|
|
|
|
|
Examples of string representations:
|
|
|
|
|
|
|
|
* simple: `936DA01F9ABD4d9d80C702AF85C822A8`
|
|
|
|
* hyphenated: `550e8400-e29b-41d4-a716-446655440000`
|
|
|
|
* urn: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
|
|
|
|
|
|
|
|
# References
|
|
|
|
|
|
|
|
* [Wikipedia: Universally Unique Identifier](
|
|
|
|
http://en.wikipedia.org/wiki/Universally_unique_identifier)
|
|
|
|
* [RFC4122: A Universally Unique IDentifier (UUID) URN Namespace](
|
|
|
|
http://tools.ietf.org/html/rfc4122)
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
2014-07-01 07:12:04 -07:00
|
|
|
#![crate_name = "uuid"]
|
2014-07-30 23:30:48 +01:00
|
|
|
#![deprecated = "This is now a cargo package located at: \
|
|
|
|
https://github.com/rust-lang/uuid"]
|
2014-03-21 18:05:05 -07:00
|
|
|
#![crate_type = "rlib"]
|
|
|
|
#![crate_type = "dylib"]
|
|
|
|
#![license = "MIT/ASL2"]
|
|
|
|
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
|
|
|
|
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
|
2014-07-11 11:21:57 -07:00
|
|
|
html_root_url = "http://doc.rust-lang.org/master/",
|
2014-06-06 09:12:18 -07:00
|
|
|
html_playground_url = "http://play.rust-lang.org/")]
|
2014-03-21 18:05:05 -07:00
|
|
|
|
|
|
|
#![feature(default_type_params)]
|
2014-02-25 08:03:41 -08:00
|
|
|
|
2014-02-05 08:52:54 -08:00
|
|
|
// test harness access
|
|
|
|
#[cfg(test)]
|
2014-02-14 09:49:11 +08:00
|
|
|
extern crate test;
|
2014-02-14 10:10:06 -08:00
|
|
|
extern crate serialize;
|
2014-02-03 20:02:47 +02:00
|
|
|
|
2013-07-24 23:10:15 +10:00
|
|
|
use std::char::Char;
|
2014-02-23 12:07:11 +11:00
|
|
|
use std::default::Default;
|
2014-02-19 18:56:33 -08:00
|
|
|
use std::fmt;
|
2014-02-23 12:29:42 +11:00
|
|
|
use std::from_str::FromStr;
|
2014-05-29 19:03:06 -07:00
|
|
|
use std::hash;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
use std::mem::{transmute,transmute_copy};
|
2014-02-19 18:56:33 -08:00
|
|
|
use std::num::FromStrRadix;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
use std::rand;
|
|
|
|
use std::rand::Rng;
|
2014-03-08 18:11:52 -05:00
|
|
|
use std::slice;
|
2014-03-02 11:33:24 +11:00
|
|
|
|
2014-02-05 08:52:54 -08:00
|
|
|
use serialize::{Encoder, Encodable, Decoder, Decodable};
|
2013-10-14 01:47:52 -04:00
|
|
|
|
2013-07-24 23:10:15 +10:00
|
|
|
/// A 128-bit (16 byte) buffer containing the ID
|
|
|
|
pub type UuidBytes = [u8, ..16];
|
|
|
|
|
|
|
|
/// The version of the UUID, denoting the generating algorithm
|
2014-05-29 17:45:07 -07:00
|
|
|
#[deriving(PartialEq)]
|
2013-07-24 23:10:15 +10:00
|
|
|
pub enum UuidVersion {
|
|
|
|
/// Version 1: MAC address
|
|
|
|
Version1Mac = 1,
|
|
|
|
/// Version 2: DCE Security
|
|
|
|
Version2Dce = 2,
|
|
|
|
/// Version 3: MD5 hash
|
|
|
|
Version3Md5 = 3,
|
|
|
|
/// Version 4: Random
|
|
|
|
Version4Random = 4,
|
|
|
|
/// Version 5: SHA-1 hash
|
|
|
|
Version5Sha1 = 5,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The reserved variants of UUIDs
|
2014-05-29 17:45:07 -07:00
|
|
|
#[deriving(PartialEq)]
|
2013-07-24 23:10:15 +10:00
|
|
|
pub enum UuidVariant {
|
2013-12-15 16:34:14 +11:00
|
|
|
/// Reserved by the NCS for backward compatibility
|
2013-07-24 23:10:15 +10:00
|
|
|
VariantNCS,
|
|
|
|
/// As described in the RFC4122 Specification (default)
|
|
|
|
VariantRFC4122,
|
2013-12-15 16:34:14 +11:00
|
|
|
/// Reserved by Microsoft for backward compatibility
|
2013-07-24 23:10:15 +10:00
|
|
|
VariantMicrosoft,
|
|
|
|
/// Reserved for future expansion
|
|
|
|
VariantFuture,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A Universally Unique Identifier (UUID)
|
|
|
|
pub struct Uuid {
|
|
|
|
/// The 128-bit number stored in 16 bytes
|
|
|
|
bytes: UuidBytes
|
|
|
|
}
|
2014-02-25 08:03:41 -08:00
|
|
|
|
2014-05-29 19:03:06 -07:00
|
|
|
impl<S: hash::Writer> hash::Hash<S> for Uuid {
|
2014-02-25 08:03:41 -08:00
|
|
|
fn hash(&self, state: &mut S) {
|
|
|
|
self.bytes.hash(state)
|
2013-12-23 23:44:58 -08:00
|
|
|
}
|
|
|
|
}
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
/// A UUID stored as fields (identical to UUID, used only for conversions)
|
|
|
|
struct UuidFields {
|
|
|
|
/// First field, 32-bit word
|
|
|
|
data1: u32,
|
|
|
|
/// Second field, 16-bit short
|
|
|
|
data2: u16,
|
|
|
|
/// Third field, 16-bit short
|
|
|
|
data3: u16,
|
|
|
|
/// Fourth field, 8 bytes
|
|
|
|
data4: [u8, ..8]
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Error details for string parsing failures
|
2013-10-01 23:26:45 -07:00
|
|
|
#[allow(missing_doc)]
|
2013-07-24 23:10:15 +10:00
|
|
|
pub enum ParseError {
|
|
|
|
ErrorInvalidLength(uint),
|
|
|
|
ErrorInvalidCharacter(char, uint),
|
|
|
|
ErrorInvalidGroups(uint),
|
|
|
|
ErrorInvalidGroupLength(uint, uint, uint),
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Converts a ParseError to a string
|
2014-02-19 18:56:33 -08:00
|
|
|
impl fmt::Show for ParseError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2013-07-24 23:10:15 +10:00
|
|
|
match *self {
|
|
|
|
ErrorInvalidLength(found) =>
|
2014-05-10 14:05:06 -07:00
|
|
|
write!(f, "Invalid length; expecting 32, 36 or 45 chars, \
|
|
|
|
found {}", found),
|
2013-07-24 23:10:15 +10:00
|
|
|
ErrorInvalidCharacter(found, pos) =>
|
2014-05-10 14:05:06 -07:00
|
|
|
write!(f, "Invalid character; found `{}` (0x{:02x}) at \
|
|
|
|
offset {}", found, found as uint, pos),
|
2013-07-24 23:10:15 +10:00
|
|
|
ErrorInvalidGroups(found) =>
|
2014-05-10 14:05:06 -07:00
|
|
|
write!(f, "Malformed; wrong number of groups: expected 1 \
|
|
|
|
or 5, found {}", found),
|
2013-07-24 23:10:15 +10:00
|
|
|
ErrorInvalidGroupLength(group, found, expecting) =>
|
2014-05-10 14:05:06 -07:00
|
|
|
write!(f, "Malformed; length of group {} was {}, \
|
|
|
|
expecting {}", group, found, expecting),
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Length of each hyphenated group in hex digits
|
|
|
|
static UuidGroupLens: [uint, ..5] = [8u, 4u, 4u, 4u, 12u];
|
|
|
|
|
|
|
|
/// UUID support
|
|
|
|
impl Uuid {
|
|
|
|
/// Returns a nil or empty UUID (containing all zeroes)
|
2014-01-18 17:08:23 +11:00
|
|
|
pub fn nil() -> Uuid {
|
2013-07-24 23:10:15 +10:00
|
|
|
let uuid = Uuid{ bytes: [0, .. 16] };
|
|
|
|
uuid
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Create a new UUID of the specified version
|
|
|
|
pub fn new(v: UuidVersion) -> Option<Uuid> {
|
|
|
|
match v {
|
|
|
|
Version4Random => Some(Uuid::new_v4()),
|
|
|
|
_ => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new random UUID
|
|
|
|
///
|
|
|
|
/// Uses the `rand` module's default RNG task as the source
|
|
|
|
/// of random numbers. Use the rand::Rand trait to supply
|
|
|
|
/// a custom generator if required.
|
|
|
|
pub fn new_v4() -> Uuid {
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
let ub = rand::task_rng().gen_iter::<u8>().take(16).collect::<Vec<_>>();
|
2013-07-24 23:10:15 +10:00
|
|
|
let mut uuid = Uuid{ bytes: [0, .. 16] };
|
2014-03-27 23:00:46 +11:00
|
|
|
slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
|
2013-07-24 23:10:15 +10:00
|
|
|
uuid.set_variant(VariantRFC4122);
|
|
|
|
uuid.set_version(Version4Random);
|
|
|
|
uuid
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a UUID using the supplied field values
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
/// * `d1` A 32-bit word
|
|
|
|
/// * `d2` A 16-bit word
|
|
|
|
/// * `d3` A 16-bit word
|
|
|
|
/// * `d4` Array of 8 octets
|
|
|
|
pub fn from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8]) -> Uuid {
|
|
|
|
// First construct a temporary field-based struct
|
|
|
|
let mut fields = UuidFields {
|
|
|
|
data1: 0,
|
|
|
|
data2: 0,
|
|
|
|
data3: 0,
|
|
|
|
data4: [0, ..8]
|
|
|
|
};
|
|
|
|
|
2014-06-17 15:47:31 -07:00
|
|
|
fields.data1 = d1.to_be();
|
|
|
|
fields.data2 = d2.to_be();
|
|
|
|
fields.data3 = d3.to_be();
|
2014-03-08 18:11:52 -05:00
|
|
|
slice::bytes::copy_memory(fields.data4, d4);
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
unsafe {
|
|
|
|
transmute(fields)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a UUID using the supplied bytes
|
|
|
|
///
|
|
|
|
/// # Arguments
|
|
|
|
/// * `b` An array or slice of 16 bytes
|
2013-09-07 11:05:48 -07:00
|
|
|
pub fn from_bytes(b: &[u8]) -> Option<Uuid> {
|
2013-07-24 23:10:15 +10:00
|
|
|
if b.len() != 16 {
|
|
|
|
return None
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut uuid = Uuid{ bytes: [0, .. 16] };
|
2014-03-08 18:11:52 -05:00
|
|
|
slice::bytes::copy_memory(uuid.bytes, b);
|
2013-07-24 23:10:15 +10:00
|
|
|
Some(uuid)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Specifies the variant of the UUID structure
|
|
|
|
fn set_variant(&mut self, v: UuidVariant) {
|
|
|
|
// Octet 8 contains the variant in the most significant 3 bits
|
|
|
|
match v {
|
|
|
|
VariantNCS => // b0xx...
|
|
|
|
self.bytes[8] = self.bytes[8] & 0x7f,
|
|
|
|
VariantRFC4122 => // b10x...
|
|
|
|
self.bytes[8] = (self.bytes[8] & 0x3f) | 0x80,
|
|
|
|
VariantMicrosoft => // b110...
|
|
|
|
self.bytes[8] = (self.bytes[8] & 0x1f) | 0xc0,
|
|
|
|
VariantFuture => // b111...
|
|
|
|
self.bytes[8] = (self.bytes[8] & 0x1f) | 0xe0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the variant of the UUID structure
|
|
|
|
///
|
|
|
|
/// This determines the interpretation of the structure of the UUID.
|
|
|
|
/// Currently only the RFC4122 variant is generated by this module.
|
|
|
|
///
|
|
|
|
/// * [Variant Reference](http://tools.ietf.org/html/rfc4122#section-4.1.1)
|
|
|
|
pub fn get_variant(&self) -> Option<UuidVariant> {
|
|
|
|
if self.bytes[8] & 0x80 == 0x00 {
|
|
|
|
Some(VariantNCS)
|
|
|
|
} else if self.bytes[8] & 0xc0 == 0x80 {
|
|
|
|
Some(VariantRFC4122)
|
|
|
|
} else if self.bytes[8] & 0xe0 == 0xc0 {
|
|
|
|
Some(VariantMicrosoft)
|
|
|
|
} else if self.bytes[8] & 0xe0 == 0xe0 {
|
|
|
|
Some(VariantFuture)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Specifies the version number of the UUID
|
|
|
|
fn set_version(&mut self, v: UuidVersion) {
|
|
|
|
self.bytes[6] = (self.bytes[6] & 0xF) | ((v as u8) << 4);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the version number of the UUID
|
|
|
|
///
|
|
|
|
/// This represents the algorithm used to generate the contents.
|
|
|
|
///
|
|
|
|
/// Currently only the Random (V4) algorithm is supported by this
|
|
|
|
/// module. There are security and privacy implications for using
|
|
|
|
/// older versions - see [Wikipedia: Universally Unique Identifier](
|
|
|
|
/// http://en.wikipedia.org/wiki/Universally_unique_identifier) for
|
|
|
|
/// details.
|
|
|
|
///
|
|
|
|
/// * [Version Reference](http://tools.ietf.org/html/rfc4122#section-4.1.3)
|
|
|
|
pub fn get_version_num(&self) -> uint {
|
|
|
|
(self.bytes[6] >> 4) as uint
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the version of the UUID
|
|
|
|
///
|
|
|
|
/// This represents the algorithm used to generate the contents
|
|
|
|
pub fn get_version(&self) -> Option<UuidVersion> {
|
2014-02-18 13:40:25 +01:00
|
|
|
let v = self.bytes[6] >> 4;
|
2013-07-24 23:10:15 +10:00
|
|
|
match v {
|
|
|
|
1 => Some(Version1Mac),
|
|
|
|
2 => Some(Version2Dce),
|
|
|
|
3 => Some(Version3Md5),
|
|
|
|
4 => Some(Version4Random),
|
|
|
|
5 => Some(Version5Sha1),
|
|
|
|
_ => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return an array of 16 octets containing the UUID data
|
2014-07-31 07:56:39 +09:00
|
|
|
pub fn as_bytes(&self) -> &[u8] {
|
2013-07-24 23:10:15 +10:00
|
|
|
self.bytes.as_slice()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the UUID as a string of 16 hexadecimal digits
|
|
|
|
///
|
|
|
|
/// Example: `936DA01F9ABD4d9d80C702AF85C822A8`
|
2014-05-22 16:57:53 -07:00
|
|
|
pub fn to_simple_str(&self) -> String {
|
2014-03-05 15:28:08 -08:00
|
|
|
let mut s: Vec<u8> = Vec::from_elem(32, 0u8);
|
2013-07-24 23:10:15 +10:00
|
|
|
for i in range(0u, 16u) {
|
2013-09-27 20:18:50 -07:00
|
|
|
let digit = format!("{:02x}", self.bytes[i] as uint);
|
2014-06-19 18:22:33 -07:00
|
|
|
*s.get_mut(i*2+0) = digit.as_bytes()[0];
|
|
|
|
*s.get_mut(i*2+1) = digit.as_bytes()[1];
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
2014-06-30 16:41:30 +02:00
|
|
|
String::from_utf8(s).unwrap()
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
2013-12-15 16:34:14 +11:00
|
|
|
/// Returns a string of hexadecimal digits, separated into groups with a hyphen.
|
2013-07-24 23:10:15 +10:00
|
|
|
///
|
|
|
|
/// Example: `550e8400-e29b-41d4-a716-446655440000`
|
2014-05-22 16:57:53 -07:00
|
|
|
pub fn to_hyphenated_str(&self) -> String {
|
2013-07-24 23:10:15 +10:00
|
|
|
// Convert to field-based struct as it matches groups in output.
|
|
|
|
// Ensure fields are in network byte order, as per RFC.
|
|
|
|
let mut uf: UuidFields;
|
|
|
|
unsafe {
|
|
|
|
uf = transmute_copy(&self.bytes);
|
|
|
|
}
|
2014-06-17 15:47:31 -07:00
|
|
|
uf.data1 = uf.data1.to_be();
|
|
|
|
uf.data2 = uf.data2.to_be();
|
|
|
|
uf.data3 = uf.data3.to_be();
|
2014-05-27 20:44:58 -07:00
|
|
|
let s = format!("{:08x}-{:04x}-{:04x}-{:02x}{:02x}-\
|
|
|
|
{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
|
2013-09-27 20:18:50 -07:00
|
|
|
uf.data1,
|
|
|
|
uf.data2, uf.data3,
|
|
|
|
uf.data4[0], uf.data4[1],
|
|
|
|
uf.data4[2], uf.data4[3], uf.data4[4],
|
|
|
|
uf.data4[5], uf.data4[6], uf.data4[7]);
|
2013-07-24 23:10:15 +10:00
|
|
|
s
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the UUID formatted as a full URN string
|
|
|
|
///
|
|
|
|
/// This is the same as the hyphenated format, but with the "urn:uuid:" prefix.
|
|
|
|
///
|
|
|
|
/// Example: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`
|
2014-05-22 16:57:53 -07:00
|
|
|
pub fn to_urn_str(&self) -> String {
|
2014-05-27 20:44:58 -07:00
|
|
|
format!("urn:uuid:{}", self.to_hyphenated_str())
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses a UUID from a string of hexadecimal digits with optional hyphens
|
|
|
|
///
|
|
|
|
/// Any of the formats generated by this module (simple, hyphenated, urn) are
|
|
|
|
/// supported by this parsing function.
|
|
|
|
pub fn parse_string(us: &str) -> Result<Uuid, ParseError> {
|
|
|
|
|
|
|
|
let mut us = us.clone();
|
|
|
|
let orig_len = us.len();
|
|
|
|
|
|
|
|
// Ensure length is valid for any of the supported formats
|
|
|
|
if orig_len != 32 && orig_len != 36 && orig_len != 45 {
|
|
|
|
return Err(ErrorInvalidLength(orig_len));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Strip off URN prefix if present
|
|
|
|
if us.starts_with("urn:uuid:") {
|
|
|
|
us = us.slice(9, orig_len);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure all chars are either hex digits or hyphen
|
2013-11-23 11:18:51 +01:00
|
|
|
for (i, c) in us.chars().enumerate() {
|
2013-07-24 23:10:15 +10:00
|
|
|
match c {
|
|
|
|
'0'..'9' | 'A'..'F' | 'a'..'f' | '-' => {},
|
|
|
|
_ => return Err(ErrorInvalidCharacter(c, i)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Split string up by hyphens into groups
|
2014-03-05 15:28:08 -08:00
|
|
|
let hex_groups: Vec<&str> = us.split_str("-").collect();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
// Get the length of each group
|
2014-03-05 15:28:08 -08:00
|
|
|
let group_lens: Vec<uint> = hex_groups.iter().map(|&v| v.len()).collect();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
// Ensure the group lengths are valid
|
|
|
|
match group_lens.len() {
|
|
|
|
// Single group, no hyphens
|
|
|
|
1 => {
|
2014-07-15 11:37:25 +12:00
|
|
|
if group_lens[0] != 32 {
|
|
|
|
return Err(ErrorInvalidLength(group_lens[0]));
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
},
|
|
|
|
// Five groups, hyphens in between each
|
|
|
|
5 => {
|
|
|
|
// Ensure each group length matches the expected
|
|
|
|
for (i, (&gl, &expected)) in
|
|
|
|
group_lens.iter().zip(UuidGroupLens.iter()).enumerate() {
|
|
|
|
if gl != expected {
|
|
|
|
return Err(ErrorInvalidGroupLength(i, gl, expected))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => {
|
|
|
|
return Err(ErrorInvalidGroups(group_lens.len()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Normalise into one long hex string
|
|
|
|
let vs = hex_groups.concat();
|
|
|
|
|
|
|
|
// At this point, we know we have a valid hex string, without hyphens
|
|
|
|
assert!(vs.len() == 32);
|
2014-05-19 23:19:56 -07:00
|
|
|
assert!(vs.as_slice().chars().all(|c| c.is_digit_radix(16)));
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
// Allocate output UUID buffer
|
|
|
|
let mut ub = [0u8, ..16];
|
|
|
|
|
|
|
|
// Extract each hex digit from the string
|
|
|
|
for i in range(0u, 16u) {
|
2014-05-19 23:19:56 -07:00
|
|
|
ub[i] = FromStrRadix::from_str_radix(vs.as_slice()
|
|
|
|
.slice(i*2, (i+1)*2),
|
|
|
|
16).unwrap();
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
2013-09-07 11:05:48 -07:00
|
|
|
Ok(Uuid::from_bytes(ub).unwrap())
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
2013-09-11 21:49:25 -07:00
|
|
|
|
2014-01-18 17:08:23 +11:00
|
|
|
/// Tests if the UUID is nil
|
|
|
|
pub fn is_nil(&self) -> bool {
|
|
|
|
return self.bytes.iter().all(|&b| b == 0);
|
2013-09-11 21:49:25 -07:00
|
|
|
}
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
2014-01-18 17:08:23 +11:00
|
|
|
impl Default for Uuid {
|
2013-07-24 23:10:15 +10:00
|
|
|
/// Returns the nil UUID, which is all zeroes
|
2014-01-18 17:08:23 +11:00
|
|
|
fn default() -> Uuid {
|
|
|
|
Uuid::nil()
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Clone for Uuid {
|
|
|
|
/// Returns a copy of the UUID
|
2013-12-15 22:23:11 +11:00
|
|
|
fn clone(&self) -> Uuid { *self }
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for Uuid {
|
|
|
|
/// Parse a hex string and interpret as a UUID
|
|
|
|
///
|
|
|
|
/// Accepted formats are a sequence of 32 hexadecimal characters,
|
2014-06-09 00:00:52 -04:00
|
|
|
/// with or without hyphens (grouped as 8, 4, 4, 4, 12).
|
2013-07-24 23:10:15 +10:00
|
|
|
fn from_str(us: &str) -> Option<Uuid> {
|
|
|
|
let result = Uuid::parse_string(us);
|
|
|
|
match result {
|
|
|
|
Ok(u) => Some(u),
|
|
|
|
Err(_) => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert the UUID to a hexadecimal-based string representation
|
2014-02-19 18:56:33 -08:00
|
|
|
impl fmt::Show for Uuid {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2014-05-10 14:05:06 -07:00
|
|
|
write!(f, "{}", self.to_simple_str())
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Test two UUIDs for equality
|
|
|
|
///
|
|
|
|
/// UUIDs are equal only when they are byte-for-byte identical
|
2014-05-29 17:45:07 -07:00
|
|
|
impl PartialEq for Uuid {
|
2013-07-24 23:10:15 +10:00
|
|
|
fn eq(&self, other: &Uuid) -> bool {
|
|
|
|
self.bytes == other.bytes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-31 10:43:52 -07:00
|
|
|
impl Eq for Uuid {}
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2013-10-16 21:36:41 -04:00
|
|
|
// FIXME #9845: Test these more thoroughly
|
2014-03-18 10:58:26 -07:00
|
|
|
impl<T: Encoder<E>, E> Encodable<T, E> for Uuid {
|
2014-06-09 00:00:52 -04:00
|
|
|
/// Encode a UUID as a hyphenated string
|
2014-03-18 10:58:26 -07:00
|
|
|
fn encode(&self, e: &mut T) -> Result<(), E> {
|
2014-05-12 20:33:17 -07:00
|
|
|
e.emit_str(self.to_hyphenated_str().as_slice())
|
2014-03-18 10:58:26 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: Decoder<E>, E> Decodable<T, E> for Uuid {
|
|
|
|
/// Decode a UUID from a string
|
|
|
|
fn decode(d: &mut T) -> Result<Uuid, E> {
|
2014-05-14 21:16:44 -07:00
|
|
|
Ok(from_str(try!(d.read_str()).as_slice()).unwrap())
|
2014-03-18 10:58:26 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-07-24 23:10:15 +10:00
|
|
|
/// Generates a random instance of UUID (V4 conformant)
|
|
|
|
impl rand::Rand for Uuid {
|
|
|
|
#[inline]
|
|
|
|
fn rand<R: rand::Rng>(rng: &mut R) -> Uuid {
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
let ub = rng.gen_iter::<u8>().take(16).collect::<Vec<_>>();
|
2013-07-24 23:10:15 +10:00
|
|
|
let mut uuid = Uuid{ bytes: [0, .. 16] };
|
2014-03-27 23:00:46 +11:00
|
|
|
slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
|
2013-07-24 23:10:15 +10:00
|
|
|
uuid.set_variant(VariantRFC4122);
|
|
|
|
uuid.set_version(Version4Random);
|
|
|
|
uuid
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
2014-02-03 20:02:47 +02:00
|
|
|
use super::{Uuid, VariantMicrosoft, VariantNCS, VariantRFC4122,
|
|
|
|
Version1Mac, Version2Dce, Version3Md5, Version4Random,
|
|
|
|
Version5Sha1};
|
2014-01-15 13:25:09 -08:00
|
|
|
use std::io::MemWriter;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
use std::rand;
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
#[test]
|
2014-01-18 17:08:23 +11:00
|
|
|
fn test_nil() {
|
|
|
|
let nil = Uuid::nil();
|
|
|
|
let not_nil = Uuid::new_v4();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-01-18 17:08:23 +11:00
|
|
|
assert!(nil.is_nil());
|
|
|
|
assert!(!not_nil.is_nil());
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_new() {
|
|
|
|
// Supported
|
|
|
|
let uuid1 = Uuid::new(Version4Random).unwrap();
|
|
|
|
let s = uuid1.to_simple_str();
|
|
|
|
|
|
|
|
assert!(s.len() == 32);
|
|
|
|
assert!(uuid1.get_version().unwrap() == Version4Random);
|
|
|
|
|
|
|
|
// Test unsupported versions
|
|
|
|
assert!(Uuid::new(Version1Mac) == None);
|
|
|
|
assert!(Uuid::new(Version2Dce) == None);
|
|
|
|
assert!(Uuid::new(Version3Md5) == None);
|
|
|
|
assert!(Uuid::new(Version5Sha1) == None);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_new_v4() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
|
|
|
|
assert!(uuid1.get_version().unwrap() == Version4Random);
|
|
|
|
assert!(uuid1.get_variant().unwrap() == VariantRFC4122);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_get_version() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
|
|
|
|
assert!(uuid1.get_version().unwrap() == Version4Random);
|
|
|
|
assert!(uuid1.get_version_num() == 4);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_get_variant() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
let uuid2 = Uuid::parse_string("550e8400-e29b-41d4-a716-446655440000").unwrap();
|
|
|
|
let uuid3 = Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
|
|
|
|
let uuid4 = Uuid::parse_string("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
|
|
|
|
let uuid5 = Uuid::parse_string("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
|
|
|
|
let uuid6 = Uuid::parse_string("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();
|
|
|
|
|
|
|
|
assert!(uuid1.get_variant().unwrap() == VariantRFC4122);
|
|
|
|
assert!(uuid2.get_variant().unwrap() == VariantRFC4122);
|
|
|
|
assert!(uuid3.get_variant().unwrap() == VariantRFC4122);
|
|
|
|
assert!(uuid4.get_variant().unwrap() == VariantMicrosoft);
|
|
|
|
assert!(uuid5.get_variant().unwrap() == VariantMicrosoft);
|
|
|
|
assert!(uuid6.get_variant().unwrap() == VariantNCS);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_parse_uuid_v4() {
|
2014-02-03 20:02:47 +02:00
|
|
|
use super::{ErrorInvalidCharacter, ErrorInvalidGroups,
|
|
|
|
ErrorInvalidGroupLength, ErrorInvalidLength};
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
// Invalid
|
|
|
|
assert!(Uuid::parse_string("").is_err());
|
|
|
|
assert!(Uuid::parse_string("!").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4").is_err());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4").is_err());
|
|
|
|
assert!(Uuid::parse_string("01020304-1112-2122-3132-41424344").is_err());
|
|
|
|
assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c").is_err());
|
|
|
|
assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c88").is_err());
|
|
|
|
assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0cg8").is_err());
|
|
|
|
assert!(Uuid::parse_string("67e5504410b1426%9247bb680e5fe0c8").is_err());
|
|
|
|
|
|
|
|
// Valid
|
|
|
|
assert!(Uuid::parse_string("00000000000000000000000000000000").is_ok());
|
|
|
|
assert!(Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
|
|
|
|
assert!(Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
|
|
|
|
assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok());
|
|
|
|
assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c8").is_ok());
|
|
|
|
assert!(Uuid::parse_string("01020304-1112-2122-3132-414243444546").is_ok());
|
|
|
|
assert!(Uuid::parse_string("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
|
|
|
|
|
|
|
|
// Nil
|
2014-01-18 17:08:23 +11:00
|
|
|
let nil = Uuid::nil();
|
2013-07-24 23:10:15 +10:00
|
|
|
assert!(Uuid::parse_string("00000000000000000000000000000000").unwrap() == nil);
|
|
|
|
assert!(Uuid::parse_string("00000000-0000-0000-0000-000000000000").unwrap() == nil);
|
|
|
|
|
|
|
|
// Round-trip
|
|
|
|
let uuid_orig = Uuid::new_v4();
|
2014-06-21 03:39:03 -07:00
|
|
|
let orig_str = uuid_orig.to_string();
|
2014-05-19 23:19:56 -07:00
|
|
|
let uuid_out = Uuid::parse_string(orig_str.as_slice()).unwrap();
|
2013-07-24 23:10:15 +10:00
|
|
|
assert!(uuid_orig == uuid_out);
|
|
|
|
|
|
|
|
// Test error reporting
|
|
|
|
let e = Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c").unwrap_err();
|
2014-01-19 19:21:14 +11:00
|
|
|
assert!(match e { ErrorInvalidLength(n) => n==31, _ => false });
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
let e = Uuid::parse_string("67e550X410b1426f9247bb680e5fe0cd").unwrap_err();
|
2014-01-19 19:21:14 +11:00
|
|
|
assert!(match e { ErrorInvalidCharacter(c, n) => c=='X' && n==6, _ => false });
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
let e = Uuid::parse_string("67e550-4105b1426f9247bb680e5fe0c").unwrap_err();
|
2014-01-19 19:21:14 +11:00
|
|
|
assert!(match e { ErrorInvalidGroups(n) => n==2, _ => false });
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
let e = Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4").unwrap_err();
|
2014-01-19 19:21:14 +11:00
|
|
|
assert!(match e { ErrorInvalidGroupLength(g, n, e) => g==3 && n==5 && e==4, _ => false });
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_simple_str() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
let s = uuid1.to_simple_str();
|
|
|
|
|
|
|
|
assert!(s.len() == 32);
|
2014-05-12 20:33:17 -07:00
|
|
|
assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16)));
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2014-06-21 03:39:03 -07:00
|
|
|
fn test_to_string() {
|
2013-07-24 23:10:15 +10:00
|
|
|
let uuid1 = Uuid::new_v4();
|
2014-06-21 03:39:03 -07:00
|
|
|
let s = uuid1.to_string();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(s.len() == 32);
|
2014-05-12 20:33:17 -07:00
|
|
|
assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16)));
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_hyphenated_str() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
let s = uuid1.to_hyphenated_str();
|
|
|
|
|
|
|
|
assert!(s.len() == 36);
|
2014-05-12 20:33:17 -07:00
|
|
|
assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16) || c == '-'));
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_urn_str() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
let ss = uuid1.to_urn_str();
|
2014-05-12 20:33:17 -07:00
|
|
|
let s = ss.as_slice().slice(9, ss.len());
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-05-12 20:33:17 -07:00
|
|
|
assert!(ss.as_slice().starts_with("urn:uuid:"));
|
2013-07-24 23:10:15 +10:00
|
|
|
assert!(s.len() == 36);
|
2014-05-12 20:33:17 -07:00
|
|
|
assert!(s.as_slice()
|
|
|
|
.chars()
|
|
|
|
.all(|c| c.is_digit_radix(16) || c == '-'));
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_str_matching() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
|
|
|
|
let hs = uuid1.to_hyphenated_str();
|
2014-06-21 03:39:03 -07:00
|
|
|
let ss = uuid1.to_string();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-07-04 21:55:58 +02:00
|
|
|
let hsn = String::from_chars(hs.as_slice()
|
2014-05-12 20:33:17 -07:00
|
|
|
.chars()
|
2014-03-05 15:28:08 -08:00
|
|
|
.filter(|&c| c != '-')
|
|
|
|
.collect::<Vec<char>>()
|
|
|
|
.as_slice());
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(hsn == ss);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_string_roundtrip() {
|
|
|
|
let uuid = Uuid::new_v4();
|
|
|
|
|
|
|
|
let hs = uuid.to_hyphenated_str();
|
2014-05-12 20:33:17 -07:00
|
|
|
let uuid_hs = Uuid::parse_string(hs.as_slice()).unwrap();
|
2013-07-24 23:10:15 +10:00
|
|
|
assert!(uuid_hs == uuid);
|
|
|
|
|
2014-06-21 03:39:03 -07:00
|
|
|
let ss = uuid.to_string();
|
2014-05-19 23:19:56 -07:00
|
|
|
let uuid_ss = Uuid::parse_string(ss.as_slice()).unwrap();
|
2013-07-24 23:10:15 +10:00
|
|
|
assert!(uuid_ss == uuid);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_compare() {
|
|
|
|
let uuid1 = Uuid::new_v4();
|
|
|
|
let uuid2 = Uuid::new_v4();
|
|
|
|
|
|
|
|
assert!(uuid1 == uuid1);
|
|
|
|
assert!(uuid2 == uuid2);
|
|
|
|
assert!(uuid1 != uuid2);
|
|
|
|
assert!(uuid2 != uuid1);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_fields() {
|
|
|
|
let d1: u32 = 0xa1a2a3a4;
|
|
|
|
let d2: u16 = 0xb1b2;
|
|
|
|
let d3: u16 = 0xc1c2;
|
2014-03-05 15:28:08 -08:00
|
|
|
let d4: Vec<u8> = vec!(0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8);
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-03-05 15:28:08 -08:00
|
|
|
let u = Uuid::from_fields(d1, d2, d3, d4.as_slice());
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-05-25 03:17:19 -07:00
|
|
|
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string();
|
2013-07-24 23:10:15 +10:00
|
|
|
let result = u.to_simple_str();
|
|
|
|
assert!(result == expected);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2013-09-07 11:05:48 -07:00
|
|
|
fn test_from_bytes() {
|
2014-03-05 15:28:08 -08:00
|
|
|
let b = vec!( 0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2,
|
|
|
|
0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 );
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-03-05 15:28:08 -08:00
|
|
|
let u = Uuid::from_bytes(b.as_slice()).unwrap();
|
2014-05-25 03:17:19 -07:00
|
|
|
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(u.to_simple_str() == expected);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2014-01-21 17:02:31 -08:00
|
|
|
fn test_as_bytes() {
|
2013-07-24 23:10:15 +10:00
|
|
|
let u = Uuid::new_v4();
|
2014-01-21 17:02:31 -08:00
|
|
|
let ub = u.as_bytes();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(ub.len() == 16);
|
|
|
|
assert!(! ub.iter().all(|&b| b == 0));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bytes_roundtrip() {
|
|
|
|
let b_in: [u8, ..16] = [ 0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2,
|
|
|
|
0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 ];
|
|
|
|
|
2013-09-07 11:05:48 -07:00
|
|
|
let u = Uuid::from_bytes(b_in.clone()).unwrap();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
2014-01-21 17:02:31 -08:00
|
|
|
let b_out = u.as_bytes();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(b_in == b_out);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_operator_eq() {
|
|
|
|
let u1 = Uuid::new_v4();
|
|
|
|
let u2 = u1.clone();
|
|
|
|
let u3 = Uuid::new_v4();
|
|
|
|
|
|
|
|
assert!(u1 == u1);
|
|
|
|
assert!(u1 == u2);
|
|
|
|
assert!(u2 == u1);
|
|
|
|
|
|
|
|
assert!(u1 != u3);
|
|
|
|
assert!(u3 != u1);
|
|
|
|
assert!(u2 != u3);
|
|
|
|
assert!(u3 != u2);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_rand_rand() {
|
2014-03-02 12:59:35 +11:00
|
|
|
let mut rng = rand::task_rng();
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 01:39:37 -07:00
|
|
|
let u: Uuid = rand::Rand::rand(&mut rng);
|
2014-01-21 17:02:31 -08:00
|
|
|
let ub = u.as_bytes();
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
assert!(ub.len() == 16);
|
|
|
|
assert!(! ub.iter().all(|&b| b == 0));
|
|
|
|
}
|
2013-10-16 21:36:41 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_serialize_round_trip() {
|
2014-07-29 16:31:39 -07:00
|
|
|
use serialize::json;
|
2014-02-05 08:52:54 -08:00
|
|
|
use serialize::{Encodable, Decodable};
|
2013-10-16 21:36:41 -04:00
|
|
|
|
|
|
|
let u = Uuid::new_v4();
|
2014-07-29 16:31:39 -07:00
|
|
|
let s = json::encode(&u);
|
|
|
|
let u2 = json::decode(s.as_slice()).unwrap();
|
2013-10-16 21:36:41 -04:00
|
|
|
assert_eq!(u, u2);
|
|
|
|
}
|
2013-12-23 23:44:58 -08:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_iterbytes_impl_for_uuid() {
|
2014-05-29 19:03:06 -07:00
|
|
|
use std::collections::HashSet;
|
2013-12-23 23:44:58 -08:00
|
|
|
let mut set = HashSet::new();
|
|
|
|
let id1 = Uuid::new_v4();
|
|
|
|
let id2 = Uuid::new_v4();
|
|
|
|
set.insert(id1);
|
|
|
|
assert!(set.contains(&id1));
|
|
|
|
assert!(!set.contains(&id2));
|
|
|
|
}
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod bench {
|
2014-02-14 09:49:11 +08:00
|
|
|
extern crate test;
|
2014-04-01 09:16:35 +08:00
|
|
|
use self::test::Bencher;
|
2014-02-03 20:02:47 +02:00
|
|
|
use super::Uuid;
|
2013-07-24 23:10:15 +10:00
|
|
|
|
|
|
|
#[bench]
|
2014-04-01 09:16:35 +08:00
|
|
|
pub fn create_uuids(b: &mut Bencher) {
|
|
|
|
b.iter(|| {
|
2013-07-24 23:10:15 +10:00
|
|
|
Uuid::new_v4();
|
2013-11-21 19:20:48 -08:00
|
|
|
})
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[bench]
|
2014-06-21 03:39:03 -07:00
|
|
|
pub fn uuid_to_string(b: &mut Bencher) {
|
2013-07-24 23:10:15 +10:00
|
|
|
let u = Uuid::new_v4();
|
2014-04-01 09:16:35 +08:00
|
|
|
b.iter(|| {
|
2014-06-21 03:39:03 -07:00
|
|
|
u.to_string();
|
2013-11-21 19:20:48 -08:00
|
|
|
})
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
#[bench]
|
2014-04-01 09:16:35 +08:00
|
|
|
pub fn parse_str(b: &mut Bencher) {
|
2013-07-24 23:10:15 +10:00
|
|
|
let s = "urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4";
|
2014-04-01 09:16:35 +08:00
|
|
|
b.iter(|| {
|
2014-01-30 14:28:20 -08:00
|
|
|
Uuid::parse_string(s).unwrap();
|
2013-11-21 19:20:48 -08:00
|
|
|
})
|
2013-07-24 23:10:15 +10:00
|
|
|
}
|
|
|
|
}
|