about summary refs log tree commit diff
path: root/IrcTokens/Extensions.cs
blob: 2eee7dc08e516c064b018bd53b984595ea32909e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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();
        }
    }
}