Skip to content

Commit

Permalink
adding concat byte extension #36
Browse files Browse the repository at this point in the history
  • Loading branch information
alec1o committed Dec 11, 2024
1 parent 87d5d5a commit 7e1ed96
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
36 changes: 36 additions & 0 deletions src/src/extension/ByteExtension.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ByEx = Byter.ByterExtension;

Expand All @@ -14,5 +16,39 @@ public static string GetString(this byte[] content, Encoding encoding)
{
return ByEx.IsNull(content) ? ByEx.DEFAULT_STRING_VALUE : encoding.GetString(content);
}

public static byte[] Concat(this byte[] value, params byte[][] values)
{
return Concat(value, false, values);
}

public static byte[] ConcatInverse(this byte[] value, params byte[][] values)
{
return Concat(value, true, values);
}

public static byte[] Concat(this byte[] value, bool invert, params byte[][] values)
{
var list = new List<byte[]> { value };

list.AddRange(values);

if (!invert || list.Count <= 1) return list.SelectMany(x => x).ToArray();

var reversed = new List<byte[]>();

var count = list.Count - 1;

while (list.Count > 0)
{
reversed.Add(list[count]);
list.RemoveAt(count);
count--;
}

list.Clear();

return reversed.SelectMany(x => x).ToArray();
}
}
}
24 changes: 20 additions & 4 deletions test/extension/ByteExtensionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,37 @@ public void GetString()
var utf8Bytes = BaseText.GetBytes(Encoding.UTF8);
var utf16Bytes = BaseText.GetBytes(Encoding.Unicode);
var utf32Bytes = BaseText.GetBytes(Encoding.UTF32);

Assert.Equal(BaseText, utf8Bytes.GetString(Encoding.UTF8));
Assert.Equal(BaseText, utf16Bytes.GetString(Encoding.Unicode));
Assert.Equal(BaseText, utf32Bytes.GetString(Encoding.UTF32));

Assert.NotEqual(BaseText, utf16Bytes.GetString(Encoding.UTF8));
Assert.NotEqual(BaseText, utf32Bytes.GetString(Encoding.Unicode));
Assert.NotEqual(BaseText, utf8Bytes.GetString(Encoding.UTF32));
}

[Fact]
public void Nullable()
{
var result = string.Empty;
Assert.Equal(result, Array.Empty<byte>().GetString());
Assert.Equal(result, ByteExtension.GetString(null!));
}
}

[Fact]
public void Concat()
{
byte[] part1 = [1, 2, 3];
byte[] part2 = [4, 5, 6];
byte[] part3 = [7, 8, 9];

Assert.Equal([1, 2, 3, /**/ 4, 5, 6], part1.Concat(part2));
Assert.Equal([1, 2, 3, /**/ 4, 5, 6], part1.Concat(false, part2));
Assert.Equal([1, 2, 3, /**/ 4, 5, 6, /**/7, 8, 9], part1.Concat(false, part2, part3));

Assert.Equal([4, 5, 6, /**/ 1, 2, 3], part1.ConcatInverse(part2));
Assert.Equal([4, 5, 6, /**/ 1, 2, 3], part1.Concat(true, part2));
Assert.Equal([7, 8, 9, /**/ 4, 5, 6, /**/ 1, 2, 3,], part1.Concat(true, part2, part3));
}
}

0 comments on commit 7e1ed96

Please sign in to comment.