Skip to content

A Swiss Army knife for developers.

Added localized error message and error parsing for base number type (#103)

BenjaminT865c7b68f3f6
diff --git a/src/dev/impl/DevToys/LanguageManager.cs b/src/dev/impl/DevToys/LanguageManager.cs
index 7c1eb96c2..b3b146c25 100644
--- a/src/dev/impl/DevToys/LanguageManager.cs
+++ b/src/dev/impl/DevToys/LanguageManager.cs
@@ -944,6 +944,32 @@ namespace DevToys
/// Gets the resource OctalLabel.
/// </summary>
public string OctalLabel => _resources.GetString("OctalLabel");
+
+ /// <summary>
+ /// Gets the resource ValueInvalid.
+ /// </summary>
+ public string ValueInvalid => _resources.GetString("ValueInvalid");
+
+ /// <summary>
+ /// Gets the resource ValueInvalid with format.
+ /// </summary>
+ public string GetFormattedValueInvalid(string? param0)
+ {
+ return string.Format(ValueInvalid, param0);
+ }
+
+ /// <summary>
+ /// Gets the resource ValueOverflow.
+ /// </summary>
+ public string ValueOverflow => _resources.GetString("ValueOverflow");
+
+ /// <summary>
+ /// Gets the resource ValueOverflow with format.
+ /// </summary>
+ public string GetFormattedValueOverflow(string? param0)
+ {
+ return string.Format(ValueOverflow, param0);
+ }
}
public class PngJpgCompressorStrings : ObservableObject
diff --git a/src/dev/impl/DevToys/Models/NumberBaseFormat.cs b/src/dev/impl/DevToys/Models/NumberBaseFormat.cs
index a6594e9ce..298dbf74e 100644
--- a/src/dev/impl/DevToys/Models/NumberBaseFormat.cs
+++ b/src/dev/impl/DevToys/Models/NumberBaseFormat.cs
@@ -7,13 +7,6 @@ namespace DevToys.Models
{
private static NumberBaseConverterStrings Strings => LanguageManager.Instance.NumberBaseConverter;
- public static readonly NumberBaseFormat Octal = new(
- displayName: Strings.OctalLabel,
- value: Radix.Octal,
- baseNumber:8,
- groupSize: CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes[0],
- groupSeparator: ' ');
-
public static readonly NumberBaseFormat Binary = new(
displayName: Strings.BinaryLabel,
value: Radix.Binary,
@@ -21,6 +14,13 @@ namespace DevToys.Models
groupSize: 4,
groupSeparator: ' ');
+ public static readonly NumberBaseFormat Octal = new(
+ displayName: Strings.OctalLabel,
+ value: Radix.Octal,
+ baseNumber: 8,
+ groupSize: CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes[0],
+ groupSeparator: ' ');
+
public static readonly NumberBaseFormat Decimal = new(
displayName: Strings.DecimalLabel,
value: Radix.Decimal,
diff --git a/src/dev/impl/DevToys/Strings/cs-CZ/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/cs-CZ/NumberBaseConverter.resw
index 0a162a510..f09f809c4 100644
--- a/src/dev/impl/DevToys/Strings/cs-CZ/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/cs-CZ/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>The current value isn't a valid {0}</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Unable to parse the current value exceed max value {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Strings/en-US/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/en-US/NumberBaseConverter.resw
index 0a162a510..f09f809c4 100644
--- a/src/dev/impl/DevToys/Strings/en-US/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/en-US/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>The current value isn't a valid {0}</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Unable to parse the current value exceed max value {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Strings/fr-FR/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/fr-FR/NumberBaseConverter.resw
index 3c39690b0..77ec9e68d 100644
--- a/src/dev/impl/DevToys/Strings/fr-FR/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/fr-FR/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>La valeur actuelle n'est pas une valeur {0} valide.</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Impossible d'analyser la valeur actuelle qui dépasse la valeur maximale {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Strings/pl-PL/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/pl-PL/NumberBaseConverter.resw
index 0a162a510..f09f809c4 100644
--- a/src/dev/impl/DevToys/Strings/pl-PL/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/pl-PL/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>The current value isn't a valid {0}</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Unable to parse the current value exceed max value {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Strings/ru-RU/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/ru-RU/NumberBaseConverter.resw
index 0a162a510..f09f809c4 100644
--- a/src/dev/impl/DevToys/Strings/ru-RU/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/ru-RU/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>The current value isn't a valid {0}</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Unable to parse the current value exceed max value {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/Strings/zh-CN/NumberBaseConverter.resw b/src/dev/impl/DevToys/Strings/zh-CN/NumberBaseConverter.resw
index 0a162a510..f09f809c4 100644
--- a/src/dev/impl/DevToys/Strings/zh-CN/NumberBaseConverter.resw
+++ b/src/dev/impl/DevToys/Strings/zh-CN/NumberBaseConverter.resw
@@ -162,4 +162,12 @@
<data name="OctalLabel" xml:space="preserve">
<value>Octal</value>
</data>
+ <data name="ValueInvalid" xml:space="preserve">
+ <value>The current value isn't a valid {0}</value>
+ <comment>The parameter is the Base Number Type (Decimal, Octal, ...)</comment>
+ </data>
+ <data name="ValueOverflow" xml:space="preserve">
+ <value>Unable to parse the current value exceed max value {0}</value>
+ <comment>The parameter is the Max value of a long</comment>
+ </data>
</root>
\ No newline at end of file
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseConverterToolViewModel.cs b/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseConverterToolViewModel.cs
index bc95fdf1f..89d63b100 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseConverterToolViewModel.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseConverterToolViewModel.cs
@@ -215,6 +215,11 @@ namespace DevToys.ViewModels.Tools.NumberBaseConverter
isInfoBarOpen = true;
infoBarMessage = exception.Message;
}
+ catch (InvalidOperationException exception)
+ {
+ isInfoBarOpen = true;
+ infoBarMessage = exception.Message;
+ }
catch (Exception ex)
{
Logger.LogFault("NumberBaseConverter", ex, $"Input base number: {InputBaseNumber}");
diff --git a/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseFormatter.cs b/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseFormatter.cs
index 0c842ce3d..9b413b8a4 100644
--- a/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseFormatter.cs
+++ b/src/dev/impl/DevToys/ViewModels/Tools/NumberBaseConverter/NumberBaseFormatter.cs
@@ -9,6 +9,8 @@ namespace DevToys.Core.Formatter
{
internal static class NumberBaseFormatter
{
+ private static NumberBaseConverterStrings Strings => LanguageManager.Instance.NumberBaseConverter;
+
/// <summary>
/// Based on <see cref="System.ParseNumbers"/>
/// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/ParseNumbers.cs
@@ -18,19 +20,19 @@ namespace DevToys.Core.Formatter
/// <returns>Value converted to <see cref="NumberBaseFormat.Decimal"/></returns>
public static long? StringToBase(string value, NumberBaseFormat baseNumber)
{
- if (value.Length <= 0)
+ if (string.IsNullOrWhiteSpace(value))
{
return null;
}
- int length = value.Length;
int index = 0;
- Span<char> unformattedValue = RemoveFormatting(value);
+ Span<char> spanValue = value!.ToCharArray();
+ int length = RemoveFormatting(spanValue);
// Check for a sign
int sign = 1;
- if (unformattedValue[index] == '-')
+ if (spanValue[index] == '-')
{
if (baseNumber != NumberBaseFormat.Decimal)
{
@@ -40,65 +42,12 @@ namespace DevToys.Core.Formatter
sign = -1;
index++;
}
- else if (unformattedValue[index] == '+')
+ else if (spanValue[index] == '+')
{
index++;
}
- long result = 0;
- long maxVal;
-
- // Allow all non-decimal numbers to set the sign bit.
- if (baseNumber == NumberBaseFormat.Decimal)
- {
- maxVal = 0x7FFFFFFFFFFFFFFF / 10;
-
- // Read all of the digits and convert to a number
- while (index < length && IsDigit(unformattedValue[index], baseNumber.BaseNumber, out int current))
- {
- // Check for overflows - this is sufficient & correct.
- if (result > maxVal || result < 0)
- {
- throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
- }
-
- result = result * baseNumber.BaseNumber + current;
- index++;
- }
-
- if (result is < 0 and not 0x800000000000000)
- {
- throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
- }
- }
- else
- {
- maxVal =
- baseNumber.BaseNumber == 10 ? 0xfffffffffffffff / 10 :
- baseNumber.BaseNumber == 16 ? 0xfffffffffffffff / 16 :
- baseNumber.BaseNumber == 8 ? 0xfffffffffffffff / 8 :
- 0xfffffffffffffff / 2;
-
- // Read all of the digits and convert to a number
- while (index < unformattedValue.Length && IsDigit(unformattedValue[index], baseNumber.BaseNumber, out int current))
- {
- // Check for overflows - this is sufficient & correct.
- if (result > maxVal)
- {
- throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
- }
-
- long temp = result * baseNumber.BaseNumber + current;
-
- if (temp < result) // this means overflow as well
- {
- throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
- }
-
- result = temp;
- index++;
- }
- }
+ long result = GetLong(baseNumber, spanValue, index, length);
if (baseNumber == NumberBaseFormat.Decimal)
{
@@ -202,30 +151,125 @@ namespace DevToys.Core.Formatter
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
- public static Span<char> RemoveFormatting(string? value)
+ public static string RemoveFormatting(string? value)
{
if (string.IsNullOrWhiteSpace(value!))
{
- return Span<char>.Empty;
+ return string.Empty;
+ }
+
+ Span<char> valueSpan = value!.ToCharArray();
+ int length = RemoveFormatting(valueSpan);
+ var result = new StringBuilder();
+ for (int i = 0; i < length; i++)
+ {
+ result.Append(valueSpan[i]);
+ }
+ return result.ToString();
+ }
+
+ private static int RemoveFormatting(Span<char> values)
+ {
+ if (values.Length == 0)
+ {
+ return 0;
}
string currentCulture = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator;
- Span<char> values = new char[value!.Length];
- int valueIndex = 0;
+ int maxLength = 0;
for (int i = 0; i < values.Length; i++)
{
- if (!char.IsWhiteSpace(value[i]) && value[i] != Convert.ToChar(currentCulture))
+ if (!char.IsWhiteSpace(values[i]) && values[i] != Convert.ToChar(currentCulture))
+ {
+ values[maxLength] = values[i];
+ maxLength++;
+ }
+ }
+ return maxLength;
+ }
+
+ private static long GetLong(NumberBaseFormat baseNumber, ReadOnlySpan<char> spanValue, int index, int length)
+ {
+ ulong result = 0;
+ ulong maxVal = 0x7FFFFFFFFFFFFFFF / 10;
+
+ // Read all of the digits and convert to a number
+ while (index < length)
+ {
+ if (!IsValidChar(spanValue[index], baseNumber))
+ {
+ throw new InvalidOperationException(string.Format(Strings.ValueInvalid, baseNumber.DisplayName));
+ }
+
+ if (!IsDigit(spanValue[index], baseNumber.BaseNumber, out int current))
+ {
+ break;
+ }
+
+ if (baseNumber == NumberBaseFormat.Decimal)
{
- values[valueIndex] = value[i];
- valueIndex++;
+ // Check for overflows - this is sufficient & correct.
+ if (result > maxVal || result < 0)
+ {
+ throw new OverflowException(string.Format(Strings.ValueOverflow, long.MaxValue));
+ }
+
+ result = result * (ulong)baseNumber.BaseNumber + (ulong)current;
+ index++;
+ }
+ else
+ {
+ // Check for overflows - this is sufficient & correct.
+ if (result > maxVal)
+ {
+ throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
+ }
+
+ ulong temp = result * (ulong)baseNumber.BaseNumber + (ulong)current;
+
+ if (temp < result) // this means overflow as well
+ {
+ throw new OverflowException($"Unable to parse the current value exceded max value ({long.MaxValue})");
+ }
+
+ result = temp;
+ index++;
}
}
- return values;
+
+ if (baseNumber == NumberBaseFormat.Decimal && (long)result is < 0 and not 0x800000000000000)
+ {
+ throw new OverflowException(string.Format(Strings.ValueOverflow, long.MaxValue));
+ }
+ return (long)result;
+ }
+
+ private static bool IsValidChar(char c, NumberBaseFormat baseNumber)
+ {
+ switch (baseNumber.Value)
+ {
+ case Radix.Binary:
+ if (c is '0' or '1')
+ {
+ return true;
+ }
+ return false;
+ case Radix.Decimal:
+ case Radix.Octal:
+ return char.IsNumber(c);
+ case Radix.Hexdecimal:
+ return (char.IsNumber(c) ||
+ (c >= 'a' && c <= 'f') ||
+ (c >= 'A' && c <= 'F'));
+ default:
+ return true;
+ }
}
private static bool IsDigit(char c, int radix, out int result)
{
int tmp;
+
if ((uint)(c - '0') <= 9)
{
result = tmp = c - '0';
@@ -243,7 +287,6 @@ namespace DevToys.Core.Formatter
result = -1;
return false;
}
-
return tmp < radix;
}
}
diff --git a/src/tests/DevToys.Tests/Core/Formatter/BaseNumberFormatterTests.cs b/src/tests/DevToys.Tests/Core/Formatter/BaseNumberFormatterTests.cs
index a6fff9af5..dc2ee3488 100644
--- a/src/tests/DevToys.Tests/Core/Formatter/BaseNumberFormatterTests.cs
+++ b/src/tests/DevToys.Tests/Core/Formatter/BaseNumberFormatterTests.cs
@@ -1,4 +1,7 @@
-using DevToys.Core.Formatter;
+using System;
+using System.Globalization;
+using System.Threading;
+using DevToys.Core.Formatter;
using DevToys.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -8,13 +11,29 @@ namespace DevToys.Tests.Core.Formatter
public class BaseNumberFormatterTests
{
[DataTestMethod]
+ [DataRow("123ABC", 1194684)]
+ [DataRow("123 ABC", 1194684)]
+ [DataRow("123abc", 1194684)]
+ [DataRow("123 abc", 1194684)]
[DataRow("C6AEA155", 3333333333)]
[DataRow("C6AE A155", 3333333333)]
+ [DataRow("C6AE A15 5", 3333333333)]
public void HexadecimalToDecimal(string input, long expectedResult)
{
Assert.AreEqual(expectedResult, NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Hexadecimal));
}
+ [DataTestMethod]
+ [DataRow("123ZER")]
+ [DataRow("123&ZER")]
+ public void HexadecimalToDecimalShouldThrowInvalidOperationException(string input)
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
+ InvalidOperationException exception = Assert.ThrowsException<InvalidOperationException>(
+ () => NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Hexadecimal));
+ Assert.AreEqual("The current value isn't a valid Hexadecimal", exception.Message);
+ }
+
[DataTestMethod]
[DataRow("30653520525", 3333333333)]
[DataRow("30 653 520 525", 3333333333)]
@@ -23,6 +42,17 @@ namespace DevToys.Tests.Core.Formatter
Assert.AreEqual(expectedResult, NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Octal));
}
+ [DataTestMethod]
+ [DataRow("30653520525&")]
+ [DataRow("30 653 520 525 &")]
+ public void OctalToDecimalShouldThrowInvalidOperationException(string input)
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
+ InvalidOperationException exception = Assert.ThrowsException<InvalidOperationException>(
+ () => NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Octal));
+ Assert.AreEqual("The current value isn't a valid Octal", exception.Message);
+ }
+
[DataTestMethod]
[DataRow("000101001101", 333)]
[DataRow("0001 0100 1101", 333)]
@@ -33,6 +63,17 @@ namespace DevToys.Tests.Core.Formatter
Assert.AreEqual(expectedResult, NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Binary));
}
+ [DataTestMethod]
+ [DataRow("000101001101&")]
+ [DataRow("0001 0100 1101as")]
+ public void BinaryToDecimalShouldThrowInvalidOperationException(string input)
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
+ InvalidOperationException exception = Assert.ThrowsException<InvalidOperationException>(
+ () => NumberBaseFormatter.StringToBase(input, NumberBaseFormat.Binary));
+ Assert.AreEqual("The current value isn't a valid Binary", exception.Message);
+ }
+
[DataTestMethod]
[DataRow(3333333333, "C6AEA155", false)]
[DataRow(3333333333, "C6AE A155", true)]
@@ -58,5 +99,16 @@ namespace DevToys.Tests.Core.Formatter
{
Assert.AreEqual(expectedResult, NumberBaseFormatter.LongToBase(input, NumberBaseFormat.Binary, isFormatted));
}
+
+ [DataTestMethod]
+ [DataRow(null, "")]
+ [DataRow(" ", "")]
+ [DataRow(" C6AE A15 5 ", "C6AEA155")]
+ [DataRow("0001 0100 1101", "000101001101")]
+ [DataRow("C6AE A15 5", "C6AEA155")]
+ public void RemoveFormatting(string input, string expectedResult)
+ {
+ Assert.AreEqual(expectedResult, NumberBaseFormatter.RemoveFormatting(input));
+ }
}
}