Skip to content

Commit

Permalink
Merge pull request #1062 from dahlbyk/ByteSize-Parse-IFormatProvider
Browse files Browse the repository at this point in the history
Parse `ByteSize` with `IFormatProvider`
  • Loading branch information
clairernovotny authored May 3, 2021
2 parents 42ac2a1 + 8db043d commit b8c06d7
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 20 deletions.
66 changes: 54 additions & 12 deletions src/Humanizer.Tests.Shared/Bytes/ParsingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
//THE SOFTWARE.

using System;
using System.Globalization;
using Humanizer.Bytes;
using Xunit;

Expand All @@ -36,6 +37,13 @@ public void Parse()
Assert.Equal(ByteSize.FromKilobytes(1020), ByteSize.Parse("1020KB"));
}

[Fact]
public void TryParseReturnsFalseOnNull()
{
Assert.False(ByteSize.TryParse(null, out var result));
Assert.Equal(default, result);
}

[Fact]
public void TryParse()
{
Expand All @@ -45,22 +53,68 @@ public void TryParse()
Assert.Equal(ByteSize.FromKilobytes(1020), resultByteSize);
}

[Theory]
[InlineData("2000.01KB", "")] // Invariant
[InlineData("2,000.01KB", "")]
[InlineData("+2000.01KB", "")]
[InlineData("2000.01KB", "en")]
[InlineData("2,000.01KB", "en")]
[InlineData("+2000.01KB", "en")]
[InlineData("2000,01KB", "de")]
[InlineData("2.000,01KB", "de")]
[InlineData("+2000,01KB", "de")]
public void TryParseWithCultureInfo(string value, string cultureName)
{
var culture = new CultureInfo(cultureName);

Assert.True(ByteSize.TryParse(value, culture, out var resultByteSize));
Assert.Equal(ByteSize.FromKilobytes(2000.01), resultByteSize);

Assert.Equal(resultByteSize, ByteSize.Parse(value, culture));
}

[Fact]
public void TryParseWithNumberFormatInfo()
{
var numberFormat = new NumberFormatInfo
{
NumberDecimalSeparator = "_",
NumberGroupSeparator = ";",
NegativeSign = "−", // proper minus, not hyphen-minus
};

var value = "−2;000_01KB";

Assert.True(ByteSize.TryParse(value, numberFormat, out var resultByteSize));
Assert.Equal(ByteSize.FromKilobytes(-2000.01), resultByteSize);

Assert.Equal(resultByteSize, ByteSize.Parse(value, numberFormat));
}

[Fact]
public void ParseDecimalMegabytes()
{
Assert.Equal(ByteSize.FromMegabytes(100.5), ByteSize.Parse("100.5MB"));
}

[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("\t")]
[InlineData("Unexpected Value")]
[InlineData("1000")]
[InlineData(" 1000 ")]
[InlineData("KB")]
[InlineData("1000.5b")] // Partial bits
[InlineData("1000KBB")] // Bad suffix
public void TryParseReturnsFalseOnBadValue(string input)
{
var resultBool = ByteSize.TryParse(input, out var resultByteSize);

Assert.False(resultBool);
Assert.Equal(new ByteSize(), resultByteSize);

Assert.Throws<FormatException>(() => { ByteSize.Parse(input); });
}

[Fact]
Expand All @@ -69,18 +123,6 @@ public void TryParseWorksWithLotsOfSpaces()
Assert.Equal(ByteSize.FromKilobytes(100), ByteSize.Parse(" 100 KB "));
}

[Fact]
public void ParseThrowsOnPartialBits()
{
Assert.Throws<FormatException>(() => { ByteSize.Parse("10.5b"); });
}

[Fact]
public void ParseThrowsOnInvalid()
{
Assert.Throws<FormatException>(() => { ByteSize.Parse("Unexpected Value"); });
}

[Fact]
public void ParseThrowsOnNull()
{
Expand Down
56 changes: 48 additions & 8 deletions src/Humanizer/Bytes/ByteSize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@

using System;
using System.Globalization;
using System.Linq;
using Humanizer.Configuration;
using Humanizer.Localisation;

using static System.Globalization.NumberStyles;

namespace Humanizer.Bytes
{
/// <summary>
Expand Down Expand Up @@ -466,13 +469,31 @@ public ByteSize Subtract(ByteSize bs)
}

public static bool TryParse(string s, out ByteSize result)
{
return TryParse(s, null, out result);
}

public static bool TryParse(string s, IFormatProvider formatProvider, out ByteSize result)
{
// Arg checking
if (string.IsNullOrWhiteSpace(s))
{
throw new ArgumentNullException(nameof(s), "String is null or whitespace");
result = default;
return false;
}

// Acquiring culture-specific parsing info
var numberFormat = GetNumberFormatInfo(formatProvider);

const NumberStyles numberStyles = AllowDecimalPoint | AllowThousands | AllowLeadingSign;
var numberSpecialChars = new[]
{
Convert.ToChar(numberFormat.NumberDecimalSeparator),
Convert.ToChar(numberFormat.NumberGroupSeparator),
Convert.ToChar(numberFormat.PositiveSign),
Convert.ToChar(numberFormat.NegativeSign),
};

// Setup the result
result = new ByteSize();

Expand All @@ -482,14 +503,10 @@ public static bool TryParse(string s, out ByteSize result)
int num;
var found = false;

// Acquiring culture specific decimal separator

var decSep = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

// Pick first non-digit number
for (num = 0; num < s.Length; num++)
{
if (!(char.IsDigit(s[num]) || s[num] == decSep))
if (!(char.IsDigit(s[num]) || numberSpecialChars.Contains(s[num])))
{
found = true;
break;
Expand All @@ -508,7 +525,7 @@ public static bool TryParse(string s, out ByteSize result)
var sizePart = s.Substring(lastNumber, s.Length - lastNumber).Trim();

// Get the numeric part
if (!double.TryParse(numberPart, out var number))
if (!double.TryParse(numberPart, numberStyles, formatProvider, out var number))
{
return false;
}
Expand Down Expand Up @@ -547,14 +564,37 @@ public static bool TryParse(string s, out ByteSize result)
case TerabyteSymbol:
result = FromTerabytes(number);
break;

default:
return false;
}

return true;
}

private static NumberFormatInfo GetNumberFormatInfo(IFormatProvider formatProvider)
{
if (formatProvider is NumberFormatInfo numberFormat)
return numberFormat;

var culture = formatProvider as CultureInfo ?? CultureInfo.CurrentCulture;

return culture.NumberFormat;
}

public static ByteSize Parse(string s)
{
if (TryParse(s, out var result))
return Parse(s, null);
}

public static ByteSize Parse(string s, IFormatProvider formatProvider)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}

if (TryParse(s, formatProvider, out var result))
{
return result;
}
Expand Down

0 comments on commit b8c06d7

Please sign in to comment.