summary refs log tree commit diff
path: root/LibGit/Extensions/IEnumerableExtensions.cs
blob: d8fc54dc344daee27a9ae571fab47fca8dc6a456 (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
using System.IO.Compression;
using System.Text;

namespace LibGit.Extensions;

public static class IEnumerableExtensions
{
    public static bool StartsWith<T>(this IEnumerable<T> list, IEnumerable<T> prefix)
    {
        return prefix.SequenceEqual(list.Take(prefix.Count()));
    }

    public static void HexDump(this IEnumerable<byte> bytes, int width = 32)
    {
        var data = new Queue<(string hex, char utf8)>(bytes.ToArray().Select(x => ($"{x:X2}", (char)x)).ToArray());
        while (data.Count > 0)
        {
            var line = data.Dequeue(Math.Min(width, data.Count)).ToArray();
            Console.WriteLine(
                string.Join(" ", line.Select(x => x.hex)).PadRight(width * 3)
                + " | "
                + string.Join("", line.Select(x => x.utf8))
                    .Replace('\n', '.')
                    .Replace('\r', '.')
                    .Replace('\0', '.')
                );
        }
    }

    public static string AsHexString(this IEnumerable<byte> bytes) => string.Join(' ', bytes.Select(x => $"{x:X2}"));
    public static string AsString(this IEnumerable<byte> bytes) => Encoding.UTF8.GetString(bytes.ToArray());
    
    
    //zlib decompress 
    public static byte[] ZlibDecompress(this IEnumerable<byte> bytes)
    {
        var inStream = new MemoryStream(bytes.ToArray());
        using ZLibStream stream = new ZLibStream(inStream, CompressionMode.Decompress);
        using var result = new MemoryStream();
        stream.CopyTo(result);
        stream.Flush();
        stream.Close();
        return result.ToArray();
    }
}