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

Add Generic Enum.TryFormat() #71590

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -1046,8 +1046,8 @@ private int WhichBofsIsBetter(BinOpFullSig bofs1, BinOpFullSig bofs2, CType type
bt2 = WhichTypeIsBetter(bofs1.Type2(), bofs2.Type2(), type2);
}

Debug.Assert(Enum.IsDefined(typeof(BetterType), bt1));
Debug.Assert(Enum.IsDefined(typeof(BetterType), bt2));
Debug.Assert(Enum.IsDefined(bt1));
Debug.Assert(Enum.IsDefined(bt2));
int res = bt1 switch
{
BetterType.Left => -1,
Expand Down Expand Up @@ -1550,7 +1550,7 @@ private int WhichUofsIsBetter(UnaOpFullSig uofs1, UnaOpFullSig uofs2, CType type
bt = WhichTypeIsBetter(uofs1.GetType(), uofs2.GetType(), typeArg);
}

Debug.Assert(Enum.IsDefined(typeof(BetterType), bt));
Debug.Assert(Enum.IsDefined(bt));
return bt switch
{
BetterType.Left => -1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ public void SetValue(string? name, object value, RegistryValueKind valueKind)
throw new ArgumentException(SR.Arg_RegValStrLenBug, nameof(name));
}

if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
if (!Enum.IsDefined(valueKind))
{
throw new ArgumentException(SR.Arg_RegBadKeyKind, nameof(valueKind));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ public ProcessPriorityClass PriorityClass
}
set
{
if (!Enum.IsDefined(typeof(ProcessPriorityClass), value))
if (!Enum.IsDefined(value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public ProcessWindowStyle WindowStyle
get => _windowStyle;
set
{
if (!Enum.IsDefined(typeof(ProcessWindowStyle), value))
if (!Enum.IsDefined(value))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessWindowStyle));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ public PrintRange PrintRange
get { return _printRange; }
set
{
if (!Enum.IsDefined(typeof(PrintRange), value))
if (!Enum.IsDefined(value))
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PrintRange));

_printRange = value;
Expand Down
669 changes: 493 additions & 176 deletions src/libraries/System.Private.CoreLib/src/System/Enum.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,10 @@ public static string ExpandEnvironmentVariables(string name)

public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
{
if (!Enum.IsDefined(typeof(SpecialFolder), folder))
if (!Enum.IsDefined(folder))
throw new ArgumentOutOfRangeException(nameof(folder), folder, SR.Format(SR.Arg_EnumIllegalVal, folder));

if (option != SpecialFolderOption.None && !Enum.IsDefined(typeof(SpecialFolderOption), option))
if (option != SpecialFolderOption.None && !Enum.IsDefined(option))
throw new ArgumentOutOfRangeException(nameof(option), option, SR.Format(SR.Arg_EnumIllegalVal, option));

return GetFolderPathCore(folder, option);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3271,10 +3271,21 @@ public bool AppendFormatted<T>(T value)
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.

if (value is ISpanFormattable)
{
int charsWritten;
if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out charsWritten, default, _provider)) // constrained call avoiding boxing for value types
if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out int charsWritten, default, _provider)) // constrained call avoiding boxing for value types
{
_pos += charsWritten;
return true;
}

return Fail();
}

if (typeof(T).IsEnum)
{
if (Enum.TryFormatUnconstrained(value, _destination.Slice(_pos), out int charsWritten))
{
_pos += charsWritten;
return true;
Expand Down Expand Up @@ -3318,8 +3329,18 @@ public bool AppendFormatted<T>(T value, string? format)
// If the value can format itself directly into our buffer, do so.
if (value is ISpanFormattable)
{
int charsWritten;
if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out charsWritten, format, _provider)) // constrained call avoiding boxing for value types
if (((ISpanFormattable)value).TryFormat(_destination.Slice(_pos), out int charsWritten, format, _provider)) // constrained call avoiding boxing for value types
{
_pos += charsWritten;
return true;
}

return Fail();
}

if (typeof(T).IsEnum)
{
if (Enum.TryFormatUnconstrained(value, _destination.Slice(_pos), out int charsWritten, format))
{
_pos += charsWritten;
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public NeutralResourcesLanguageAttribute(string cultureName, UltimateResourceFal
{
ArgumentNullException.ThrowIfNull(cultureName);

if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location))
if (!Enum.IsDefined(location))
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, location));

CultureName = cultureName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ public void AppendFormatted<T>(T value)
if (value is IFormattable)
{
// If the value can format itself directly into our buffer, do so.

if (value is ISpanFormattable)
{
int charsWritten;
Expand All @@ -317,6 +318,18 @@ public void AppendFormatted<T>(T value)
return;
}

if (typeof(T).IsEnum)
{
int charsWritten;
while (!Enum.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten))
{
Grow();
}

_pos += charsWritten;
return;
}

s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types
}
else
Expand All @@ -329,6 +342,7 @@ public void AppendFormatted<T>(T value)
AppendStringDirect(s);
}
}

/// <summary>Writes the specified value to the handler.</summary>
/// <param name="value">The value to write.</param>
/// <param name="format">The format string.</param>
Expand Down Expand Up @@ -365,6 +379,18 @@ public void AppendFormatted<T>(T value, string? format)
return;
}

if (typeof(T).IsEnum)
{
int charsWritten;
while (!Enum.TryFormatUnconstrained(value, _chars.Slice(_pos), out charsWritten, format))
{
Grow();
}

_pos += charsWritten;
return;
}

s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2640,6 +2640,17 @@ public void AppendFormatted<T>(T value)
AppendFormattedWithTempSpace(value, 0, format: null);
}
}
else if (typeof(T).IsEnum)
{
if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritten))
{
_stringBuilder.m_ChunkLength += charsWritten;
}
else
{
AppendFormattedWithTempSpace(value, 0, format: null);
}
}
else
{
_stringBuilder.Append(((IFormattable)value).ToString(format: null, _provider)); // constrained call avoiding boxing for value types
Expand Down Expand Up @@ -2693,6 +2704,17 @@ public void AppendFormatted<T>(T value, string? format)
AppendFormattedWithTempSpace(value, 0, format);
}
}
else if (typeof(T).IsEnum)
{
if (Enum.TryFormatUnconstrained(value, _stringBuilder.RemainingCurrentChunk, out int charsWritten, format))
{
_stringBuilder.m_ChunkLength += charsWritten;
}
else
{
AppendFormattedWithTempSpace(value, 0, format);
}
}
else
{
_stringBuilder.Append(((IFormattable)value).ToString(format, _provider)); // constrained call avoiding boxing for value types
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ internal static void ThrowForUnsupportedIntrinsicsVector256BaseType<T>()
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetArgumentName(ExceptionArgument argument)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
Debug.Assert(Enum.IsDefined(argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");

return argument.ToString();
Expand Down Expand Up @@ -912,7 +912,7 @@ private static string GetArgumentName(ExceptionArgument argument)
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetResourceString(ExceptionResource resource)
{
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
Debug.Assert(Enum.IsDefined(resource),
"The enum value is not defined, please check the ExceptionResource Enum.");

return SR.GetResourceString(resource.ToString());
Expand Down
4 changes: 0 additions & 4 deletions src/libraries/System.Private.Uri/src/System/UriExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ private void CreateThis(string? uri, bool dontEscape, UriKind uriKind, in UriCre
{
DebugAssertInCtor();

// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
Expand Down Expand Up @@ -622,8 +620,6 @@ private Uri(Flags flags, UriParser? uriParser, string uri)
//
internal static Uri? CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException? e, in UriCreationOptions creationOptions = default)
{
// if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow
// to be used here.
if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative)
{
throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public object GetArgument(OptimizerPatternArgument argNum)
/// </summary>
public void AddPattern(OptimizerPatternName pattern)
{
Debug.Assert(Enum.IsDefined(typeof(OptimizerPatternName), pattern));
Debug.Assert(Enum.IsDefined(pattern));
Debug.Assert((int)pattern < 32);
Debug.Assert(!_isReadOnly, "This OptimizerPatterns instance is read-only.");
_patterns |= (1 << (int)pattern);
Expand All @@ -253,7 +253,7 @@ public void AddPattern(OptimizerPatternName pattern)
/// </summary>
public bool MatchesPattern(OptimizerPatternName pattern)
{
Debug.Assert(Enum.IsDefined(typeof(OptimizerPatternName), pattern));
Debug.Assert(Enum.IsDefined(pattern));
return (_patterns & (1 << (int)pattern)) != 0;
}

Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2366,6 +2366,7 @@ protected Enum() { }
public string ToString([System.Diagnostics.CodeAnalysis.StringSyntaxAttribute("EnumFormat")] string? format) { throw null; }
[System.ObsoleteAttribute("The provider argument is not used. Use ToString(String) instead.")]
public string ToString([System.Diagnostics.CodeAnalysis.StringSyntaxAttribute("EnumFormat")] string? format, System.IFormatProvider? provider) { throw null; }
public static bool TryFormat<TEnum>(TEnum value, System.Span<char> destination, out int charsWritten, [System.Diagnostics.CodeAnalysis.StringSyntaxAttribute("EnumFormat")] System.ReadOnlySpan<char> format = default(System.ReadOnlySpan<char>)) where TEnum : struct { throw null; }
public static bool TryParse(System.Type enumType, System.ReadOnlySpan<char> value, bool ignoreCase, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out object? result) { throw null; }
public static bool TryParse(System.Type enumType, System.ReadOnlySpan<char> value, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out object? result) { throw null; }
public static bool TryParse(System.Type enumType, string? value, bool ignoreCase, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out object? result) { throw null; }
Expand Down
Loading