1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// 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 displayed in a readable string form as a sequence of hexadecimal digits,
//! 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.
//!
//! # Dependencies
//!
//! This crate by default has no dependencies and is `#![no_std]` compatible.
//! The following Cargo features, however, can be used to enable various pieces
//! of functionality.
//!
//! * `use_std` - adds in functionality available when linking to the standard
//!   library, currently this is only the `impl Error for ParseError`.
//! * `v1` - adds the `Uuid::new_v1` function and the ability to create a V1
//!   using a `UUIDV1Context` and a timestamp from `time::timespec`
//! * `v3` - adds the `Uuid::new_v3` function and the ability to create a V3
//!   UUID based on the MD5 hash of some data.
//! * `v4` - adds the `Uuid::new_v4` function and the ability to randomly
//!   generate a `Uuid`.
//! * `v5` - adds the `Uuid::new_v5` function and the ability to create a V5
//!   UUID based on the SHA1 hash of some data.
//! * `rustc-serialize` - adds the ability to serialize and deserialize a `Uuid`
//!   using the `rustc-serialize` crate.
//! * `serde` - adds the ability to serialize and deserialize a `Uuid` using the
//!   `serde` crate.
//!
//! By default, `uuid` can be depended on with:
//!
//! ```toml
//! [dependencies]
//! uuid = "0.4"
//! ```
//!
//! To activate various features, use syntax like:
//!
//! ```toml
//! [dependencies]
//! uuid = { version = "0.4", features = ["serde", "v4"] }
//! ```
//!
//! # Examples
//!
//! To parse a UUID given in the simple format and print it as a urn:
//!
//! ```rust
//! use uuid::Uuid;
//!
//! fn main() {
//!     let my_uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
//!     println!("{}", my_uuid.urn());
//! }
//! ```
//!
//! To create a new random (V4) UUID and print it out in hexadecimal form:
//!
//! ```ignore,rust
//! // Note that this requires the `v4` feature enabled in the uuid crate.
//!
//! use uuid::Uuid;
//!
//! fn main() {
//!     let my_uuid = Uuid::new_v4();
//!     println!("{}", my_uuid);
//! }
//! ```
//!
//! # 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)

#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://www.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/uuid/")]

#![deny(warnings)]
#![no_std]

#[cfg(feature = "v3")]
extern crate md5;
#[cfg(any(feature = "v4",
          feature = "v1"))]
extern crate rand;
#[cfg(feature = "v5")]
extern crate sha1;

use core::fmt;
use core::hash;
use core::str::FromStr;

// rustc-serialize and serde link to std, so go ahead an pull in our own std
// support in those situations as well.
#[cfg(any(feature = "use_std",
          feature = "rustc-serialize",
          feature = "serde"))]
mod std_support;
#[cfg(feature = "rustc-serialize")]
mod rustc_serialize;
#[cfg(feature = "serde")]
mod serde;

#[cfg(feature = "v1")]
use core::sync::atomic::{AtomicUsize, Ordering};

#[cfg(feature = "v1")]
use rand::{Rand};

#[cfg(any(feature = "v4",
          feature = "v1"))]
use rand::{Rng};

#[cfg(feature = "v5")]
use sha1::Sha1;

/// A 128-bit (16 byte) buffer containing the ID.
pub type UuidBytes = [u8; 16];

/// The version of the UUID, denoting the generating algorithm.
#[derive(PartialEq, Copy, Clone)]
pub enum UuidVersion {
    /// Version 1: MAC address
    Mac = 1,
    /// Version 2: DCE Security
    Dce = 2,
    /// Version 3: MD5 hash
    Md5 = 3,
    /// Version 4: Random
    Random = 4,
    /// Version 5: SHA-1 hash
    Sha1 = 5,
}

/// The reserved variants of UUIDs.
#[derive(PartialEq, Copy, Clone)]
pub enum UuidVariant {
    /// Reserved by the NCS for backward compatibility
    NCS,
    /// As described in the RFC4122 Specification (default)
    RFC4122,
    /// Reserved by Microsoft for backward compatibility
    Microsoft,
    /// Reserved for future expansion
    Future,
}

/// A Universally Unique Identifier (UUID).
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Uuid {
    /// The 128-bit number stored in 16 bytes
    bytes: UuidBytes,
}

/// An adaptor for formatting a `Uuid` as a simple string.
pub struct Simple<'a> {
    inner: &'a Uuid,
}

/// An adaptor for formatting a `Uuid` as a hyphenated string.
pub struct Hyphenated<'a> {
    inner: &'a Uuid,
}

/// A UUID of the namespace of fully-qualified domain names
pub const NAMESPACE_DNS: Uuid = Uuid {
    bytes: [0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1,
            0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8]
};

/// A UUID of the namespace of URLs
pub const NAMESPACE_URL: Uuid = Uuid {
    bytes: [0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1,
            0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8]
};

/// A UUID of the namespace of ISO OIDs
pub const NAMESPACE_OID: Uuid = Uuid {
    bytes: [0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1,
            0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8]
};

/// A UUID of the namespace of X.500 DNs (in DER or a text output format)
pub const NAMESPACE_X500: Uuid = Uuid {
    bytes: [0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1,
            0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8]
};

/// The number of 100 ns ticks between 
/// the UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00
#[cfg(feature = "v1")]
const UUID_TICKS_BETWEEN_EPOCHS : u64 = 0x01B21DD213814000;

/// An adaptor for formatting a `Uuid` as a URN string.
pub struct Urn<'a> {
    inner: &'a Uuid,
}

/// A stateful context for the v1 generator to help ensure process-wide uniqueness
#[cfg(feature = "v1")]
pub struct UuidV1Context {
    count: AtomicUsize,
}

#[cfg(feature = "v1")]
impl UuidV1Context {

    /// Creates a thread-safe, internally mutable context to help ensure uniqueness
    ///
    /// This is a context which can be shared across threads.  It maintains an internal
    /// counter that is incremented at every request, the value ends up in the clock_seq
    /// portion of the V1 uuid (the fourth group).  This will improve the probability
    /// that the UUID is unique across the process.
    pub fn new(count : u16) -> UuidV1Context {
        UuidV1Context {
            count: AtomicUsize::new(count as usize)
        }
    }
}

#[cfg(feature = "v1")]
impl Rand for UuidV1Context {

    /// Creates a `UuidV1Context` that has been initialized to a random value
    ///
    /// For usage, see `UuidV1Context::new` and `Uuid::new_v1`
    fn rand<R: Rng>(rng: &mut R) -> Self {
        UuidV1Context {
            count: AtomicUsize::new(rng.gen())
        }
    }
}

/// Error details for string parsing failures.
#[allow(missing_docs)]
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ParseError {
    InvalidLength(usize),
    InvalidCharacter(char, usize),
    InvalidGroups(usize),
    InvalidGroupLength(usize, usize, u8),
}

const SIMPLE_LENGTH: usize = 32;
const HYPHENATED_LENGTH: usize = 36;

/// Converts a ParseError to a string.
impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseError::InvalidLength(found) => {
                write!(f,
                       "Invalid length; expecting {} or {} chars, found {}",
                       SIMPLE_LENGTH, HYPHENATED_LENGTH, found)
            }
            ParseError::InvalidCharacter(found, pos) => {
                write!(f,
                       "Invalid character; found `{}` (0x{:02x}) at offset {}",
                       found,
                       found as usize,
                       pos)
            }
            ParseError::InvalidGroups(found) => {
                write!(f,
                       "Malformed; wrong number of groups: expected 1 or 5, found {}",
                       found)
            }
            ParseError::InvalidGroupLength(group, found, expecting) => {
                write!(f,
                       "Malformed; length of group {} was {}, expecting {}",
                       group,
                       found,
                       expecting)
            }
        }
    }
}

// Length of each hyphenated group in hex digits.
const GROUP_LENS: [u8; 5] = [8, 4, 4, 4, 12];
// Accumulated length of each hyphenated group in hex digits.
const ACC_GROUP_LENS: [u8; 5] = [8, 12, 16, 20, 32];

impl Uuid {
    /// The 'nil UUID'.
    ///
    /// The nil UUID is special form of UUID that is specified to have all
    /// 128 bits set to zero, as defined in [IETF RFC 4122 Section 4.1.7][RFC].
    ///
    /// [RFC]: https://tools.ietf.org/html/rfc4122.html#section-4.1.7
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    ///
    /// assert_eq!(uuid.hyphenated().to_string(),
    ///            "00000000-0000-0000-0000-000000000000");
    /// ```
    pub fn nil() -> Uuid {
        Uuid { bytes: [0; 16] }
    }

    /// Creates a new `Uuid`.
    ///
    /// Note that not all versions can be generated currently and `None` will be
    /// returned if the specified version cannot be generated.
    ///
    /// To generate a random UUID (`UuidVersion::Random`), then the `v4`
    /// feature must be enabled for this crate.
    pub fn new(v: UuidVersion) -> Option<Uuid> {
        match v {
            #[cfg(feature = "v4")]
            UuidVersion::Random => Some(Uuid::new_v4()),
            _ => None,
        }
    }
    
    /// Creates a new `Uuid` (version 1 style) using a time value + seq + NodeID
    ///
    /// This expects two values representing a monotonically increasing value 
    /// as well as a unique 6 byte NodeId, and a `UuidV1Context`
    /// This function is only guaranteed to produce unique values if the following
    /// conditions hold: 
    /// 1. The NodeID is unique for this process.
    /// 2. The Context is shared across all threads which are generating V1 UUIDs
    /// 3. The supplied seconds+nsecs values are monotonically increasing.
    ///
    /// The NodeID must be exactly 6 bytes long. If the NodeID is not a valid length
    /// this will return a `ParseError::InvalidLength`
    ///
    /// The function is not guaranteed to produce monotonically increasing values
    /// however.  There is a slight possibility that two successive equal time values
    /// could be supplied and the sequence counter wraps back over to 0. 
    ///
    /// If uniqueness and monotonicity is required, the user is responsibile for ensuring
    /// that the time value always increases between calls. 
    /// (including between restarts of the process and device)
    ///
    /// Note that usage of this method requires the `v1` feature of this crate
    /// to be enabled.
    ///
    /// # Examples
    /// Basic usage:
    /// #[cfg(feature = "v1")]
    /// ```
    /// use uuid::{Uuid, UuidV1Context};
    ///
    /// let ctx = UuidV1Context::new(42);
    /// let v1uuid = Uuid::new_v1(&ctx, 1497624119, 1234, &[1,2,3,4,5,6]).unwrap();
    ///
    /// assert_eq!(v1uuid.hyphenated().to_string(), "f3b4958c-52a1-11e7-802a-010203040506");
    /// ```
    #[cfg(feature = "v1")]
    pub fn new_v1(context: &UuidV1Context, seconds: u64, nsecs: u32, node: &[u8]) -> Result<Uuid, ParseError> {
        if node.len() != 6 {
            return Err(ParseError::InvalidLength(node.len()))
        }
        let count = (context.count.fetch_add(1, Ordering::SeqCst) & 0xffff) as u16;
        let timestamp = seconds * 10_000_000 + (nsecs / 100) as u64;
        let uuidtime = timestamp + UUID_TICKS_BETWEEN_EPOCHS; 
        let time_low : u32 = (uuidtime & 0xFFFFFFFF) as u32;
        let time_mid : u16 = ((uuidtime >> 32) & 0xFFFF) as u16; 
        let time_hi_and_ver : u16 = (((uuidtime >> 48) & 0x0FFF) as u16) | (1 << 12);
        let mut d4 = [0_u8; 8];
        d4[0] = (((count & 0x3F00) >> 8) as u8) | 0x80;
        d4[1] = (count & 0xFF) as u8;
        d4[2..].copy_from_slice(node);
        Uuid::from_fields(time_low, time_mid, time_hi_and_ver, &d4)
    }


    /// Creates a UUID using a name from a namespace, based on the MD5 hash.
    ///
    /// A number of namespaces are available as constants in this crate:
    ///
    /// * `NAMESPACE_DNS`
    /// * `NAMESPACE_URL`
    /// * `NAMESPACE_OID`
    /// * `NAMESPACE_X500`
    ///
    /// Note that usage of this method requires the `v3` feature of this crate
    /// to be enabled.
    #[cfg(feature = "v3")]
    pub fn new_v3(namespace: &Uuid, name: &str) -> Uuid {
        let mut ctx = md5::Context::new();
        ctx.consume(namespace.as_bytes());
        ctx.consume(name.as_bytes());
        let digest = ctx.compute();
        let mut uuid = Uuid { bytes: [0; 16] };
        copy_memory(&mut uuid.bytes, &digest[..16]);
        uuid.set_variant(UuidVariant::RFC4122);
        uuid.set_version(UuidVersion::Md5);
        uuid
    }
    
    /// Creates a random `Uuid`.
    ///
    /// This uses the `rand` crate's default task RNG as the source of random numbers.
    /// If you'd like to use a custom generator, don't use this method: use the
    /// [`rand::Rand trait`]'s `rand()` method instead.
    ///
    /// [`rand::Rand trait`]: ../../rand/rand/trait.Rand.html#tymethod.rand
    ///
    /// Note that usage of this method requires the `v4` feature of this crate
    /// to be enabled.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::new_v4();
    /// ```
    #[cfg(feature = "v4")]
    pub fn new_v4() -> Uuid {
        rand::thread_rng().gen()
    }

    /// Creates a UUID using a name from a namespace, based on the SHA-1 hash.
    ///
    /// A number of namespaces are available as constants in this crate:
    ///
    /// * `NAMESPACE_DNS`
    /// * `NAMESPACE_URL`
    /// * `NAMESPACE_OID`
    /// * `NAMESPACE_X500`
    ///
    /// Note that usage of this method requires the `v5` feature of this crate
    /// to be enabled.
    #[cfg(feature = "v5")]
    pub fn new_v5(namespace: &Uuid, name: &str) -> Uuid {
        let mut hash = Sha1::new();
        hash.update(namespace.as_bytes());
        hash.update(name.as_bytes());
        let buffer = hash.digest().bytes();
        let mut uuid = Uuid { bytes: [0; 16] };
        copy_memory(&mut uuid.bytes, &buffer[..16]);
        uuid.set_variant(UuidVariant::RFC4122);
        uuid.set_version(UuidVersion::Sha1);
        uuid
    }

    /// Creates a `Uuid` from four field values.
    ///
    /// # Errors
    ///
    /// This function will return an error if `d4`'s length is not 8 bytes.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let d4 = [12, 3, 9, 56, 54, 43, 8, 9];
    ///
    /// let uuid = Uuid::from_fields(42, 12, 5, &d4);
    /// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
    ///
    /// let expected_uuid = Ok(String::from("0000002a-000c-0005-0c03-0938362b0809"));
    ///
    /// assert_eq!(expected_uuid, uuid);
    /// ```
    ///
    /// An invalid length:
    ///
    /// ```
    /// use uuid::Uuid;
    /// use uuid::ParseError;
    ///
    /// let d4 = [12];
    ///
    /// let uuid = Uuid::from_fields(42, 12, 5, &d4);
    ///
    /// let expected_uuid = Err(ParseError::InvalidLength(1));
    ///
    /// assert_eq!(expected_uuid, uuid);
    /// ```
    pub fn from_fields(d1: u32,
                       d2: u16,
                       d3: u16,
                       d4: &[u8]) -> Result<Uuid, ParseError>  {
        if d4.len() != 8 {
            return Err(ParseError::InvalidLength(d4.len()))
        }

        Ok(Uuid {
            bytes: [
                (d1 >> 24) as u8,
                (d1 >> 16) as u8,
                (d1 >>  8) as u8,
                (d1 >>  0) as u8,
                (d2 >>  8) as u8,
                (d2 >>  0) as u8,
                (d3 >>  8) as u8,
                (d3 >>  0) as u8,
                d4[0], d4[1], d4[2], d4[3], d4[4], d4[5], d4[6], d4[7]
            ],
        })
    }

    /// Creates a `Uuid` using the supplied bytes.
    ///
    /// # Errors
    ///
    /// This function will return an error if `b` has any length other than 16.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let bytes = [4, 54, 67, 12, 43, 2, 98, 76,
    ///              32, 50, 87, 5, 1, 33, 43, 87];
    ///
    /// let uuid = Uuid::from_bytes(&bytes);
    /// let uuid = uuid.map(|uuid| uuid.hyphenated().to_string());
    ///
    /// let expected_uuid = Ok(String::from("0436430c-2b02-624c-2032-570501212b57"));
    ///
    /// assert_eq!(expected_uuid, uuid);
    /// ```
    ///
    /// An incorrect number of bytes:
    ///
    /// ```
    /// use uuid::Uuid;
    /// use uuid::ParseError;
    ///
    /// let bytes = [4, 54, 67, 12, 43, 2, 98, 76];
    ///
    /// let uuid = Uuid::from_bytes(&bytes);
    ///
    /// let expected_uuid = Err(ParseError::InvalidLength(8));
    ///
    /// assert_eq!(expected_uuid, uuid);
    /// ```
    pub fn from_bytes(b: &[u8]) -> Result<Uuid, ParseError> {
        let len = b.len();
        if len != 16 {
            return Err(ParseError::InvalidLength(len));
        }

        let mut uuid = Uuid { bytes: [0; 16] };
        copy_memory(&mut uuid.bytes, b);
        Ok(uuid)
    }

    /// Specifies the variant of the UUID structure
    #[allow(dead_code)]
    fn set_variant(&mut self, v: UuidVariant) {
        // Octet 8 contains the variant in the most significant 3 bits
        self.bytes[8] = match v {
            UuidVariant::NCS => self.bytes[8] & 0x7f,                // b0xx...
            UuidVariant::RFC4122 => (self.bytes[8] & 0x3f) | 0x80,   // b10x...
            UuidVariant::Microsoft => (self.bytes[8] & 0x1f) | 0xc0, // b110...
            UuidVariant::Future => (self.bytes[8] & 0x1f) | 0xe0,    // b111...
        }
    }

    /// 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> {
        match self.bytes[8] {
            x if x & 0x80 == 0x00 => Some(UuidVariant::NCS),
            x if x & 0xc0 == 0x80 => Some(UuidVariant::RFC4122),
            x if x & 0xe0 == 0xc0 => Some(UuidVariant::Microsoft),
            x if x & 0xe0 == 0xe0 => Some(UuidVariant::Future),
            _ => None,
        }
    }

    /// Specifies the version number of the `Uuid`.
    #[allow(dead_code)]
    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) -> usize {
        (self.bytes[6] >> 4) as usize
    }

    /// Returns the version of the `Uuid`.
    ///
    /// This represents the algorithm used to generate the contents
    pub fn get_version(&self) -> Option<UuidVersion> {
        let v = self.bytes[6] >> 4;
        match v {
            1 => Some(UuidVersion::Mac),
            2 => Some(UuidVersion::Dce),
            3 => Some(UuidVersion::Md5),
            4 => Some(UuidVersion::Random),
            5 => Some(UuidVersion::Sha1),
            _ => None,
        }
    }

    /// Return an array of 16 octets containing the UUID data
    ///
    /// # Examples
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.as_bytes(), &[0; 16]);
    ///
    /// let uuid = Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8").unwrap();
    /// assert_eq!(uuid.as_bytes(),
    ///            &[147, 109, 160, 31, 154, 189, 77, 157,
    ///              128, 199, 2, 175, 133, 200, 34, 168]);
    /// ```
    pub fn as_bytes(&self) -> &[u8; 16] {
        &self.bytes
    }

    /// Returns a wrapper which when formatted via `fmt::Display` will format a
    /// string of 32 hexadecimal digits.
    ///
    /// # Examples
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.simple().to_string(),
    ///            "00000000000000000000000000000000");
    /// ```
    pub fn simple(&self) -> Simple {
        Simple { inner: self }
    }

    /// Returns a wrapper which when formatted via `fmt::Display` will format a
    /// string of hexadecimal digits separated into groups with a hyphen.
    ///
    /// # Examples
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.hyphenated().to_string(),
    ///            "00000000-0000-0000-0000-000000000000");
    /// ```
    pub fn hyphenated(&self) -> Hyphenated {
        Hyphenated { inner: self }
    }

    /// Returns a wrapper which when formatted via `fmt::Display` will format a
    /// string of the UUID as a full URN string.
    ///
    /// # Examples
    ///
    /// ```
    /// use uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.urn().to_string(),
    ///            "urn:uuid:00000000-0000-0000-0000-000000000000");
    /// ```
    pub fn urn(&self) -> Urn {
        Urn { inner: self }
    }


    /// Returns an Optional Tuple of (u64, u16) representing the timestamp and 
    /// counter portion of a V1 UUID.  If the supplied UUID is not V1, this 
    /// will return None
    pub fn to_timestamp(&self) -> Option<(u64, u16)> {

        if self.get_version().map(|v| v != UuidVersion::Mac).unwrap_or(true) {
            return None;
        }

        let ts : u64 = (((self.bytes[6] & 0x0F) as u64) << 56)
                     |  ((self.bytes[7] as u64) << 48)
                     |  ((self.bytes[4] as u64) << 40)
                     |  ((self.bytes[5] as u64) << 32)
                     |  ((self.bytes[0] as u64) << 24)
                     |  ((self.bytes[1] as u64) << 16)
                     |  ((self.bytes[2] as u64) << 8)
                     |    self.bytes[3] as u64;

        let count : u16 = (((self.bytes[8] & 0x3F) as u16) << 8) | self.bytes[9] as u16;

        Some((ts, count))
    }


    /// 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_str(mut input: &str) -> Result<Uuid, ParseError> {
        // Ensure length is valid for any of the supported formats
        let len = input.len();
        if len == (HYPHENATED_LENGTH + 9) && input.starts_with("urn:uuid:") {
            input = &input[9..];
        } else if len != SIMPLE_LENGTH && len != HYPHENATED_LENGTH {
            return Err(ParseError::InvalidLength(len));
        }

        // `digit` counts only hexadecimal digits, `i_char` counts all chars.
        let mut digit = 0;
        let mut group = 0;
        let mut acc = 0;
        let mut buffer = [0u8; 16];

        for (i_char, chr) in input.bytes().enumerate() {
            if digit as usize >= SIMPLE_LENGTH && group != 4 {
                if group == 0 {
                    return Err(ParseError::InvalidLength(len));
                }
                return Err(ParseError::InvalidGroups(group + 1));
            }

            if digit % 2 == 0 {
                // First digit of the byte.
                match chr {
                    // Calulate upper half.
                    b'0'...b'9' => acc = chr - b'0',
                    b'a'...b'f' => acc = chr - b'a' + 10,
                    b'A'...b'F' => acc = chr - b'A' + 10,
                    // Found a group delimiter
                    b'-' => {
                        if ACC_GROUP_LENS[group] != digit {
                            // Calculate how many digits this group consists of in the input.
                            let found = if group > 0 {
                                digit - ACC_GROUP_LENS[group - 1]
                            } else {
                                digit
                            };
                            return Err(ParseError::InvalidGroupLength(group,
                                                                      found as usize,
                                                                      GROUP_LENS[group]));
                        }
                        // Next group, decrement digit, it is incremented again at the bottom.
                        group += 1;
                        digit -= 1;
                    }
                    _ => return Err(ParseError::InvalidCharacter(input[i_char..].chars().next().unwrap(), i_char)),
                }
            } else {
                // Second digit of the byte, shift the upper half.
                acc *= 16;
                match chr {
                    b'0'...b'9' => acc += chr - b'0',
                    b'a'...b'f' => acc += chr - b'a' + 10,
                    b'A'...b'F' => acc += chr - b'A' + 10,
                    b'-' => {
                        // The byte isn't complete yet.
                        let found = if group > 0 {
                            digit - ACC_GROUP_LENS[group - 1]
                        } else {
                            digit
                        };
                        return Err(ParseError::InvalidGroupLength(group,
                                                                  found as usize,
                                                                  GROUP_LENS[group]));
                    }
                    _ => return Err(ParseError::InvalidCharacter(input[i_char..].chars().next().unwrap(), i_char)),
                }
                buffer[(digit / 2) as usize] = acc;
            }
            digit += 1;
        }

        // Now check the last group.
        if ACC_GROUP_LENS[4] != digit {
            return Err(ParseError::InvalidGroupLength(group,
                                                      (digit - ACC_GROUP_LENS[3]) as usize,
                                                      GROUP_LENS[4]));
        }

        Ok(Uuid::from_bytes(&mut buffer).unwrap())
    }

    /// Tests if the UUID is nil
    pub fn is_nil(&self) -> bool {
        self.bytes.iter().all(|&b| b == 0)
    }
}

fn copy_memory(dst: &mut [u8], src: &[u8]) {
    for (slot, val) in dst.iter_mut().zip(src.iter()) {
        *slot = *val;
    }
}

impl Default for Uuid {
    /// Returns the nil UUID, which is all zeroes
    fn default() -> Uuid {
        Uuid::nil()
    }
}

impl FromStr for Uuid {
    type Err = ParseError;

    /// Parse a hex string and interpret as a `Uuid`.
    ///
    /// Accepted formats are a sequence of 32 hexadecimal characters,
    /// with or without hyphens (grouped as 8, 4, 4, 4, 12).
    fn from_str(us: &str) -> Result<Uuid, ParseError> {
        Uuid::parse_str(us)
    }
}

impl fmt::Debug for Uuid {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Uuid(\"{}\")", self.hyphenated())
    }
}

impl fmt::Display for Uuid {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.hyphenated().fmt(f)
    }
}

impl hash::Hash for Uuid {
    fn hash<S: hash::Hasher>(&self, state: &mut S) {
        self.bytes.hash(state)
    }
}

impl<'a> fmt::Display for Simple<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for byte in self.inner.bytes.iter() {
            try!(write!(f, "{:02x}", byte));
        }
        Ok(())
    }
}

impl<'a> fmt::Display for Hyphenated<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let data1 = ((self.inner.bytes[0] as u32) << 24) |
                    ((self.inner.bytes[1] as u32) << 16) |
                    ((self.inner.bytes[2] as u32) <<  8) |
                    ((self.inner.bytes[3] as u32) <<  0);
        let data2 = ((self.inner.bytes[4] as u16) <<  8) |
                    ((self.inner.bytes[5] as u16) <<  0);
        let data3 = ((self.inner.bytes[6] as u16) <<  8) |
                    ((self.inner.bytes[7] as u16) <<  0);

        write!(f, "{:08x}-\
                   {:04x}-\
                   {:04x}-\
                   {:02x}{:02x}-\
                   {:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
               data1,
               data2,
               data3,
               self.inner.bytes[8],
               self.inner.bytes[9],
               self.inner.bytes[10],
               self.inner.bytes[11],
               self.inner.bytes[12],
               self.inner.bytes[13],
               self.inner.bytes[14],
               self.inner.bytes[15])
    }
}

impl<'a> fmt::Display for Urn<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "urn:uuid:{}", self.inner.hyphenated())
    }
}

/// Generates a random `Uuid` (V4 conformant).
#[cfg(feature = "v4")]
impl rand::Rand for Uuid {
    fn rand<R: rand::Rng>(rng: &mut R) -> Uuid {
        let mut uuid = Uuid { bytes: [0; 16] };
        rng.fill_bytes(&mut uuid.bytes);
        uuid.set_variant(UuidVariant::RFC4122);
        uuid.set_version(UuidVersion::Random);
        uuid
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use self::std::prelude::v1::*;

    use super::{NAMESPACE_DNS, NAMESPACE_URL, NAMESPACE_OID, NAMESPACE_X500};
    use super::{Uuid, UuidVariant, UuidVersion};

    #[cfg(feature = "v4")]
    use rand;

    fn new() -> Uuid {
        Uuid::parse_str("F9168C5E-CEB2-4FAA-B6BF-329BF39FA1E4").unwrap()
    }

    fn new2() -> Uuid {
        Uuid::parse_str("F9168C5E-CEB2-4FAB-B6BF-329BF39FA1E4").unwrap()
    }

    #[cfg(feature = "v3")]
    static FIXTURE_V3: &'static [(&'static Uuid, &'static str, &'static str)] = &[
        (&NAMESPACE_DNS, "example.org",    "04738bdf-b25a-3829-a801-b21a1d25095b"),
        (&NAMESPACE_DNS, "rust-lang.org",  "c6db027c-615c-3b4d-959e-1a917747ca5a"),
        (&NAMESPACE_DNS, "42",             "5aab6e0c-b7d3-379c-92e3-2bfbb5572511"),
        (&NAMESPACE_DNS, "lorem ipsum",    "4f8772e9-b59c-3cc9-91a9-5c823df27281"),
        (&NAMESPACE_URL, "example.org",    "39682ca1-9168-3da2-a1bb-f4dbcde99bf9"),
        (&NAMESPACE_URL, "rust-lang.org",  "7ed45aaf-e75b-3130-8e33-ee4d9253b19f"),
        (&NAMESPACE_URL, "42",             "08998a0c-fcf4-34a9-b444-f2bfc15731dc"),
        (&NAMESPACE_URL, "lorem ipsum",    "e55ad2e6-fb89-34e8-b012-c5dde3cd67f0"),
        (&NAMESPACE_OID, "example.org",    "f14eec63-2812-3110-ad06-1625e5a4a5b2"),
        (&NAMESPACE_OID, "rust-lang.org",  "6506a0ec-4d79-3e18-8c2b-f2b6b34f2b6d"),
        (&NAMESPACE_OID, "42",             "ce6925a5-2cd7-327b-ab1c-4b375ac044e4"),
        (&NAMESPACE_OID, "lorem ipsum",    "5dd8654f-76ba-3d47-bc2e-4d6d3a78cb09"),
        (&NAMESPACE_X500, "example.org",   "64606f3f-bd63-363e-b946-fca13611b6f7"),
        (&NAMESPACE_X500, "rust-lang.org", "bcee7a9c-52f1-30c6-a3cc-8c72ba634990"),
        (&NAMESPACE_X500, "42",            "c1073fa2-d4a6-3104-b21d-7a6bdcf39a23"),
        (&NAMESPACE_X500, "lorem ipsum",   "02f09a3f-1624-3b1d-8409-44eff7708208"),
    ];


    #[cfg(feature = "v5")]
    static FIXTURE_V5: &'static [(&'static Uuid, &'static str, &'static str)] = &[
        (&NAMESPACE_DNS, "example.org",    "aad03681-8b63-5304-89e0-8ca8f49461b5"),
        (&NAMESPACE_DNS, "rust-lang.org",  "c66bbb60-d62e-5f17-a399-3a0bd237c503"),
        (&NAMESPACE_DNS, "42",             "7c411b5e-9d3f-50b5-9c28-62096e41c4ed"),
        (&NAMESPACE_DNS, "lorem ipsum",    "97886a05-8a68-5743-ad55-56ab2d61cf7b"),
        (&NAMESPACE_URL, "example.org",    "54a35416-963c-5dd6-a1e2-5ab7bb5bafc7"),
        (&NAMESPACE_URL, "rust-lang.org",  "c48d927f-4122-5413-968c-598b1780e749"),
        (&NAMESPACE_URL, "42",             "5c2b23de-4bad-58ee-a4b3-f22f3b9cfd7d"),
        (&NAMESPACE_URL, "lorem ipsum",    "15c67689-4b85-5253-86b4-49fbb138569f"),
        (&NAMESPACE_OID, "example.org",    "34784df9-b065-5094-92c7-00bb3da97a30"),
        (&NAMESPACE_OID, "rust-lang.org",  "8ef61ecb-977a-5844-ab0f-c25ef9b8d5d6"),
        (&NAMESPACE_OID, "42",             "ba293c61-ad33-57b9-9671-f3319f57d789"),
        (&NAMESPACE_OID, "lorem ipsum",    "6485290d-f79e-5380-9e64-cb4312c7b4a6"),
        (&NAMESPACE_X500, "example.org",   "e3635e86-f82b-5bbc-a54a-da97923e5c76"),
        (&NAMESPACE_X500, "rust-lang.org", "26c9c3e9-49b7-56da-8b9f-a0fb916a71a3"),
        (&NAMESPACE_X500, "42",            "e4b88014-47c6-5fe0-a195-13710e5f6e27"),
        (&NAMESPACE_X500, "lorem ipsum",   "b11f79a5-1e6d-57ce-a4b5-ba8531ea03d0"),
    ];

    #[test]
    fn test_nil() {
        let nil = Uuid::nil();
        let not_nil = new();

        assert!(nil.is_nil());
        assert!(!not_nil.is_nil());
    }

    #[test]
    fn test_new() {
        if cfg!(feature = "v4") {
            let uuid1 = Uuid::new(UuidVersion::Random).unwrap();
            let s = uuid1.simple().to_string();

            assert!(s.len() == 32);
            assert!(uuid1.get_version().unwrap() == UuidVersion::Random);
        } else {
            assert!(Uuid::new(UuidVersion::Random).is_none());
        }

        // Test unsupported versions
        assert!(Uuid::new(UuidVersion::Mac) == None);
        assert!(Uuid::new(UuidVersion::Dce) == None);
        assert!(Uuid::new(UuidVersion::Md5) == None);
        assert!(Uuid::new(UuidVersion::Sha1) == None);
    }
    
    #[cfg(feature = "v1")]
    #[test]
    fn test_new_v1() {
        use UuidV1Context;
        let time : u64 = 1_496_854_535;
        let timefrac : u32 = 812_946_000;
        let node = [1,2,3,4,5,6];
        let ctx = UuidV1Context::new(0);
        let uuid = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
        assert!(uuid.get_version().unwrap() == UuidVersion::Mac);
        assert!(uuid.get_variant().unwrap() == UuidVariant::RFC4122);
        assert_eq!(uuid.hyphenated().to_string(), "20616934-4ba2-11e7-8000-010203040506");
        let uuid2 = Uuid::new_v1(&ctx, time, timefrac, &node[..]).unwrap();
        assert_eq!(uuid2.hyphenated().to_string(), "20616934-4ba2-11e7-8001-010203040506");

        let ts = uuid.to_timestamp().unwrap();
        assert_eq!(ts.0 - 0x01B21DD213814000, 1_496_854_535_812_946_0);
        assert_eq!(ts.1, 0);
        assert_eq!(uuid2.to_timestamp().unwrap().1, 1);
    }

    #[cfg(feature = "v3")]
    #[test]
    fn test_new_v3() {
        for &(ref ns, ref name, _) in FIXTURE_V3 {
            let uuid = Uuid::new_v3(*ns, *name);
            assert!(uuid.get_version().unwrap() == UuidVersion::Md5);
            assert!(uuid.get_variant().unwrap() == UuidVariant::RFC4122);
        }
    }

    #[test]
    #[cfg(feature = "v4")]
    fn test_new_v4() {
        let uuid1 = Uuid::new_v4();

        assert!(uuid1.get_version().unwrap() == UuidVersion::Random);
        assert!(uuid1.get_variant().unwrap() == UuidVariant::RFC4122);
    }

    #[cfg(feature = "v5")]
    #[test]
    fn test_new_v5() {
        for &(ref ns, ref name, _) in FIXTURE_V5 {
            let uuid = Uuid::new_v5(*ns, *name);
            assert!(uuid.get_version().unwrap() == UuidVersion::Sha1);
            assert!(uuid.get_variant().unwrap() == UuidVariant::RFC4122);
        }
    }

    #[test]
    fn test_predefined_namespaces() {
        assert_eq!(NAMESPACE_DNS.hyphenated().to_string(),
                   "6ba7b810-9dad-11d1-80b4-00c04fd430c8");
        assert_eq!(NAMESPACE_URL.hyphenated().to_string(),
                   "6ba7b811-9dad-11d1-80b4-00c04fd430c8");
        assert_eq!(NAMESPACE_OID.hyphenated().to_string(),
                   "6ba7b812-9dad-11d1-80b4-00c04fd430c8");
        assert_eq!(NAMESPACE_X500.hyphenated().to_string(),
                   "6ba7b814-9dad-11d1-80b4-00c04fd430c8");
    }

    #[cfg(feature = "v3")]
    #[test]
    fn test_get_version_v3() {
        let uuid = Uuid::new_v3(&NAMESPACE_DNS, "rust-lang.org");

        assert!(uuid.get_version().unwrap() == UuidVersion::Md5);
        assert_eq!(uuid.get_version_num(), 3);
    }

    #[test]
    #[cfg(feature = "v4")]
    fn test_get_version_v4() {
        let uuid1 = Uuid::new_v4();

        assert!(uuid1.get_version().unwrap() == UuidVersion::Random);
        assert_eq!(uuid1.get_version_num(), 4);
    }

    #[cfg(feature = "v5")]
    #[test]
    fn test_get_version_v5() {
        let uuid2 = Uuid::new_v5(&NAMESPACE_DNS, "rust-lang.org");

        assert!(uuid2.get_version().unwrap() == UuidVersion::Sha1);
        assert_eq!(uuid2.get_version_num(), 5);
    }

    #[test]
    fn test_get_variant() {
        let uuid1 = new();
        let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        let uuid3 = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap();
        let uuid4 = Uuid::parse_str("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap();
        let uuid5 = Uuid::parse_str("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap();
        let uuid6 = Uuid::parse_str("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap();

        assert!(uuid1.get_variant().unwrap() == UuidVariant::RFC4122);
        assert!(uuid2.get_variant().unwrap() == UuidVariant::RFC4122);
        assert!(uuid3.get_variant().unwrap() == UuidVariant::RFC4122);
        assert!(uuid4.get_variant().unwrap() == UuidVariant::Microsoft);
        assert!(uuid5.get_variant().unwrap() == UuidVariant::Microsoft);
        assert!(uuid6.get_variant().unwrap() == UuidVariant::NCS);
    }

    #[test]
    fn test_parse_uuid_v4() {
        use super::ParseError::*;

        // Invalid
        assert_eq!(Uuid::parse_str(""), Err(InvalidLength(0)));
        assert_eq!(Uuid::parse_str("!"), Err(InvalidLength(1)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45"),
                   Err(InvalidLength(37)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4"),
                   Err(InvalidLength(35)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4"),
                   Err(InvalidCharacter('G', 20)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2F4faaFB6BFF329BF39FA1E4"),
                   Err(InvalidGroups(2)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faaFB6BFF329BF39FA1E4"),
                   Err(InvalidGroups(3)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4"),
                   Err(InvalidGroups(4)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa"),
                   Err(InvalidLength(18)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4"),
                   Err(InvalidCharacter('X', 18)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4"),
                   Err(InvalidGroupLength(1, 3, 4)));
        assert_eq!(Uuid::parse_str("01020304-1112-2122-3132-41424344"),
                   Err(InvalidGroupLength(4, 8, 12)));
        assert_eq!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
                   Err(InvalidLength(31)));
        assert_eq!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c88"),
                   Err(InvalidLength(33)));
        assert_eq!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0cg8"),
                   Err(InvalidLength(33)));
        assert_eq!(Uuid::parse_str("67e5504410b1426%9247bb680e5fe0c8"),
                   Err(InvalidCharacter('%', 15)));
        assert_eq!(Uuid::parse_str("231231212212423424324323477343246663"),
                   Err(InvalidLength(36)));

        // Valid
        assert!(Uuid::parse_str("00000000000000000000000000000000").is_ok());
        assert!(Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());
        assert!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok());
        assert!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8").is_ok());
        assert!(Uuid::parse_str("01020304-1112-2122-3132-414243444546").is_ok());
        assert!(Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok());

        // Nil
        let nil = Uuid::nil();
        assert!(Uuid::parse_str("00000000000000000000000000000000").unwrap() == nil);
        assert!(Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap() == nil);

        // Round-trip
        let uuid_orig = new();
        let orig_str = uuid_orig.to_string();
        let uuid_out = Uuid::parse_str(&orig_str).unwrap();
        assert!(uuid_orig == uuid_out);

        // Test error reporting
        assert_eq!(Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c"),
                   Err(InvalidLength(31)));
        assert_eq!(Uuid::parse_str("67e550X410b1426f9247bb680e5fe0cd"),
                   Err(InvalidCharacter('X', 6)));
        assert_eq!(Uuid::parse_str("67e550-4105b1426f9247bb680e5fe0c"),
                   Err(InvalidGroupLength(0, 6, 8)));
        assert_eq!(Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4"),
                   Err(InvalidGroupLength(3, 5, 4)));
    }

    #[test]
    fn test_to_simple_string() {
        let uuid1 = new();
        let s = uuid1.simple().to_string();

        assert!(s.len() == 32);
        assert!(s.chars().all(|c| c.is_digit(16)));
    }

    #[test]
    fn test_to_string() {
        let uuid1 = new();
        let s = uuid1.to_string();

        assert!(s.len() == 36);
        assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[test]
    fn test_display() {
        let uuid1 = new();
        let s = uuid1.to_string();

        assert_eq!(s, uuid1.hyphenated().to_string());
    }

    #[test]
    fn test_to_hyphenated_string() {
        let uuid1 = new();
        let s = uuid1.hyphenated().to_string();

        assert!(s.len() == 36);
        assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[cfg(feature = "v3")]
    #[test]
    fn test_v3_to_hypenated_string() {
        for &(ref ns, ref name, ref expected) in FIXTURE_V3 {
            let uuid = Uuid::new_v3(*ns, *name);
            assert_eq!(uuid.hyphenated().to_string(), *expected);
        }
    }
    
    #[cfg(feature = "v5")]
    #[test]
    fn test_v5_to_hypenated_string() {
        for &(ref ns, ref name, ref expected) in FIXTURE_V5 {
            let uuid = Uuid::new_v5(*ns, *name);
            assert_eq!(uuid.hyphenated().to_string(), *expected);
        }
    }

    #[test]
    fn test_to_urn_string() {
        let uuid1 = new();
        let ss = uuid1.urn().to_string();
        let s = &ss[9..];

        assert!(ss.starts_with("urn:uuid:"));
        assert!(s.len() == 36);
        assert!(s.chars().all(|c| c.is_digit(16) || c == '-'));
    }

    #[test]
    fn test_to_simple_string_matching() {
        let uuid1 = new();

        let hs = uuid1.hyphenated().to_string();
        let ss = uuid1.simple().to_string();

        let hsn = hs.chars().filter(|&c| c != '-').collect::<String>();

        assert!(hsn == ss);
    }

    #[test]
    fn test_string_roundtrip() {
        let uuid = new();

        let hs = uuid.hyphenated().to_string();
        let uuid_hs = Uuid::parse_str(&hs).unwrap();
        assert_eq!(uuid_hs, uuid);

        let ss = uuid.to_string();
        let uuid_ss = Uuid::parse_str(&ss).unwrap();
        assert_eq!(uuid_ss, uuid);
    }

    #[test]
    fn test_compare() {
        let uuid1 = new();
        let uuid2 = new2();

        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;
        let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8];

        let u = Uuid::from_fields(d1, d2, d3, &d4).unwrap();

        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
        let result = u.simple().to_string();
        assert_eq!(result, expected);
    }

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

        let u = Uuid::from_bytes(&b).unwrap();
        let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";

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

    #[test]
    fn test_as_bytes() {
        let u = new();
        let ub = u.as_bytes();

        assert_eq!(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];

        let u = Uuid::from_bytes(&b_in).unwrap();

        let b_out = u.as_bytes();

        assert_eq!(&b_in, b_out);
    }

    #[test]
    fn test_operator_eq() {
        let u1 = new();
        let u2 = u1.clone();
        let u3 = new2();

        assert!(u1 == u1);
        assert!(u1 == u2);
        assert!(u2 == u1);

        assert!(u1 != u3);
        assert!(u3 != u1);
        assert!(u2 != u3);
        assert!(u3 != u2);
    }

    #[test]
    #[cfg(feature = "v4")]
    fn test_rand_rand() {
        let mut rng = rand::thread_rng();
        let u: Uuid = rand::Rand::rand(&mut rng);
        let ub = u.as_bytes();

        assert!(ub.len() == 16);
        assert!(!ub.iter().all(|&b| b == 0));
    }

    #[test]
    fn test_iterbytes_impl_for_uuid() {
        let mut set = std::collections::HashSet::new();
        let id1 = new();
        let id2 = new2();
        set.insert(id1.clone());
        assert!(set.contains(&id1));
        assert!(!set.contains(&id2));
    }
}