Fix strlcpy

This commit is contained in:
Alex Barney 2024-05-11 21:48:29 -07:00
parent 6599c5977b
commit c238cf63b0
2 changed files with 48 additions and 4 deletions

View file

@ -38,14 +38,15 @@ public static class StringUtils
return i; return i;
} }
public static int Strlcpy(Span<byte> dest, ReadOnlySpan<byte> source, int maxLen) public static int Strlcpy(Span<byte> dest, ReadOnlySpan<byte> source, int size)
{ {
int maxLenLocal = Math.Min(Math.Min(dest.Length, source.Length), maxLen); int destSize = Math.Min(dest.Length, size);
int i = 0; int i = 0;
if (maxLenLocal > 0) if (destSize > 0)
{ {
for (; i < maxLenLocal - 1 && source[i] != 0; i++) int maxCopySize = Math.Min(destSize - 1, source.Length);
for (; i < maxCopySize && source[i] != 0; i++)
{ {
dest[i] = source[i]; dest[i] = source[i];
} }

View file

@ -0,0 +1,43 @@
using System;
using System.Text;
using LibHac.Util;
using Xunit;
namespace LibHac.Tests.Util;
public class StringUtilTests
{
[Theory]
[InlineData("abcdef", 3, 1, "", 6)]
[InlineData("abcdef", 3, 3, "ab", 6)]
[InlineData("abcdef", 3, 6, "ab", 6)]
[InlineData("abcdef", 6, 6, "abcde", 6)]
[InlineData("abcdef", 7, 6, "abcde", 6)]
[InlineData("abcdef", 7, 7, "abcdef", 6)]
[InlineData("abcdef", 10, 10, "abcdef", 6)]
public void Strlcpy_TestKnownInputs(string source, int destBufferSize, int size, string expected, int expectedReturnValue)
{
const byte paddingValue = (byte)'X';
byte[] src = Encoding.ASCII.GetBytes(source);
byte[] expectedBytes = Encoding.ASCII.GetBytes(expected);
byte[] dest = new byte[destBufferSize];
dest.AsSpan().Fill(paddingValue);
int returnValue = StringUtils.Strlcpy(dest, src, size);
Assert.Equal(expectedReturnValue, returnValue);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], dest[i]);
}
Assert.Equal(0, dest[expectedBytes.Length]);
for (int i = expectedBytes.Length + 1; i < dest.Length; i++)
{
Assert.Equal(paddingValue, dest[i]);
}
}
}