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 <stdint.h> 8 9 #include <limits> 10 11 #include <gtest/gtest.h> 12 13 #include "base/strings/string_util.h" 14 #include "build/build_config.h" 15 16 namespace base { 17 18 #if defined(OS_POSIX) 19 20 namespace { 21 22 template <typename Char> 23 inline bool IsHexDigit(Char c) { 24 return (c >= '0' && c <= '9') || 25 (c >= 'A' && c <= 'F') || 26 (c >= 'a' && c <= 'f'); 27 } 28 29 bool IsValidGUID(const std::string& guid) { 30 const size_t kGUIDLength = 36U; 31 if (guid.length() != kGUIDLength) 32 return false; 33 34 for (size_t i = 0; i < guid.length(); ++i) { 35 char current = guid[i]; 36 if (i == 8 || i == 13 || i == 18 || i == 23) { 37 if (current != '-') 38 return false; 39 } else { 40 if (!IsHexDigit(current)) 41 return false; 42 } 43 } 44 45 return true; 46 } 47 48 bool IsGUIDv4(const std::string& guid) { 49 // The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, 50 // where y is one of [8, 9, A, B]. 51 return IsValidGUID(guid) && guid[14] == '4' && 52 (guid[19] == '8' || guid[19] == '9' || guid[19] == 'A' || 53 guid[19] == 'a' || guid[19] == 'B' || guid[19] == 'b'); 54 } 55 56 } // namespace 57 58 TEST(GUIDTest, GUIDGeneratesAllZeroes) { 59 uint64_t bytes[] = {0, 0}; 60 std::string clientid = RandomDataToGUIDString(bytes); 61 EXPECT_EQ("00000000-0000-0000-0000-000000000000", clientid); 62 } 63 64 TEST(GUIDTest, GUIDGeneratesCorrectly) { 65 uint64_t bytes[] = {0x0123456789ABCDEFULL, 0xFEDCBA9876543210ULL}; 66 std::string clientid = RandomDataToGUIDString(bytes); 67 EXPECT_EQ("01234567-89AB-CDEF-FEDC-BA9876543210", clientid); 68 } 69 #endif 70 71 TEST(GUIDTest, GUIDCorrectlyFormatted) { 72 const int kIterations = 10; 73 for (int it = 0; it < kIterations; ++it) { 74 std::string guid = GenerateGUID(); 75 EXPECT_TRUE(IsValidGUID(guid)); 76 } 77 } 78 79 TEST(GUIDTest, GUIDBasicUniqueness) { 80 const int kIterations = 10; 81 for (int it = 0; it < kIterations; ++it) { 82 std::string guid1 = GenerateGUID(); 83 std::string guid2 = GenerateGUID(); 84 EXPECT_EQ(36U, guid1.length()); 85 EXPECT_EQ(36U, guid2.length()); 86 EXPECT_NE(guid1, guid2); 87 #if defined(OS_POSIX) 88 EXPECT_TRUE(IsGUIDv4(guid1)); 89 EXPECT_TRUE(IsGUIDv4(guid2)); 90 #endif 91 } 92 } 93 94 } // namespace base 95