Skip to content

Commit a883016

Browse files
committed
Add error handling and conversion methods for Integer32 to ErrorCode #187
1 parent 1f60edd commit a883016

2 files changed

Lines changed: 79 additions & 1 deletion

File tree

SharpSnmpLib/CompatibilityExtensions.cs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,38 @@ public static ErrorCode ToErrorCode(this ErrorCode value)
4141
/// </summary>
4242
public static ErrorCode ToErrorCode(this Integer32 value)
4343
{
44-
return (ErrorCode)value.Value;
44+
if (!TryToErrorCode(value, out var code))
45+
{
46+
throw new InvalidCastException(
47+
string.Format(
48+
CultureInfo.InvariantCulture,
49+
"Integer32 value {0} cannot be converted to a known ErrorCode.",
50+
value.Value));
51+
}
52+
53+
return code;
54+
}
55+
56+
/// <summary>
57+
/// Tries to convert an <see cref="Integer32"/> value to <see cref="ErrorCode"/>.
58+
/// </summary>
59+
public static bool TryToErrorCode(this Integer32 value, out ErrorCode code)
60+
{
61+
var raw = value.Value;
62+
if (raw < byte.MinValue || raw > byte.MaxValue)
63+
{
64+
code = default;
65+
return false;
66+
}
67+
68+
code = (ErrorCode)(byte)raw;
69+
if (!Enum.IsDefined(code))
70+
{
71+
code = default;
72+
return false;
73+
}
74+
75+
return true;
4576
}
4677

4778
/// <summary>
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using DotNetSnmp.Asn1.SyntaxObjects;
2+
using Lextm.SharpSnmpLib;
3+
using Xunit;
4+
5+
namespace DotNetSnmp.Test;
6+
7+
public class CompatibilityExtensionsErrorCodeTest
8+
{
9+
[Fact]
10+
public void ToErrorCode_KnownValue_ReturnsCode()
11+
{
12+
var raw = new Integer32((int)ErrorCode.TooBig);
13+
14+
var code = raw.ToErrorCode();
15+
16+
Assert.Equal(ErrorCode.TooBig, code);
17+
}
18+
19+
[Fact]
20+
public void ToErrorCode_UnknownValue_Throws()
21+
{
22+
var raw = new Integer32(99);
23+
24+
Assert.Throws<InvalidCastException>(() => raw.ToErrorCode());
25+
}
26+
27+
[Fact]
28+
public void TryToErrorCode_KnownValue_ReturnsTrue()
29+
{
30+
var raw = new Integer32((int)ErrorCode.NoError);
31+
32+
var ok = raw.TryToErrorCode(out var code);
33+
34+
Assert.True(ok);
35+
Assert.Equal(ErrorCode.NoError, code);
36+
}
37+
38+
[Fact]
39+
public void TryToErrorCode_UnknownValue_ReturnsFalse()
40+
{
41+
var raw = new Integer32(-1);
42+
43+
var ok = raw.TryToErrorCode(out _);
44+
45+
Assert.False(ok);
46+
}
47+
}

0 commit comments

Comments
 (0)