summary refs log tree commit diff
path: root/LibGit/Extensions/StreamExtensions.cs
blob: 90bd35a9ebffb93a5968b3b0e3343a3073d72ce9 (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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System.IO.Compression;
using System.Runtime.InteropServices;

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");

        var buffer = new byte[count];
        var readCount = stream.Read(buffer, 0, (int)count);
        for (int i = 0; i < readCount; i++)
        {
            yield return buffer[i];
        }
    }

    public static byte[] ReadBlock(this Stream stream, int count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> buffer = stackalloc byte[count];
        stream.ReadExactly(buffer);
        return buffer.ToArray();
    }

    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");

        Span<byte> b = stackalloc byte[4];
        stream.ReadExactly(b);
        return ((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
    }

    public static int[] MultiReadInt32BE(this Stream stream, int count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> b = stackalloc byte[4 * count];
        stream.ReadExactly(b);
        int[] results = new int[count];
        for (int i = 0; i < count; i++)
        {
            results[i] = (b[i * 4 + 0] << 24) | (b[i * 4 + 1] << 16) | (b[i * 4 + 2] << 8) | b[i * 4 + 3];
        }

        return results;
    }

    public static uint ReadUInt32BE(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> b = stackalloc byte[4];
        stream.ReadExactly(b);
        return (uint)((b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]);
    }

    public static uint[] MultiReadUInt32BE(this Stream stream, int count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> b = count >= 32767 ? new byte[4 * count] : stackalloc byte[4 * count];
        stream.ReadExactly(b);
        uint[] results = new uint[count];
        for (int i = 0; i < count; i++)
        {
            results[i] = (uint)((b[i * 4 + 0] << 24) | (b[i * 4 + 1] << 16) | (b[i * 4 + 2] << 8) | b[i * 4 + 3]);
        }

        return results;
    }

    public static ulong ReadUInt64BE(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> b = stackalloc byte[8];
        stream.ReadExactly(b);
        return ((ulong)b[0] << 56) | ((ulong)b[1] << 48) | ((ulong)b[2] << 40) | ((ulong)b[3] << 32) |
               ((ulong)b[4] << 24) | ((ulong)b[5] << 16) | ((ulong)b[6] << 8) | b[7];
    }

    public static ulong[] MultiReadUInt64BE(this Stream stream, int count)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<byte> b = count >= 16384 ? new byte[8 * count] : stackalloc byte[8 * count];
        stream.ReadExactly(b);
        ulong[] results = new ulong[count];
        for (int i = 0; i < count; i++)
        {
            results[i] = ((ulong)b[i * 8 + 0] << 56) | ((ulong)b[i * 8 + 1] << 48) | ((ulong)b[i * 8 + 2] << 40) | ((ulong)b[i * 8 + 3] << 32) |
                         ((ulong)b[i * 8 + 4] << 24) | ((ulong)b[i * 8 + 5] << 16) | ((ulong)b[i * 8 + 6] << 8) | b[i * 8 + 7];
        }

        return results;
    }

    public static T[] MultiReadInlineArray<T>(this Stream stream, int count) where T : unmanaged
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        Span<T> buffer = count >= 8192 ? new T[count] : stackalloc T[count];
        Span<byte> byteBuffer = MemoryMarshal.AsBytes(buffer);
        stream.ReadExactly(byteBuffer);
        return buffer.ToArray();
    }

    //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;
    }

    // for some reason this is special...
    public static int ReadGitPackOffsetModifiedVLQ(this Stream stream)
    {
        if (!stream.CanRead)
            throw new InvalidOperationException("Can't read a non-readable stream");

        int b = stream.ReadByte();
        int result = b & 0x7F;

        while ((b & 0x80) != 0)
        {
            b = stream.ReadByte();
            result = ((result + 1) << 7) | (b & 0x7F);
        }

        return result;
    }
}