Skip to content

Commit 90676b2

Browse files
committed
feat: Add FirmwareVersion.Parse(versionString)
1 parent a4241ab commit 90676b2

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Yubico.YubiKey/src/Yubico/YubiKey/FirmwareVersion.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,36 @@ public FirmwareVersion(byte major, byte minor = 0, byte patch = 0)
6161
Minor = minor;
6262
Patch = patch;
6363
}
64+
65+
/// <summary>
66+
/// Parse a string of the form "major.minor.patch"
67+
/// </summary>
68+
/// <param name="versionString"></param>
69+
/// <returns>Returns a FirmwareVersion instance</returns>
70+
/// <exception cref="ArgumentNullException"></exception>
71+
/// <exception cref="ArgumentException"></exception>
72+
public static FirmwareVersion Parse(string versionString)
73+
{
74+
if (versionString is null)
75+
{
76+
throw new ArgumentNullException(nameof(versionString));
77+
}
78+
79+
string[] parts = versionString.Split('.');
80+
if (parts.Length != 3)
81+
{
82+
throw new ArgumentException("Must include major.minor.patch", nameof(versionString));
83+
}
84+
85+
if (!byte.TryParse(parts[0], out byte major) ||
86+
!byte.TryParse(parts[1], out byte minor) ||
87+
!byte.TryParse(parts[2], out byte patch))
88+
{
89+
throw new ArgumentException("Major, minor and patch must be valid numbers", nameof(versionString));
90+
}
91+
92+
return new FirmwareVersion(major, minor, patch);
93+
}
6494

6595
public static bool operator >(FirmwareVersion left, FirmwareVersion right)
6696
{

Yubico.YubiKey/tests/unit/Yubico/YubiKey/FirmwareVersionTests.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,38 @@ namespace Yubico.YubiKey
2020
{
2121
public class FirmwareVersionTests
2222
{
23+
[Fact]
24+
public void Parse_GivenValidString_ReturnsFirmwareVersion()
25+
{
26+
// Arrange
27+
28+
string validString = "1.2.3";
29+
30+
// Act
31+
32+
var fw = FirmwareVersion.Parse(validString);
33+
34+
// Assert
35+
36+
Assert.Equal(1, fw.Major);
37+
Assert.Equal(2, fw.Minor);
38+
Assert.Equal(3, fw.Patch);
39+
}
40+
41+
42+
[Fact]
43+
public void Parse_GivenInvalidString_ThrowsArgumentException()
44+
{
45+
// Arrange
46+
47+
string invalidString = "1.2";
48+
49+
// Act & Assert
50+
51+
Assert.Throws<ArgumentException>(() => FirmwareVersion.Parse(invalidString));
52+
}
53+
54+
2355
[Fact]
2456
public void Major_GetSet_Succeeds()
2557
{

0 commit comments

Comments
 (0)