summary refs log tree commit diff
path: root/LibGit/Extensions/StreamExtensions.cs
blob: 6555783a2513ee64122efe2d4d67a09c191fc5cd (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
using System.IO.Compression;

namespace LibGit.Extensions;

public static class StreamExtensions
{
    private const bool _debug = false;

    public static long Remaining(this Stream stream)
    {
        //if (_debug) Console.WriteLine($"stream pos: {stream.Position}, stream len: {stream.Length}, stream rem: {stream.Length - stream.Position}");
        return stream.Length - stream.Position;
    }

    public static int Peek(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't peek a non-readable stream");
        if (!stream.CanSeek)
            throw new InvalidOperationException("Can't peek a non-seekable stream");

        int peek = stream.ReadByte();
        if (peek != -1)
            stream.Seek(-1, SeekOrigin.Current);

        return peek;
    }

    public static IEnumerable<byte> Peek(this Stream stream, long count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't peek a non-readable stream");
        if (!stream.CanSeek)
            throw new InvalidOperationException("Can't peek a non-seekable stream");
        long i;
        for (i = 0; i < count; i++)
        {
            int peek = stream.ReadByte();
            if (peek == -1)
            {
                if(_debug) Console.WriteLine($"Can't peek {count} bytes, only {i} bytes remaining");
                stream.Seek(-i, SeekOrigin.Current);
                yield break;
            }

            yield return (byte)peek;
        }
        stream.Seek(-i, SeekOrigin.Current);
    }

    public static IEnumerable<byte> ReadBytes(this Stream stream, long count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");
        if (!stream.CanSeek)
            throw new InvalidOperationException("Can't read a non-seekable stream");

        for (long i = 0; i < count; i++)
        {
            int read = stream.ReadByte();
            if (read == -1)
                yield break;
            yield return (byte)read;
        }
    }

    public static bool StartsWith(this Stream stream, IEnumerable<byte> sequence)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");
        if (!stream.CanSeek)
            throw new InvalidOperationException("Can't read a non-seekable stream");

        if (_debug)
        {
            Console.WriteLine($"Expected: {sequence.AsHexString()} ({sequence.AsString()})");
            Console.WriteLine($"Actual:   {stream.Peek(sequence.Count()).AsHexString()} ({stream.Peek(sequence.Count()).AsString()})");
        }
        
        int readCount = 0;
        foreach (int b in sequence)
        {
            int read = stream.ReadByte();
            readCount++;
            if (read == -1)
            {
                stream.Seek(-readCount, SeekOrigin.Current);
                return false;
            }
            
            if (read != b)
            {
                if (_debug)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("^^".PadLeft(readCount * 3 + 9));
                    Console.ResetColor();
                }

                stream.Seek(-readCount, SeekOrigin.Current);
                return false;
            }
        }
        stream.Seek(-readCount, SeekOrigin.Current);
        
        return true;
    }

    public static bool StartsWith(this Stream stream, string ascii_seq)
    {
        return stream.StartsWith(ascii_seq.Select(x => (byte)x));
    }

    public static Stream Skip(this Stream stream, long count = 1)
    {
        if (!stream.CanSeek)
            throw new InvalidOperationException("Can't skip a non-seekable stream");
        stream.Seek(count, SeekOrigin.Current);
        return stream;
    }

    public static IEnumerable<byte> ReadNullTerminatedField(this Stream stream, IEnumerable<byte>? binaryPrefix = null, string? asciiPrefix = null) => ReadTerminatedField(stream: stream, terminator: 0x00, binaryPrefix: binaryPrefix, asciiPrefix: asciiPrefix);
    public static IEnumerable<byte> ReadSpaceTerminatedField(this Stream stream, IEnumerable<byte>? binaryPrefix = null, string? asciiPrefix = null) => ReadTerminatedField(stream: stream, terminator: 0x20, binaryPrefix: binaryPrefix, asciiPrefix: asciiPrefix);
    public static IEnumerable<byte> ReadTerminatedField(this Stream stream, byte terminator, IEnumerable<byte>? binaryPrefix = null, string? asciiPrefix = null)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");
        if (binaryPrefix != null)
            if (!stream.StartsWith(binaryPrefix))
                throw new InvalidDataException($"Binary prefix {stream.Peek(binaryPrefix.Count()).AsHexString()} does not match expected value of {binaryPrefix.AsHexString()}!");
            else stream.Skip(binaryPrefix.Count());
        else if (asciiPrefix != null)
            if (!stream.StartsWith(asciiPrefix))
                throw new InvalidDataException($"Text prefix {stream.Peek(asciiPrefix.Length).AsHexString()} ({stream.Peek(asciiPrefix.Length).AsString()}) does not match expected value of {asciiPrefix.AsBytes().AsHexString()} ({asciiPrefix})!");
            else stream.Skip(asciiPrefix.Length);

        var read = 0;
        while (stream.Peek() != terminator)
        {
            if (_debug) Console.WriteLine($"ReadTerminatedField -- pos: {stream.Position}/+{stream.Remaining()}/{stream.Length} | next: {(char)stream.Peek()} | Length: {read}");
            if (stream.Peek() == -1)
            {
                Console.WriteLine($"Warning: Reached end of stream while reading null-terminated field");
                yield break;
            }

            read++;
            yield return (byte)stream.ReadByte();
        }

        if (stream.Peek() == terminator) stream.Skip();
    }
    
    public static IEnumerable<byte> ReadToEnd(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        while (stream.Peek() != -1)
            yield return (byte)stream.ReadByte();
    }
    
    public static int ReadInt32BE(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        var bytes = stream.ReadBytes(4).ToArray();
        
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        
        Console.WriteLine("ReadInt32BE: " + bytes.AsHexString() + " => " + BitConverter.ToInt32(bytes));
        return BitConverter.ToInt32(bytes);
    }
    
    //read variable length number
    public static int ReadVLQ(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        int result = 0;
        int shift = 0;
        byte b;
        do
        {
            b = (byte)stream.ReadByte();
            result |= (b & 0b0111_1111) << shift;
            shift += 7;
        } while ((b & 0b1000_0000) != 0);

        return result;
    }
    public static int ReadVLQBigEndian(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        int result = 0;
        int shift = 0;
        byte b;
        do
        {
            b = (byte)stream.ReadByte();
            result = (result << 7) | (b & 0b0111_1111);
        } while ((b & 0b1000_0000) != 0);

        return result;
    }
}