From: Alexej Liebenthal <13908853+AlexejLiebenthal@users.noreply.github.com> Date: Fri, 30 Nov 2018 00:58:38 +0000 (+0100) Subject: Added TryParse to StandardFormat (#21216) X-Git-Tag: accepted/tizen/unified/20190422.045933~499 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=50e2a0eac6f9cd3bf620c336079b4eb497cc0a99;p=platform%2Fupstream%2Fcoreclr.git Added TryParse to StandardFormat (#21216) --- diff --git a/src/System.Private.CoreLib/shared/System/Buffers/StandardFormat.cs b/src/System.Private.CoreLib/shared/System/Buffers/StandardFormat.cs index 6975c20..8260325 100644 --- a/src/System.Private.CoreLib/shared/System/Buffers/StandardFormat.cs +++ b/src/System.Private.CoreLib/shared/System/Buffers/StandardFormat.cs @@ -67,12 +67,34 @@ namespace System.Buffers public static implicit operator StandardFormat(char symbol) => new StandardFormat(symbol); /// - /// Converts a classic .NET format string into a StandardFormat + /// Converts a ReadOnlySpan into a StandardFormat /// public static StandardFormat Parse(ReadOnlySpan format) { + ParseHelper(format, out StandardFormat standardFormat, throws: true); + + return standardFormat; + } + + /// + /// Converts a classic .NET format string into a StandardFormat + /// + public static StandardFormat Parse(string format) => format == null ? default : Parse(format.AsSpan()); + + /// + /// Tries to convert a ReadOnlySpan into a StandardFormat. A return value indicates whether the conversion succeeded or failed. + /// + public static bool TryParse(ReadOnlySpan format, out StandardFormat result) + { + return ParseHelper(format, out result); + } + + private static bool ParseHelper(ReadOnlySpan format, out StandardFormat standardFormat, bool throws = false) + { + standardFormat = default; + if (format.Length == 0) - return default; + return true; char symbol = format[0]; byte precision; @@ -87,25 +109,24 @@ namespace System.Buffers { uint digit = format[srcIndex] - 48u; // '0' if (digit > 9) - throw new FormatException(SR.Format(SR.Argument_CannotParsePrecision, MaxPrecision)); - + { + return throws ? throw new FormatException(SR.Format(SR.Argument_CannotParsePrecision, MaxPrecision)) : false; + } parsedPrecision = parsedPrecision * 10 + digit; if (parsedPrecision > MaxPrecision) - throw new FormatException(SR.Format(SR.Argument_PrecisionTooLarge, MaxPrecision)); + { + return throws ? throw new FormatException(SR.Format(SR.Argument_PrecisionTooLarge, MaxPrecision)) : false; + } } precision = (byte)parsedPrecision; } - return new StandardFormat(symbol, precision); + standardFormat = new StandardFormat(symbol, precision); + return true; } /// - /// Converts a classic .NET format string into a StandardFormat - /// - public static StandardFormat Parse(string format) => format == null ? default : Parse(format.AsSpan()); - - /// /// Returns true if both the Symbol and Precision are equal. /// public override bool Equals(object obj) => obj is StandardFormat other && Equals(other);