1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/guid.h"
6
7#include "base/rand_util.h"
8#include "base/strings/stringprintf.h"
9
10namespace base {
11
12std::string GenerateGUID() {
13  uint64 sixteen_bytes[2] = { base::RandUint64(), base::RandUint64() };
14
15  // Set the GUID to version 4 as described in RFC 4122, section 4.4.
16  // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
17  // where y is one of [8, 9, A, B].
18
19  // Clear the version bits and set the version to 4:
20  sixteen_bytes[0] &= 0xffffffffffff0fffULL;
21  sixteen_bytes[0] |= 0x0000000000004000ULL;
22
23  // Set the two most significant bits (bits 6 and 7) of the
24  // clock_seq_hi_and_reserved to zero and one, respectively:
25  sixteen_bytes[1] &= 0x3fffffffffffffffULL;
26  sixteen_bytes[1] |= 0x8000000000000000ULL;
27
28  return RandomDataToGUIDString(sixteen_bytes);
29}
30
31// TODO(cmasone): Once we're comfortable this works, migrate Windows code to
32// use this as well.
33std::string RandomDataToGUIDString(const uint64 bytes[2]) {
34  return StringPrintf("%08X-%04X-%04X-%04X-%012llX",
35                      static_cast<unsigned int>(bytes[0] >> 32),
36                      static_cast<unsigned int>((bytes[0] >> 16) & 0x0000ffff),
37                      static_cast<unsigned int>(bytes[0] & 0x0000ffff),
38                      static_cast<unsigned int>(bytes[1] >> 48),
39                      bytes[1] & 0x0000ffffffffffffULL);
40}
41
42}  // namespace guid
43