Skip to content

Commit

Permalink
Fixed GetVarSize (#3594)
Browse files Browse the repository at this point in the history
* Fixed `GetVarSize`

* Added unit tests

* revert `global.json`

* Fixed test for `old` method

* revert `global.json`

* Update src/Neo.Extensions/UnsafeData.cs

---------

Co-authored-by: Shargon <[email protected]>
  • Loading branch information
cschuchardt88 and shargon authored Nov 26, 2024
1 parent b2cbfc0 commit 6e00052
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/Neo.Extensions/UnsafeData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ public static class UnsafeData
/// </summary>
/// <param name="value">The length of the data.</param>
/// <returns>The size of variable-length of the data.</returns>
public static int GetVarSize(int value)
public static byte GetVarSize(long value)
{
if (value < 0xFD)
return sizeof(byte);
else if (value <= 0xFFFF)
else if (value <= ushort.MaxValue)
return sizeof(byte) + sizeof(ushort);
else
else if (value <= uint.MaxValue)
return sizeof(byte) + sizeof(uint);
else
return sizeof(byte) + sizeof(ulong);
}
}
}
29 changes: 25 additions & 4 deletions tests/Neo.Extensions.Tests/UT_UnsafeData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,33 @@ public class UT_UnsafeData
[TestMethod]
public void TestGetVarSizeInt()
{
for (int i = 0; i < 3; i++)
for (int i = 0; i < 4; i++)
{
if (i == 0)
{
int result = UnsafeData.GetVarSize(1);
int old = OldGetVarSize(1);
Assert.AreEqual(1, result);
Assert.AreEqual(1, old);
}
else if (i == 1)
{
int result = UnsafeData.GetVarSize(0xFFFF);
int result = UnsafeData.GetVarSize(ushort.MaxValue);
int old = OldGetVarSize(ushort.MaxValue);
Assert.AreEqual(3, result);
Assert.AreEqual(3, old);
}
else
else if (i == 2)
{
int result = UnsafeData.GetVarSize(0xFFFFFF);
int result = UnsafeData.GetVarSize(uint.MaxValue);
int old = OldGetVarSize(int.MaxValue);
Assert.AreEqual(5, result);
Assert.AreEqual(5, old);
}
else
{
int result = UnsafeData.GetVarSize(long.MaxValue);
Assert.AreEqual(9, result);
}
}
}
Expand Down Expand Up @@ -159,5 +170,15 @@ enum TestEnum6 : long
{
case1 = 1, case2 = 2
}

public static int OldGetVarSize(int value)
{
if (value < 0xFD)
return sizeof(byte);
else if (value <= ushort.MaxValue)
return sizeof(byte) + sizeof(ushort);
else
return sizeof(byte) + sizeof(uint);
}
}
}

0 comments on commit 6e00052

Please sign in to comment.