mirror of
https://github.com/beefytech/Beef.git
synced 2025-06-23 10:08:00 +02:00
Improvements to Number parsing
This commit is contained in:
parent
4c65652955
commit
5d28f8e1f0
10 changed files with 418 additions and 90 deletions
|
@ -1,10 +1,20 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace System
|
||||
{
|
||||
#unwarn
|
||||
struct Int8 : int8, IInteger, ISigned, IHashable, IFormattable, IIsNaN
|
||||
{
|
||||
public const int32 MaxValue = 0x7F;
|
||||
public const int32 MinValue = -0x80;
|
||||
public enum ParseError
|
||||
{
|
||||
case Ok;
|
||||
case NoValue;
|
||||
case Overflow;
|
||||
case InvalidChar(int8 partialResult);
|
||||
}
|
||||
|
||||
public const int8 MaxValue = 0x7F;
|
||||
public const int8 MinValue = -0x80;
|
||||
|
||||
public static int operator<=>(Self a, Self b)
|
||||
{
|
||||
|
@ -66,5 +76,68 @@ namespace System
|
|||
NumberFormatter.NumberToString(format, (int32)this, formatProvider, outString);
|
||||
}
|
||||
}
|
||||
|
||||
public static Result<int8, ParseError> Parse(StringView val, NumberStyles style = .Number, CultureInfo cultureInfo = null)
|
||||
{
|
||||
if (val.IsEmpty)
|
||||
return .Err(.NoValue);
|
||||
|
||||
bool isNeg = false;
|
||||
int8 result = 0;
|
||||
|
||||
int8 radix = style.HasFlag(.AllowHexSpecifier) ? 0x10 : 10;
|
||||
|
||||
for (int32 i = 0; i < val.Length; i++)
|
||||
{
|
||||
char8 c = val[i];
|
||||
|
||||
if ((i == 0) && (c == '-'))
|
||||
{
|
||||
isNeg = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((c >= '0') && (c <= '9'))
|
||||
{
|
||||
result &*= radix;
|
||||
result &+= (int8)(c - '0');
|
||||
}
|
||||
else if ((c >= 'a') && (c <= 'f'))
|
||||
{
|
||||
if (radix != 0x10)
|
||||
return .Err(.InvalidChar(result));
|
||||
result &*= radix;
|
||||
result &+= (int8)(c - 'a' + 10);
|
||||
}
|
||||
else if ((c >= 'A') && (c <= 'F'))
|
||||
{
|
||||
if (radix != 0x10)
|
||||
return .Err(.InvalidChar(result));
|
||||
result &*= radix;
|
||||
result &+= (int8)(c - 'A' + 10);
|
||||
}
|
||||
else if ((c == 'X') || (c == 'x'))
|
||||
{
|
||||
if ((!style.HasFlag(.AllowHexSpecifier)) || (i == 0) || (result != 0))
|
||||
return .Err(.InvalidChar(result));
|
||||
radix = 0x10;
|
||||
}
|
||||
else if (c == '\'')
|
||||
{
|
||||
// Ignore
|
||||
}
|
||||
else if ((c == '+') && (i == 0))
|
||||
{
|
||||
// Ignore
|
||||
}
|
||||
else
|
||||
return .Err(.InvalidChar(result));
|
||||
|
||||
if (isNeg ? (uint8)result > (uint8)MaxValue + 1 : (uint8)result > (uint8)MaxValue)
|
||||
return .Err(.Overflow);
|
||||
}
|
||||
|
||||
return isNeg ? -result : result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue