-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpbInput.pas
471 lines (409 loc) · 11.1 KB
/
pbInput.pas
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// author this port to delphi - Marat Shaymardanov, Tomsk 2007, 2013
//
// You can freely use this code in any project
// if sending any postcards with postage stamp to my address:
// Frunze 131/1, 56, Russia, Tomsk, 634021
unit pbInput;
//define PB_USE_ASSERTS (here or in project settings), to let pbInput do the
//error checking using Asserts. Warning: if release builds will be compiled
//with Asserts off, then no runtime error checking for malformed input will
//be done!
{.$DEFINE PB_USE_ASSERTS}
interface
uses
Classes,
SysUtils,
pbPublic;
type
{$IFNDEF PB_USE_ASSERTS}
EPBInputException = class(Exception);
{$ENDIF}
TProtoBufInput = class;
IExtensionRegistry = interface
['{B08BC625-245E-4C25-98DD-98859B951CC7}']
end;
IBuilder = interface
['{98E70F9E-9236-48B2-A6BB-6468150B3A58}']
procedure mergeFrom(input: TProtoBufInput; extReg: IExtensionRegistry);
end;
// Reads and decodes protocol message fields.
TProtoBufInput = class
private
FBuffer: PAnsiChar;
FPos: integer;
FLen: integer;
FSizeLimit: integer;
FRecursionDepth: integer;
FLastTag: integer;
FOwnBuffer: Boolean;
procedure FreeBuffer;
{$IFNDEF PB_USE_ASSERTS}
procedure Assert(Condition: Boolean; const AMessage: string = '');
{$ENDIF}
public
constructor Create; overload;
constructor Create(buf: PAnsiChar; len: Integer; ACopyBuffer: Boolean = False); overload;
destructor Destroy; override;
// I/O routines to file and stream
procedure SaveToStream(Stream: TStream);
procedure SaveToFile(const FileName: string);
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure LoadFromBuf(buf: PAnsiChar; len: Integer; ACopyBuffer: Boolean = False);
// Get buffer posititon
function getPos: integer;
// Attempt to read a field tag, returning zero if we have reached EOF.
function readTag: integer;
// Check whether the latter match the value read tag.
// Used to test for nested groups.
procedure checkLastTagWas(value: integer);
// Reads and discards a single field, given its tag value.
function skipField(tag: integer): boolean;
// Reads and discards an entire message.
procedure skipMessage;
// Read a double field value
function readDouble: double;
// Read a float field value
function readFloat: single;
// Read an int64 field value
function readInt64: int64;
// Read an int32 field value
function readInt32: integer;
// Read a fixed64 field value
function readFixed64: int64;
// Read a fixed32 field value
function readFixed32: integer;
function readRawBoolean: boolean;
// Read a boolean field value
function readBoolean: boolean;
// Read a UTF8 string field value
function readString: string;
// read bytes field value
function readBytes: TBytes;
// Read nested message
procedure readMessage(builder: IBuilder; extensionRegistry: IExtensionRegistry);
// Read a uint32 field value
function readUInt32: integer;
// Read a enum field value
function readEnum: integer;
// Read an sfixed32 field value
function readSFixed32: integer;
// Read an sfixed64 field value
function readSFixed64: int64;
// Read an sint32 field value
function readSInt32: integer;
// Read an sint64 field value
function readSInt64: int64;
// Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits
function readRawVarint32: integer;
// Read a raw Varint
function readRawVarint64: int64;
// Read a 32-bit little-endian integer
function readRawLittleEndian32: integer;
// Read a 64-bit little-endian integer
function readRawLittleEndian64: int64;
// Read one byte
function readRawByte: shortint;
// Read "size" bytes
procedure readRawBytes(var data; size: integer);
// Skip "size" bytes
procedure skipRawBytes(size: integer);
function ReadSubProtoBufInput: TProtoBufInput;
property BufSize: integer read FLen;
property LastTag: integer read FLastTag;
end;
function decodeZigZag32(n: integer): integer;
function decodeZigZag64(n: int64): int64;
implementation
const
ProtoBufException = 'Protocol buffer exception: ';
DEFAULT_RECURSION_LIMIT = 64;
DEFAULT_SIZE_LIMIT = 64 shl 20; // 64MB
function decodeZigZag32(n: integer): integer;
begin
result := (n shr 1) xor -(n and 1);
end;
function decodeZigZag64(n: int64): int64;
begin
result := (n shr 1) xor -(n and 1);
end;
{ TProtoBufInput }
constructor TProtoBufInput.Create;
begin
inherited Create;
FSizeLimit := DEFAULT_SIZE_LIMIT;
FRecursionDepth := DEFAULT_RECURSION_LIMIT;
end;
constructor TProtoBufInput.Create(buf: PAnsiChar; len: integer; ACopyBuffer: boolean);
begin
Create;
LoadFromBuf(buf, len, ACopyBuffer);
end;
destructor TProtoBufInput.Destroy;
begin
FreeBuffer;
inherited;
end;
{$IFNDEF PB_USE_ASSERTS}
procedure TProtoBufInput.Assert(Condition: Boolean; const AMessage: string);
begin
if not Condition then
raise EPBInputException.Create(AMessage);
end;
{$ENDIF}
procedure TProtoBufInput.FreeBuffer;
begin
if FOwnBuffer then
FreeMem(FBuffer);
FBuffer := nil;
end;
function TProtoBufInput.readTag: integer;
begin
if FPos < FLen then
FLastTag := readRawVarint32
else
FLastTag := 0;
result := FLastTag;
end;
procedure TProtoBufInput.checkLastTagWas(value: integer);
begin
Assert(FLastTag = value, ProtoBufException + 'invalid end tag');
end;
function TProtoBufInput.skipField(tag: integer): boolean;
begin
result := true;
case getTagWireType(tag) of
WIRETYPE_VARINT:
readInt32;
WIRETYPE_FIXED64:
readRawLittleEndian64;
WIRETYPE_LENGTH_DELIMITED:
skipRawBytes(readRawVarint32());
WIRETYPE_FIXED32:
readRawLittleEndian32();
else
Assert(False, ProtoBufException + 'TProtoBufInput.skipField: invalidWireType');
end;
end;
procedure TProtoBufInput.skipMessage;
var
tag: integer;
begin
repeat
tag := readTag();
until (tag = 0) or (not skipField(tag));
end;
function TProtoBufInput.readDouble: double;
begin
readRawBytes(result, SizeOf(double));
end;
function TProtoBufInput.readFloat: single;
begin
readRawBytes(result, SizeOf(single));
end;
function TProtoBufInput.readInt64: int64;
begin
result := readRawVarint64;
end;
function TProtoBufInput.readInt32: integer;
begin
result := readRawVarint32;
end;
function TProtoBufInput.readFixed64: int64;
begin
result := readRawLittleEndian64;
end;
function TProtoBufInput.readFixed32: integer;
begin
result := readRawLittleEndian32;
end;
function TProtoBufInput.readBoolean: boolean;
begin
result := readRawBoolean;
end;
function TProtoBufInput.readBytes: TBytes;
var
size: integer;
begin
size := readRawVarint32;
Assert(size >= 0, ProtoBufException + 'readBytes (size < 0)');
SetLength(result, size);
if size > 0 then
readRawBytes(result[0], size);
end;
function TProtoBufInput.readString: string;
var
size: integer;
buf: TBytes;
begin
size := readRawVarint32;
Assert(size >= 0, ProtoBufException + 'readString (size < 0)');
if size > 0 then
begin
SetLength(buf, size);
readRawBytes(buf[0], size);
result := TEncoding.UTF8.GetString(buf);
end
else
result := '';
end;
function TProtoBufInput.ReadSubProtoBufInput: TProtoBufInput;
var
lBufSize: integer;
buf: Pointer;
begin
lBufSize := readInt32;
buf := AllocMem(lBufSize);
try
readRawBytes(buf^, lBufSize);
result := TProtoBufInput.Create(buf, lBufSize, true);
finally
FreeMem(buf);
end;
end;
procedure TProtoBufInput.readMessage(builder: IBuilder; extensionRegistry: IExtensionRegistry);
begin
readRawVarint32;
Assert(FRecursionDepth < RecursionLimit, ProtoBufException + 'recursion Limit Exceeded');
Inc(FRecursionDepth);
builder.mergeFrom(Self, extensionRegistry);
checkLastTagWas(0);
dec(FRecursionDepth);
end;
function TProtoBufInput.readUInt32: integer;
begin
result := readRawVarint32;
end;
function TProtoBufInput.readEnum: integer;
begin
result := readRawVarint32;
end;
function TProtoBufInput.readSFixed32: integer;
begin
result := readRawLittleEndian32;
end;
function TProtoBufInput.readSFixed64: int64;
begin
result := readRawLittleEndian64;
end;
function TProtoBufInput.readSInt32: integer;
begin
result := decodeZigZag32(readRawVarint32);
end;
function TProtoBufInput.readSInt64: int64;
begin
result := decodeZigZag64(readRawVarint64());
end;
function TProtoBufInput.readRawVarint32: integer;
begin
//negative int32s are padded and written as 64bit,
//we call readRawVarint64 for all int's as it will
//terminate early enough for smaller values
Result:= Integer(readRawVarint64);
end;
function TProtoBufInput.readRawVarint64: int64;
var
tmp: shortint;
shift: integer;
i64: int64;
begin
shift := -7;
result := 0;
repeat
Inc(shift, 7);
Assert(shift < 64, ProtoBufException + 'malformed Varint');
tmp := readRawByte;
i64 := tmp and $7F;
i64 := i64 shl shift;
result := result or i64;
until tmp >= 0;
end;
function TProtoBufInput.readRawLittleEndian32: integer;
begin
readRawBytes(result, SizeOf(result));
end;
function TProtoBufInput.readRawLittleEndian64: int64;
begin
readRawBytes(result, SizeOf(result));
end;
function TProtoBufInput.readRawBoolean: boolean;
begin
result := readRawVarint32 <> 0;
end;
function TProtoBufInput.readRawByte: shortint;
begin
readRawBytes(result, 1);
end;
procedure TProtoBufInput.readRawBytes(var data; size: integer);
begin
Assert(size >= 0, ProtoBufException + 'negative Size');
Assert((FLen - FPos) >= size, ProtoBufException + 'eof encounterd');
Move(FBuffer[FPos], data, size);
Inc(FPos, size);
end;
procedure TProtoBufInput.skipRawBytes(size: integer);
begin
Assert(size >= 0, ProtoBufException + 'negative Size');
Assert((FLen - FPos) >= size, ProtoBufException + 'truncated Message');
Inc(FPos, size);
end;
procedure TProtoBufInput.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TProtoBufInput.SaveToStream(Stream: TStream);
begin
Stream.WriteBuffer(Pointer(FBuffer)^, FLen);
end;
procedure TProtoBufInput.LoadFromBuf(buf: PAnsiChar; len: Integer;
ACopyBuffer: Boolean);
begin
FreeBuffer;
if ACopyBuffer then
begin
// allocate a buffer and copy the data
FBuffer := AllocMem(len);
Move(buf^, FBuffer^, len);
end else
FBuffer := buf;
FPos := 0;
FLen := len;
FOwnBuffer := ACopyBuffer;
end;
procedure TProtoBufInput.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TProtoBufInput.LoadFromStream(Stream: TStream);
begin
FreeBuffer;
FOwnBuffer := true;
FLen := Stream.size;
FPos := 0;
FBuffer := AllocMem(FLen);
Stream.Position := 0;
Stream.Read(FBuffer^, FLen);
end;
function TProtoBufInput.getPos: integer;
begin
result := FPos;
end;
end.