-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathVarInt.cs
265 lines (250 loc) · 10.1 KB
/
VarInt.cs
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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Ipfs
{
/// <summary>
/// A codec for a variable integer.
/// </summary>
/// <remarks>
/// A <b>VarInt</b> is encoded in network byte order (Big Endian). Each byte (except the last) contains 7 bits
/// of information with the most significant bit set to 1. The last byte has MSB set to 0.
/// <para>
/// Negative values are not allowed. When encountered a <see cref="NotSupportedException"/> is thrown.
/// </para>
/// <para>
/// Adds the following extension methods to <see cref="Stream"/>
/// <list type="bullet">
/// <item><description><see cref="ReadVarint32"/></description></item>
/// <item><description><see cref="ReadVarint64"/></description></item>
/// <item><description><see cref="WriteVarint"/></description></item>
/// </list>
/// </para>
/// </remarks>
/// <seealso href="https://developers.google.com/protocol-buffers/docs/encoding#varints"/>
public static class Varint
{
/// <summary>
/// Convert the value to its variable integer encoding.
/// </summary>
/// <param name="value">
/// The value to convert.
/// </param>
/// <returns>
/// A byte array representing the <paramref name="value"/> as
/// a variable integer.
/// </returns>
public static byte[] Encode(long value)
{
using var stream = new MemoryStream(64);
stream.WriteVarint(value);
return stream.ToArray();
}
/// <summary>
/// The number of bytes required to encode the value.
/// </summary>
/// <param name="value">A positive integer value.</param>
/// <returns>
/// The number of bytes required to encode the value.
/// </returns>
public static int RequiredBytes(long value)
{
return Encode(value).Length;
}
/// <summary>
/// Convert the byte array to an <see cref="int"/>.
/// </summary>
/// <param name="bytes">
/// A varint encoded byte array containing the variable integer.
/// </param>
/// <param name="offset">
/// Offset into <paramref name="bytes"/> to start reading from.
/// </param>
/// <returns>The integer value.</returns>
public static int DecodeInt32 (byte[] bytes, int offset = 0)
{
using var stream = new MemoryStream(bytes, false);
stream.Position = offset;
return stream.ReadVarint32();
}
/// <summary>
/// Convert the byte array to a <see cref="long"/>.
/// </summary>
/// <param name="bytes">
/// A varint encoded byte array containing the variable integer.
/// </param>
/// <param name="offset">
/// Offset into <paramref name="bytes"/> to start reading from.
/// </param>
/// <returns>The integer value.</returns>
public static long DecodeInt64(byte[] bytes, int offset = 0)
{
using var stream = new MemoryStream(bytes, false);
stream.Position = offset;
return stream.ReadVarint64();
}
/// <summary>
/// Writes the variable integer encoding of the value to
/// a stream.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to write to.
/// </param>
/// <param name="value">
/// A non-negative value to write.
/// </param>
/// <exception cref="NotSupportedException">
/// When <paramref name="value"/> is negative.
/// </exception>
public static void WriteVarint(this Stream stream, long value)
{
stream.WriteVarintAsync(value).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Reads a variable integer from the stream.
/// </summary>
/// <param name="stream">
/// A varint encoded <see cref="Stream"/>.
/// </param>
/// <exception cref="EndOfStreamException">
/// When the no bytes exist in the <paramref name="stream"/>.
/// </exception>
/// <exception cref="InvalidDataException">
/// When the varint value is greater than <see cref="int.MaxValue"/>.
/// </exception>
/// <returns>The integer value.</returns>
public static int ReadVarint32(this Stream stream)
{
return stream.ReadVarint32Async().ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Reads a variable integer from the stream.
/// </summary>
/// <param name="stream">
/// A varint encoded <see cref="Stream"/>.
/// </param>
/// <exception cref="EndOfStreamException">
/// When the no bytes exist in the <paramref name="stream"/>.
/// </exception>
/// <exception cref="InvalidDataException">
/// When the varint value is greater than <see cref="long.MaxValue"/>.
/// </exception>
/// <returns>The integer value.</returns>
public static long ReadVarint64(this Stream stream)
{
return stream.ReadVarint64Async().ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Writes the variable integer encoding of the value to
/// a stream.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> to write to.
/// </param>
/// <param name="value">
/// A non-negative value to write.
/// </param>
/// <param name="cancel">
/// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised.
/// </param>
/// <returns>
/// A task that represents the asynchronous operation.
/// </returns>
/// <exception cref="NotSupportedException">
/// When <paramref name="value"/> is negative.
/// </exception>
public static async Task WriteVarintAsync(this Stream stream, long value, CancellationToken cancel = default)
{
if (value < 0)
{
throw new NotSupportedException("Negative values are not allowed for a Varint");
}
var bytes = new byte[10];
int i = 0;
do
{
byte v = (byte)(value & 0x7F);
if (value > 0x7F)
{
v |= 0x80;
}
bytes[i++] = v;
value >>= 7;
} while (value != 0);
await stream.WriteAsync(bytes, 0, i, cancel).ConfigureAwait(false);
}
/// <summary>
/// Reads a variable integer from the stream.
/// </summary>
/// <param name="stream">
/// A varint encoded <see cref="Stream"/>.
/// </param>
/// <param name="cancel">
/// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised.
/// </param>
/// <returns>
/// A task that represents the asynchronous operation. The task's result
/// is the integer value in the <paramref name="stream"/>.
/// </returns>
/// <exception cref="EndOfStreamException">
/// When the no bytes exist in the <paramref name="stream"/>.
/// </exception>
/// <exception cref="InvalidDataException">
/// When the varint value is greater than <see cref="int.MaxValue"/>.
/// </exception>
public static async Task<int> ReadVarint32Async(this Stream stream, CancellationToken cancel = default)
{
var value = await stream.ReadVarint64Async(cancel).ConfigureAwait(false);
return value > int.MaxValue ? throw new InvalidDataException("Varint value is bigger than an Int32.MaxValue") : (int)value;
}
/// <summary>
/// Reads a variable integer from the stream.
/// </summary>
/// <param name="stream">
/// A varint encoded <see cref="Stream"/>.
/// </param>
/// <param name="cancel">
/// Is used to stop the task. When cancelled, the <see cref="TaskCanceledException"/> is raised.
/// </param>
/// <exception cref="InvalidDataException">
/// When the varint value is greater than <see cref="long.MaxValue"/>.
/// </exception>
/// <exception cref="EndOfStreamException">
/// When the no bytes exist in the <paramref name="stream"/>.
/// </exception>
/// <returns>
/// A task that represents the asynchronous operation. The task's result
/// is the integer value in the <paramref name="stream"/>.
/// </returns>
public static async Task<long> ReadVarint64Async(this Stream stream, CancellationToken cancel = default)
{
long value = 0;
int shift = 0;
int bytesRead = 0;
var buffer = new byte[1];
while (true)
{
if (1 != await stream.ReadAsync(buffer, 0, 1, cancel).ConfigureAwait(false))
{
if (bytesRead == 0)
{
throw new EndOfStreamException();
}
throw new InvalidDataException("Varint is not terminated");
}
if (++bytesRead > 9)
{
throw new InvalidDataException("Varint value is bigger than an Int64.MaxValue");
}
var b = buffer[0];
value |= (long)(b & 0x7F) << shift;
if (b < 0x80)
{
return value;
}
shift += 7;
}
}
}
}