Skip to content

Commit

Permalink
Correctly decode uint options from bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
NZSmartie committed Aug 27, 2017
1 parent b1719d2 commit 45d9715
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
20 changes: 20 additions & 0 deletions CoAPNet.Tests/CoapOptionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -370,5 +370,25 @@ public void TestOptionSize1()
Assert.AreEqual(OptionType.UInt, option.Type, "Type is incorrect");
Assert.AreEqual(0u, option.DefaultUInt, "Default value is incorrect");
}

[TestCase(0u, 0, new byte[] { })]
[TestCase(0x12u, 1, new byte[] {0x12})]
[TestCase(0x1234u, 2, new byte[] {0x12, 0x34})]
[TestCase(0x123456u, 3, new byte[] {0x12, 0x34, 0x56})]
[TestCase(0x12345678u, 4, new byte[] {0x12, 0x34, 0x56, 0x78})]
public void TestValueOption(uint value, int length, byte[] expected)
{
var optionToBytes = new CoapOption(0, type: OptionType.UInt);

optionToBytes.ValueUInt = value;
Assert.AreEqual(length, optionToBytes.Length);
Assert.AreEqual(expected, optionToBytes.GetBytes());

var optionFromBytes = new CoapOption(0, type: OptionType.UInt);

optionFromBytes.FromBytes(expected);
Assert.AreEqual(length, optionFromBytes.Length);
Assert.AreEqual(value, optionFromBytes.ValueUInt);
}
}
}
18 changes: 11 additions & 7 deletions CoAPNet/CoapOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,12 @@ public byte[] GetBytes()

public void FromBytes(byte[] data)
{
if (_type == OptionType.Empty && (data == null || data.Length > 0))
throw new InvalidCastException("Empty option does not accept any data");
if (_type == OptionType.Empty)
{
if ((data?.Length ?? 0) > 0)
throw new InvalidCastException("Empty option does not accept any data");
return;
}

if (_type == OptionType.Opaque)
{
Expand All @@ -312,15 +316,15 @@ public void FromBytes(byte[] data)
}


uint value = 0;
uint i=0, value = 0;
if (data.Length == 4)
value = (uint)(data[3] << 24);
value = (uint)(data[i++] << 24);
if (data.Length >= 3)
value |= (uint)(data[2] << 16);
value |= (uint)(data[i++] << 16);
if (data.Length >= 2)
value |= (uint)(data[1] << 8);
value |= (uint)(data[i++] << 8);
if (data.Length >= 1)
value |= data[0];
value |= data[i++];
ValueUInt = value;
}

Expand Down

0 comments on commit 45d9715

Please sign in to comment.