Guid.Unix.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. namespace System
  7. {
  8. partial struct Guid
  9. {
  10. // This will create a new random guid based on the https://www.ietf.org/rfc/rfc4122.txt
  11. public static unsafe Guid NewGuid()
  12. {
  13. Guid g;
  14. Interop.GetRandomBytes((byte*)&g, sizeof(Guid));
  15. const ushort VersionMask = 0xF000;
  16. const ushort RandomGuidVersion = 0x4000;
  17. const byte ClockSeqHiAndReservedMask = 0xC0;
  18. const byte ClockSeqHiAndReservedValue = 0x80;
  19. // Modify bits indicating the type of the GUID
  20. unchecked
  21. {
  22. // time_hi_and_version
  23. g._c = (short)((g._c & ~VersionMask) | RandomGuidVersion);
  24. // clock_seq_hi_and_reserved
  25. g._d = (byte)((g._d & ~ClockSeqHiAndReservedMask) | ClockSeqHiAndReservedValue);
  26. }
  27. return g;
  28. }
  29. }
  30. }