diff options
author | Ben Harris <ben@tilde.team> | 2020-04-28 11:08:01 -0400 |
---|---|---|
committer | Ben Harris <ben@tilde.team> | 2020-04-28 11:08:01 -0400 |
commit | 6a0b8dc22fc86a5de37278231f3f8418afc9b836 (patch) | |
tree | 2cac03089c4d15bfe5a66b30e2b2ee5be5255f49 /IrcTokens/Extensions.cs | |
parent | 70e2eb8e7debc342d46a9ca08d70725cb624e19d (diff) |
Fix stateful decoder i think
Diffstat (limited to 'IrcTokens/Extensions.cs')
-rw-r--r-- | IrcTokens/Extensions.cs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/IrcTokens/Extensions.cs b/IrcTokens/Extensions.cs new file mode 100644 index 0000000..2eee7dc --- /dev/null +++ b/IrcTokens/Extensions.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace IrcTokens +{ + public static class Extensions + { + public static IEnumerable<byte[]> Split(this byte[] bytes, byte separator) + { + if (bytes == null || bytes.Length == 0) return new List<byte[]>(); + + var newLineIndices = bytes.Select((b, i) => b == separator ? i : -1).Where(i => i != -1).ToArray(); + var lines = new byte[newLineIndices.Length + 1][]; + var currentIndex = 0; + var arrIndex = 0; + + for (var i = 0; i < newLineIndices.Length && currentIndex < bytes.Length; ++i) + { + var n = new byte[newLineIndices[i] - currentIndex]; + Array.Copy(bytes, currentIndex, n, 0, newLineIndices[i] - currentIndex); + currentIndex = newLineIndices[i] + 1; + lines[arrIndex++] = n; + } + + // Handle the last string at the end of the array if there is one. + if (currentIndex < bytes.Length) + lines[arrIndex] = bytes.Skip(currentIndex).ToArray(); + else if (arrIndex == newLineIndices.Length) + // We had a separator character at the end of a string. Rather than just allowing + // a null character, we'll replace the last element in the array with an empty string. + lines[arrIndex] = Array.Empty<byte>(); + + return lines.ToArray(); + } + + public static byte[] Trim(this IEnumerable<byte> bytes, byte separator) + { + if (bytes == null || !bytes.Any()) return Array.Empty<byte>(); + var byteList = new List<byte>(bytes); + var i = 0; + + while (byteList[i] == separator) + { + byteList.RemoveAt(i); + i++; + } + + i = byteList.Count - 1; + while (byteList[i] == separator) + { + byteList.RemoveAt(i); + i--; + } + + return byteList.ToArray(); + } + } +} |