Skip to content

Commit

Permalink
Streamline Guid.NewGuid on Windows (#100719)
Browse files Browse the repository at this point in the history
Enable it to be inlined automatically and remove an extra LibraryImport helper
  • Loading branch information
stephentoub committed Apr 6, 2024
1 parent b8964d8 commit e0ff36d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ internal static partial class Interop
internal static partial class Ole32
{
[LibraryImport(Libraries.Ole32)]
internal static partial int CoCreateGuid(out Guid guid);
internal static unsafe partial int CoCreateGuid(Guid* guid);
}
}
24 changes: 14 additions & 10 deletions src/libraries/System.Private.CoreLib/src/System/Guid.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,26 @@ namespace System
{
public partial struct Guid
{
public static Guid NewGuid()
public static unsafe Guid NewGuid()
{
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
// uniqueness guarantees.
// CoCreateGuid should never return Guid.Empty, since it attempts to maintain some uniqueness guarantees.

int hr = Interop.Ole32.CoCreateGuid(out Guid g);
// We don't expect that this will ever throw an error, none are even documented, and so we don't want to pull
// in the HR to ComException mappings into the core library just for this so we will try a generic exception if
// we ever hit this condition.
Guid g;
int hr = Interop.Ole32.CoCreateGuid(&g);
if (hr != 0)
{
Exception ex = new Exception();
ex.HResult = hr;
throw ex;
ThrowForHr(hr);
}

return g;
}

private static void ThrowForHr(int hr)
{
// We don't expect that this will ever throw an error, none are even documented, and so we don't want to pull
// in the HR to ComException mappings into the core library just for this so we will try a generic exception if
// we ever hit this condition.
throw new Exception() { HResult = hr };
}
}
}

0 comments on commit e0ff36d

Please sign in to comment.