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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
type payload_kind =
| Varint
| Bits32
| Bits64
| Bytes
let min_int_as_int32, max_int_as_int32 =
Int32.of_int min_int, Int32.of_int max_int
let min_int_as_int64, max_int_as_int64 =
Int64.of_int min_int, Int64.of_int max_int
module Decoder = struct
type error =
| Incomplete
| Overlong_varint
| Malformed_field
| Overflow of string
| Unexpected_payload of string * payload_kind
| Missing_field of string
| Malformed_variant of string
let error_to_string e =
match e with
| Incomplete -> "Incomplete"
| Overlong_varint -> "Overlong_varint"
| Malformed_field -> "Malformed_field"
| Overflow fld ->
Printf.sprintf "Overflow(%S)" fld
| Unexpected_payload (field, kind) ->
let kind' =
match kind with
| Varint -> "Varint"
| Bits32 -> "Bits32"
| Bits64 -> "Bits64"
| Bytes -> "Bytes"
in
Printf.sprintf "Unexpected_payload(%S, %s)" field kind'
| Missing_field field ->
Printf.sprintf "Missing_field(%S)" field
| Malformed_variant name ->
Printf.sprintf "Malformed_variant(%S)" name
exception Failure of error
let () =
Printexc.register_printer (fun exn ->
match exn with
| Failure e -> Some (
Printf.sprintf "Pbrt.Decoder.Failure(%s)" (error_to_string e)
)
| _ -> None)
type t = {
source : bytes;
limit : int;
mutable offset : int;
}
let of_bytes source =
{ source;
offset = 0;
limit = Bytes.length source; }
let of_string source =
of_bytes (Bytes.unsafe_of_string source)
let malformed_variant variant_name =
raise (Failure (Malformed_variant variant_name))
let unexpected_payload field_name pk =
raise (Failure (Unexpected_payload (field_name, pk)))
let missing_field field_name =
raise (Failure (Missing_field field_name))
let at_end d =
d.limit = d.offset
let byte d =
if d.offset >= d.limit then
raise (Failure Incomplete);
let byte = int_of_char (Bytes.get d.source d.offset) in
d.offset <- d.offset + 1;
byte
let[@inline] bool_of_int64 fld v =
if v = Int64.zero then false
else if v = Int64.one then true
else raise (Failure (Overflow fld))
let int_of_int32 fld v =
if Sys.word_size = 32 &&
(v < min_int_as_int32 || v > max_int_as_int32)
then
raise (Failure (Overflow fld))
else
Int32.to_int v
let[@inline] int_of_int64 fld v =
if (v < min_int_as_int64 || v > max_int_as_int64)
then
raise (Failure (Overflow fld))
else
Int64.to_int v
let varint d : int64 =
let shift = ref 0 in
let res = ref 0L in
let continue = ref true in
while !continue do
let b = byte d in
let cur = b land 0x7f in
if cur <> b then (
res := Int64.(logor !res (shift_left (of_int cur) !shift));
shift := !shift + 7;
) else if !shift < 63 || (b land 0x7f) <= 1 then (
res := Int64.(logor !res (shift_left (of_int b) !shift));
continue := false;
) else (
raise (Failure Overlong_varint)
);
done;
!res
let zigzag d : int64 =
let v = (varint[@inlined]) d in
Int64.(logxor (shift_right v 1) (neg (logand v Int64.one)))
let bits32 d =
let b1 = byte d in
let b2 = byte d in
let b3 = byte d in
let b4 = byte d in
Int32.(add (shift_left (of_int b4) 24)
(add (shift_left (of_int b3) 16)
(add (shift_left (of_int b2) 8)
(of_int b1))))
let bits64 d =
let b1 = byte d in
let b2 = byte d in
let b3 = byte d in
let b4 = byte d in
let b5 = byte d in
let b6 = byte d in
let b7 = byte d in
let b8 = byte d in
Int64.(add (shift_left (of_int b8) 56)
(add (shift_left (of_int b7) 48)
(add (shift_left (of_int b6) 40)
(add (shift_left (of_int b5) 32)
(add (shift_left (of_int b4) 24)
(add (shift_left (of_int b3) 16)
(add (shift_left (of_int b2) 8)
(of_int b1))))))))
let int_as_varint d =
Int64.to_int @@ (varint[@inlined]) d
let bytes d =
let len = int_as_varint d in
if d.offset + len > d.limit then
raise (Failure Incomplete);
let str = Bytes.sub d.source d.offset len in
d.offset <- d.offset + len;
str
let nested d =
let len = int_as_varint d in
if d.offset + len > d.limit then
raise (Failure Incomplete);
let d' = { d with limit = d.offset + len; } in
d.offset <- d.offset + len;
d'
let key d =
if d.offset = d.limit
then None
else
let prefix = (varint[@inlined]) d in
let key, ty =
Int64.(to_int (shift_right prefix 3)),
Int64.logand 0x7L prefix in
match ty with
| 0L -> Some (key, Varint)
| 1L -> Some (key, Bits64)
| 2L -> Some (key, Bytes)
| 5L -> Some (key, Bits32)
| _ -> raise (Failure Malformed_field)
let skip d kind =
let skip_len n =
if d.offset + n > d.limit
then
raise (Failure Incomplete)
else
d.offset <- d.offset + n
in
let rec skip_varint () =
let b = byte d in
if b land 0x80 <> 0 then skip_varint () else ()
in
match kind with
| Bits32 -> skip_len 4
| Bits64 -> skip_len 8
| Bytes -> skip_len (int_as_varint d)
| Varint -> skip_varint ()
let map_entry d ~decode_key ~decode_value =
let d = nested d in
let key_v = ref None in
let value_v = ref None in
let rec loop () =
match key d with
| None -> ()
| Some (1, _) -> key_v := Some (decode_key d); loop ()
| Some (2, _) -> value_v := Some (decode_value d); loop ()
| Some (_, pk) -> (
skip d pk;
loop ()
)
in
loop ();
match !key_v, !value_v with
| Some key, Some value -> (key, value)
| _ -> failwith "Missing key or value for map entry"
let empty_nested d =
let len = int_as_varint d in
if len <> 0
then raise (Failure Incomplete)
else ()
let packed_fold f e0 d =
let d' = nested d in
let rec loop acc =
if at_end d'
then acc
else loop (f acc d')
in
loop e0
let int_as_zigzag d =
Int64.to_int @@ (zigzag[@inlined]) d
let int32_as_varint d =
Int64.to_int32 ((varint[@inlined]) d)
let int32_as_zigzag d =
Int64.to_int32 ((zigzag[@inlined]) d)
let int64_as_varint = varint
let int64_as_zigzag = zigzag
let int32_as_bits32 = bits32
let int64_as_bits64 = bits64
let bool d =
bool_of_int64 "" ((varint[@inlined]) d)
let float_as_bits32 d =
Int32.float_of_bits (bits32 d)
let float_as_bits64 d =
Int64.float_of_bits (bits64 d)
let int_as_bits32 d =
int_of_int32 "" (bits32 d)
let int_as_bits64 d =
int_of_int64 "" (bits64 d)
let string d =
let len = int_as_varint d in
if d.offset + len > d.limit then
raise (Failure Incomplete);
let str = Bytes.sub_string d.source d.offset len in
d.offset <- d.offset + len;
str
let wrapper_double_value d =
let d = nested d in
match key d with
| Some (1, Bits64) -> Some (float_as_bits64 d)
| _ -> None
let wrapper_float_value d =
let d = nested d in
match key d with
| Some (1, Bits32) -> Some (float_as_bits32 d)
| _ -> None
let wrapper_int64_value d =
let d = nested d in
match key d with
| Some (1, Varint) -> Some (int64_as_varint d)
| _ -> None
let wrapper_int32_value d =
let d = nested d in
match key d with
| Some (1, Varint) -> Some (int32_as_varint d)
| _ -> None
let wrapper_bool_value d =
let d = nested d in
match key d with
| Some (1, Varint) -> Some (bool d)
| _ -> None
let wrapper_string_value d =
let d = nested d in
match key d with
| Some (1, Bytes) -> Some (string d)
| _ -> None
let wrapper_bytes_value d =
let d = nested d in
match key d with
| Some (1, Bytes) -> Some (bytes d)
| _ -> None
end
module Encoder = struct
type error =
| Overflow of string
let error_to_string e =
match e with
| Overflow fld -> Printf.sprintf "Overflow(%S)" fld
exception Failure of error
let () =
Printexc.register_printer (fun exn ->
match exn with
| Failure e -> Some (
Printf.sprintf "Protobuf.Encoder.Failure(%s)" (error_to_string e)
)
| _ -> None)
type t = {
mutable b: bytes;
mutable len: int;
initial: bytes;
mutable sub: t option;
}
let create () =
let b = Bytes.create 16 in
{ b;
len=0;
initial=b;
sub=None;
}
let[@inline] clear self = self.len <- 0
let[@inline] length self = self.len
let[@inline] cap self = Bytes.length self.b
let reset self =
self.len <- 0;
self.b <- self.initial
let to_string self = Bytes.sub_string self.b 0 self.len
let to_bytes self = Bytes.sub self.b 0 self.len
let write_chunks w self =
w self.b 0 self.len
let next_cap_ self =
min Sys.max_string_length (let n=cap self in n + n lsr 1)
let[@inline never] grow_to_ self newcap =
if newcap = self.len then raise (Failure (Overflow "encoder size reached its max"));
let b' = Bytes.create newcap in
Bytes.blit self.b 0 b' 0 self.len;
self.b <- b'
let[@inline never] grow_ self = grow_to_ self (next_cap_ self)
let[@inline] add_char self c =
if self.len = cap self then grow_ self;
Bytes.unsafe_set self.b self.len c;
self.len <- 1 + self.len
let add_bytes self b =
let n = Bytes.length b in
if cap self < self.len + n then (
grow_to_ self (max (next_cap_ self) (self.len + n));
);
Bytes.blit b 0 self.b self.len n;
self.len <- n + self.len
let add_buffer self sub =
let n = sub.len in
if cap self < self.len + n then (
grow_to_ self (max (next_cap_ self) (self.len + n));
);
Bytes.blit sub.b 0 self.b self.len n;
self.len <- n + self.len
let varint (i:int64) e =
let i = ref i in
let continue = ref true in
while !continue do
let cur = Int64.(logand !i 0x7fL) in
if cur = !i
then (
continue := false;
add_char e (Char.unsafe_chr Int64.(to_int cur))
) else (
add_char e
(Char.unsafe_chr Int64.( to_int (logor 0x80L cur)
));
i := Int64.shift_right_logical !i 7;
)
done
let int_as_varint i e =
(varint[@inlined]) (Int64.of_int i) e
let zigzag i e =
(varint[@inlined]) Int64.(logxor (shift_left i 1) (shift_right i 63)) e
let bits32 i e =
add_char e (char_of_int Int32.(to_int (logand 0xffl i)));
add_char e (char_of_int Int32.(to_int (
logand 0xffl (shift_right i 8))));
add_char e (char_of_int Int32.(to_int (
logand 0xffl (shift_right i 16))));
add_char e (char_of_int Int32.(to_int (
logand 0xffl (shift_right i 24))))
let bits64 i e =
add_char e (char_of_int Int64.(to_int (logand 0xffL i)));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 8))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 16))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 24))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 32))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 40))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 48))));
add_char e (char_of_int Int64.(to_int (
logand 0xffL (shift_right i 56))))
let bytes b e =
int_as_varint (Bytes.length b) e;
add_bytes e b
let nested f e =
let e' = match e.sub with
| Some e' -> e'
| None ->
let e' = create () in
e.sub <- Some e';
e'
in
f e';
int_as_varint (length e') e;
add_buffer e e';
clear e'
let[@inline] key (k, pk) e =
let pk' =
match pk with
| Varint -> 0
| Bits64 -> 1
| Bytes -> 2
| Bits32 -> 5
in
int_as_varint (pk' lor (k lsl 3)) e
let map_entry ~encode_key ~encode_value kv t =
let (
(key_value, key_pk),
(value_value, value_pk)) = kv
in
nested (fun t ->
key (1, key_pk) t;
encode_key key_value t;
key (2, value_pk) t;
encode_value value_value t;
) t
let empty_nested e = add_char e (Char.unsafe_chr 0)
let int_as_zigzag i e = (zigzag[@inlined]) (Int64.of_int i) e
let int32_as_varint i e = (varint[@inlined]) (Int64.of_int32 i) e
let int32_as_zigzag i e = (zigzag[@inlined]) (Int64.of_int32 i) e
let int64_as_varint = varint
let int64_as_zigzag = zigzag
let int32_as_bits32 = bits32
let int64_as_bits64 = bits64
let bool b e = add_char e (Char.unsafe_chr (if b then 1 else 0))
let float_as_bits32 f e = bits32 (Int32.bits_of_float f) e
let float_as_bits64 f e = bits64 (Int64.bits_of_float f) e
let int_as_bits32 i e = bits32 (Int32.of_int i) e
let int_as_bits64 i e = bits64 (Int64.of_int i) e
let string s e =
bytes (Bytes.unsafe_of_string s) e
let double_value_key = (1, Bits64)
let wrapper_double_value v e =
nested (fun e ->
key double_value_key e;
begin match v with
| None -> ()
| Some f -> float_as_bits64 f e
end
) e
let float_value_key = (1, Bits32)
let wrapper_float_value v e =
nested (fun e ->
key float_value_key e;
begin match v with
| None -> ()
| Some f -> float_as_bits32 f e
end
) e
let int64_value_key = (1, Varint)
let wrapper_int64_value v e =
nested (fun e ->
key int64_value_key e;
begin match v with
| None -> ()
| Some i -> int64_as_varint i e
end
) e
let int32_value_key = (1, Varint)
let wrapper_int32_value v e =
nested (fun e ->
key int32_value_key e;
begin match v with
| None -> ()
| Some i -> int32_as_varint i e
end
) e
let bool_value_key = (1, Varint)
let wrapper_bool_value v e =
nested (fun e ->
key bool_value_key e;
begin match v with
| None -> ()
| Some b -> bool b e
end
) e
let string_value_key = (1, Bytes)
let wrapper_string_value v e =
nested (fun e ->
key string_value_key e;
begin match v with
| None -> ()
| Some s -> string s e
end
) e
let bytes_value_key = (1, Bytes)
let wrapper_bytes_value v e =
nested (fun e ->
key bytes_value_key e;
begin match v with
| None -> ()
| Some b -> bytes b e
end
) e
end
module Repeated_field = struct
(** [t] is a container optimized for fast repeated inserts.
It is made of a list of growing size array [l] as well as
a current array [a] in which inserts are performed until
[a] is full and appended to [l].
The main growing logic is implemented in the [add] functions.
*)
type 'a t = {
mutable s : int;
mutable i : int;
mutable a : 'a array;
mutable l : 'a array list;
}
let make v = {
s = 16;
i = 0;
a = Array.make 16 v;
l = [];
}
let of_array_no_copy a = {
s = Array.length a;
i = Array.length a;
a = a;
l = [];
}
let add v ({s; i; a; l} as tmp) =
match i with
| i when i = s -> (
tmp.s <- int_of_float (float_of_int s *. 1.3);
tmp.i <- 1;
tmp.l <- a :: l;
tmp.a <- Array.make tmp.s v;
)
| i -> (
Array.unsafe_set a i v;
tmp.i <- i + 1;
)
let to_array {s; i; a; l} =
let l = match i with
| 0 -> l
| i when i = s -> a :: l
| i -> (Array.sub a 0 i) :: l
in
Array.concat (List.rev l)
(** [list_rev_iter f l] iterate over the list in reverse order *)
let rec list_rev_iter f = function
| [] -> ()
| hd::tl -> (
list_rev_iter f tl;
f hd
)
let iter f {i; a; l; _} =
list_rev_iter (fun a ->
let len = Array.length a - 1 in
for j = 0 to len do
f (Array.unsafe_get a j)
done
) l;
let len = i - 1 in
for j = 0 to len do
f (Array.unsafe_get a j)
done
let iteri f {i; a; l; _} =
let counter = ref 0 in
list_rev_iter (fun a ->
let len = Array.length a - 1 in
for j = 0 to len do
f !counter (Array.unsafe_get a j);
incr counter;
done
) l;
let len = i - 1 in
for j = 0 to len do
f !counter (Array.unsafe_get a j);
incr counter;
done
let fold_left f e0 t =
let acc = ref e0 in
iter (fun e ->
acc := f !acc e
) t;
!acc
let length {s = _ ; i; a=_; l } : int=
let len = List.fold_left (fun len a ->
len + (Array.length a)
) 0 l in
len + i
let map_to_array f t =
let len = length t in
let dest = Array.make len (f @@ Array.unsafe_get t.a 0) in
let index = ref 0 in
iter (fun e ->
Array.unsafe_set dest !index (f e);
incr index
) t;
dest
let map_to_list f ({s = _ ; i; a; l}) =
let rec a_to_list a i res =
if i < 0
then res
else a_to_list a (i - 1) (f (Array.unsafe_get a i) :: res)
in
let res = a_to_list a (i - 1) [] in
List.fold_left (fun acc a ->
a_to_list a (Array.length a - 1) acc
) res l
external identity : 'a -> 'a = "%identity"
let to_list t = map_to_list identity t
end
module Pp = struct
module F = Format
type formatter = F.formatter
let pp_unit fmt () =
F.pp_print_string fmt "()"
let pp_int =
F.pp_print_int
let pp_float =
F.pp_print_float
let pp_bool =
F.pp_print_bool
let pp_int32 fmt i =
F.pp_print_string fmt (Int32.to_string i)
let pp_int64 fmt i =
F.pp_print_string fmt (Int64.to_string i)
let pp_string fmt s =
F.fprintf fmt "\"%a\"" F.pp_print_string s
let pp_bytes fmt b =
F.fprintf fmt "<bytes len=%d>" (Bytes.length b)
let pp_option pp_f fmt = function
| None -> F.fprintf fmt "@[None@]"
| Some x -> F.fprintf fmt "@[<hv2>Some(@,%a)@]" pp_f x
let pp_wrapper_float fmt v =
pp_option pp_float fmt v
let pp_wrapper_bool fmt v =
pp_option pp_bool fmt v
let pp_wrapper_int32 fmt v =
pp_option pp_int32 fmt v
let pp_wrapper_int64 fmt v =
pp_option pp_int64 fmt v
let pp_wrapper_string fmt v =
pp_option pp_string fmt v
let pp_wrapper_bytes fmt v =
pp_option pp_bytes fmt v
let pp_list pp_element fmt l =
let rec pp_i fmt = function
| [h] -> Format.fprintf fmt "%a" pp_element h
| h::t ->
Format.fprintf fmt "%a;@,%a" pp_element h pp_i t
| [] -> ()
in
F.fprintf fmt "[@[<hv>%a@,@]]" pp_i l
let pp_associative_list pp_key pp_value fmt l =
let pp_element fmt (k, v) =
F.fprintf fmt "(@[%a,@ %a@])" pp_key k pp_value v
in
pp_list pp_element fmt l
let pp_hastable pp_key pp_value fmt h =
let l = Hashtbl.fold (fun a b l ->
(a, b)::l
) h [] in
pp_associative_list pp_key pp_value fmt l
let pp_record_field ?(first=false) field_name pp_val fmt val_ =
if not first then F.fprintf fmt "@ ";
F.fprintf fmt "@[<hv2>%s =@ %a;@]" field_name pp_val val_
let pp_brk pp_record (fmt:F.formatter) r : unit =
F.fprintf fmt "@[<hv2>{ %a@;<1 -2>@]}" pp_record r
end