Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use HexConverter directly when producing hex representation of enum value #44945

Merged
merged 4 commits into from
Nov 21, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions src/libraries/System.Private.CoreLib/src/System/Enum.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
Expand Down Expand Up @@ -63,26 +64,38 @@ private string ValueToString()
private string ValueToHexString()
{
ref byte data = ref this.GetRawData();
Span<byte> bytes = stackalloc byte[8];
int length;
switch (InternalGetCorElementType())
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
return data.ToString("X2", null);
bytes = new Span<byte>(ref data, 1);
marek-safar marked this conversation as resolved.
Show resolved Hide resolved
length = 1;
break;
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return Convert.ToByte(Unsafe.As<byte, bool>(ref data)).ToString("X2", null);
return Unsafe.As<byte, bool>(ref data) ? "01" : "00";
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, ushort>(ref data).ToString("X4", null);
BinaryPrimitives.WriteUInt16BigEndian(bytes, Unsafe.As<byte, ushort>(ref data));
length = 2;
break;
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref data).ToString("X8", null);
BinaryPrimitives.WriteUInt32BigEndian(bytes, Unsafe.As<byte, uint>(ref data));
length = 4;
break;
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref data).ToString("X16", null);
BinaryPrimitives.WriteUInt64BigEndian(bytes, Unsafe.As<byte, ulong>(ref data));
length = 8;
break;
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}

return HexConverter.ToString(bytes.Slice(0, length), HexConverter.Casing.Upper);
}

private static string ValueToHexString(object value)
Expand Down