diff options
author | Ben Harris <ben@tilde.team> | 2020-05-14 23:06:10 -0400 |
---|---|---|
committer | Ben Harris <ben@tilde.team> | 2020-05-14 23:17:47 -0400 |
commit | 21f1e95fb8e935134a969bc3d729964d8d2aadfa (patch) | |
tree | db2be27e9b5ac48e19f92b56cbad68ab59f7099e /IRCTokens/Extensions.cs | |
parent | 304df7805b9925c2edd992fd4177eef80197f807 (diff) |
rename Irc to IRC
Diffstat (limited to 'IRCTokens/Extensions.cs')
-rw-r--r-- | IRCTokens/Extensions.cs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/IRCTokens/Extensions.cs b/IRCTokens/Extensions.cs new file mode 100644 index 0000000..e346a43 --- /dev/null +++ b/IRCTokens/Extensions.cs @@ -0,0 +1,62 @@ +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) return Array.Empty<byte>(); + + var byteList = new List<byte>(bytes); + var i = 0; + + if (!byteList.Any()) return byteList.ToArray(); + + while (byteList[i] == separator) + { + byteList.RemoveAt(i); + i++; + } + + i = byteList.Count - 1; + while (byteList[i] == separator) + { + byteList.RemoveAt(i); + i--; + } + + return byteList.ToArray(); + } + } +} |