bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.79k stars 499 forks source link

Generated `UUID` is not RFC compliant #420

Open Ikendiken opened 2 years ago

Ikendiken commented 2 years ago

The UUID that Bogus generates was not RFC compliant which was causing my tests to fail. I was able to workaround the issue by combining both of the solutions from issue #102 Determinism with Uuid

var version = 4;
var guidBytes = this.Bytes(16);
// set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8)
guidBytes[6] = (byte)((guidBytes[6] & 0x0F) | (version << 4));

// set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10)
guidBytes[8] = (byte)((guidBytes[8] & 0x3F) | 0x80);

// convert the resulting UUID to local byte order (step 13)
SwapByteOrder(guidBytes);
return new Guid(guidBytes);

static void SwapByteOrder(byte[] guid)
{
    SwapBytes(guid, 0, 3);
    SwapBytes(guid, 1, 2);
    SwapBytes(guid, 4, 5);
    SwapBytes(guid, 6, 7);
}

static void SwapBytes(byte[] guid, int left, int right)
{
    byte temp = guid[left];
    guid[left] = guid[right];
    guid[right] = temp;
}
Ikendiken commented 2 years ago

"^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[45][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$" is the pattern that was generating the assertion failture. ("A type 4 ('random' or 'pseudorandom') or type 5 UUID per RFC 4122.")