| 1 |
// Copyright (c) Microsoft. All rights reserved. |
| 2 |
// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 |
|
| 4 |
#include <stdlib.h> |
| 5 |
#include <stdint.h> |
| 6 |
#include "azure_c_shared_utility/uniqueid.h" |
| 7 |
#include "azure_c_shared_utility/xlogging.h" |
| 8 |
#include <time.h> |
| 9 |
|
| 10 |
MU_DEFINE_ENUM_STRINGS(UNIQUEID_RESULT, UNIQUEID_RESULT_VALUES); |
| 11 |
|
| 12 |
static const char tochar[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; |
| 13 |
static void generate128BitUUID(unsigned char* arrayOfByte) |
| 14 |
{ |
| 15 |
size_t arrayIndex; |
| 16 |
|
| 17 |
for (arrayIndex = 0; arrayIndex < 16; arrayIndex++) |
| 18 |
{ |
| 19 |
arrayOfByte[arrayIndex] = (unsigned char)rand(); |
| 20 |
} |
| 21 |
|
| 22 |
// |
| 23 |
// Stick in the version field for random uuid. |
| 24 |
// |
| 25 |
arrayOfByte[7] &= 0x0f; //clear the bit field |
| 26 |
arrayOfByte[7] |= 0x40; //set the ones we care about |
| 27 |
|
| 28 |
// |
| 29 |
// Stick in the variant field for the random uuid. |
| 30 |
// |
| 31 |
arrayOfByte[8] &= 0xf3; // Clear |
| 32 |
arrayOfByte[8] |= 0x08; // Set |
| 33 |
|
| 34 |
} |
| 35 |
|
| 36 |
// TODO: The User will need to call srand before calling this function |
| 37 |
UNIQUEID_RESULT UniqueId_Generate(char* uid, size_t len) |
| 38 |
{ |
| 39 |
UNIQUEID_RESULT result; |
| 40 |
unsigned char arrayOfChar[16]; |
| 41 |
|
| 42 |
/* Codes_SRS_UNIQUEID_07_002: [If uid is NULL then UniqueId_Generate shall return UNIQUEID_INVALID_ARG] */ |
| 43 |
/* Codes_SRS_UNIQUEID_07_003: [If len is less then 37 then UniqueId_Generate shall return UNIQUEID_INVALID_ARG] */ |
| 44 |
if (uid == NULL || len < 37) |
| 45 |
{ |
| 46 |
result = UNIQUEID_INVALID_ARG; |
| 47 |
LogError("Buffer Size is Null or length is less then 37 bytes"); |
| 48 |
} |
| 49 |
else |
| 50 |
{ |
| 51 |
size_t arrayIndex; |
| 52 |
size_t shiftCount; |
| 53 |
size_t characterPosition = 0; |
| 54 |
|
| 55 |
/* Codes_SRS_UNIQUEID_07_001: [UniqueId_Generate shall create a unique Id 36 character long string.] */ |
| 56 |
generate128BitUUID(arrayOfChar); |
| 57 |
for (arrayIndex = 0; arrayIndex < 16; arrayIndex++) |
| 58 |
{ |
| 59 |
for (shiftCount = 0; shiftCount <= 1; shiftCount++) |
| 60 |
{ |
| 61 |
char hexChar = tochar[arrayOfChar[arrayIndex] & 0xf]; |
| 62 |
if ((characterPosition == 8) || (characterPosition == 13) || (characterPosition == 18) || (characterPosition == 23)) |
| 63 |
{ |
| 64 |
uid[characterPosition] = '-'; |
| 65 |
characterPosition++; |
| 66 |
} |
| 67 |
uid[characterPosition] = hexChar; |
| 68 |
characterPosition++; |
| 69 |
arrayOfChar[arrayIndex] = arrayOfChar[arrayIndex] >> 4; |
| 70 |
} |
| 71 |
} |
| 72 |
uid[characterPosition] = 0; |
| 73 |
result = UNIQUEID_OK; |
| 74 |
} |
| 75 |
return result; |
| 76 |
} |