forked from protocolbuffers/protobuf-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwriter.js
More file actions
executable file
·1719 lines (1583 loc) · 55.7 KB
/
writer.js
File metadata and controls
executable file
·1719 lines (1583 loc) · 55.7 KB
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview This file contains utilities for encoding Javascript objects
* into binary, wire-format protocol buffers (in the form of Uint8Arrays) that
* a server can consume directly.
*
* jspb's BinaryWriter class defines methods for efficiently encoding
* Javascript objects into binary, wire-format protocol buffers and supports
* all the fundamental field types used in protocol buffers.
*
* Major caveat 1 - Users of this library _must_ keep their Javascript proto
* parsing code in sync with the original .proto file - presumably you'll be
* using the typed jspb code generator, but if you bypass that you'll need
* to keep things in sync by hand.
*
* Major caveat 2 - Javascript is unable to accurately represent integers
* larger than 2^53 due to its use of a double-precision floating point format
* for all numbers. BinaryWriter does not make any special effort to preserve
* precision for values above this limit - if you need to pass 64-bit integers
* (hash codes, for example) between the client and server without precision
* loss, do _not_ use this library.
*
* Major caveat 3 - This class uses typed arrays and must not be used on older
* browsers that do not support them.
*
* @author aappleby@google.com (Austin Appleby)
*/
goog.module('jspb.binary.writer');
goog.module.declareLegacyNamespace();
const { Alphabet, encodeByteArray: encodeByteArraySlow } = goog.require('goog.crypt.base64');
const { AnyFieldType } = goog.requireType('jspb.binary.any_field_type');
const { BinaryEncoder } = goog.require('jspb.binary.encoder');
const { ByteSource } = goog.requireType('jspb.binary.bytesource');
const { ByteString } = goog.require('jspb.bytestring');
const { FieldType, TWO_TO_31, TWO_TO_32, TWO_TO_63, TWO_TO_64, WireType } = goog.require('jspb.BinaryConstants');
const { Int64, UInt64 } = goog.require('jspb.arith');
const { assert, fail } = goog.require('goog.asserts');
const { bufferFromSource } = goog.require('jspb.binary.internal_buffer');
const { encodeByteArray } = goog.require('jspb.internal_bytes');
const { encodeUtf8 } = goog.require('jspb.binary.utf8');
const { makeTag } = goog.require('jspb.utils');
const { unsafeByteStringFromUint8Array, unsafeUint8ArrayFromByteString } = goog.require('jspb.unsafe_bytestring');
/**
* Whether to reject unpaired surrogates when encoding strings to utf8.
*
* <p>Currently set to `goog.DEBUG`, but can be disabled if needed.
*
* @define {boolean}
*/
const REJECT_UNPAIRED_SURROGATES =
goog.define('jspb.binary.REJECT_UNPAIRED_SURROGATES', goog.DEBUG);
/**
* BinaryWriter implements encoders for all the wire types specified in
* https://developers.google.com/protocol-buffers/docs/encoding.
*/
class BinaryWriter {
constructor() {
/**
* Blocks of serialized data that will be concatenated once all messages
* have been written.
* @private {!Array<!Uint8Array|!Array<number>>}
*/
this.blocks_ = [];
/**
* Total number of bytes in the blocks_ array. Does _not_ include bytes in
* the encoder below.
* @private {number}
*/
this.totalLength_ = 0;
/**
* Binary encoder holding pieces of a message that we're still serializing.
* When we get to a stopping point (either the start of a new submessage, or
* when we need to append a raw Uint8Array), the encoder's buffer will be
* added to the block array above and the encoder will be reset.
* @private @const {!BinaryEncoder}
*/
this.encoder_ = new BinaryEncoder();
}
/** @private*/
pushBlock(/** !Array<number>|!Uint8Array */ buffer) {
// Repeated calls to appendUint8Arrays may produce empty arrays from the
// encoder, avoid storing these in our list of blocks.
if (buffer.length !== 0) {
this.blocks_.push(buffer);
this.totalLength_ += buffer.length;
}
}
/**
* Append a typed array of bytes onto the buffer.
*
* @param {!Uint8Array} arr The byte array to append.
* @private
*/
appendUint8Array_(arr) {
this.pushBlock(this.encoder_.end());
this.pushBlock(arr);
}
/**
* Begins a new message by writing the field header and returning a bookmark
* which we will use to patch in the message length to in endDelimited_ below.
* @param {number} field
* @return {!Array<number>}
* @private
*/
beginDelimited_(field) {
this.writeFieldHeader_(field, WireType.DELIMITED);
const bookmark = this.encoder_.end();
this.pushBlock(bookmark);
bookmark.push(
this.totalLength_); // store the current length in the bookmark
return bookmark;
}
/**
* Ends a message by encoding the _change_ in length of the buffer to the
* parent block and adds the number of bytes needed to encode that length to
* the total byte length.
* @param {!Array<number>} bookmark
* @private
*/
endDelimited_(bookmark) {
const oldLength = bookmark.pop();
let messageLength = this.totalLength_ + this.encoder_.length() - oldLength;
assert(messageLength >= 0);
while (messageLength > 127) {
bookmark.push((messageLength & 0x7f) | 0x80);
messageLength = messageLength >>> 7;
this.totalLength_++;
}
bookmark.push(messageLength);
this.totalLength_++;
}
/**
* Writes unknown fields to the output if there are any.
*/
writeUnknownFields(/** !Array<!ByteString> */ unknownFields) {
this.pushBlock(this.encoder_.end());
for (let i = 0; i < unknownFields.length; i++) {
// Unsafe access is ok here since arrays added to our output are always
// copied before returning to the user.
this.pushBlock(unsafeUint8ArrayFromByteString(unknownFields[i]));
}
}
/**
* Writes a pre-serialized message to the buffer.
* @param {!Uint8Array} bytes The array of bytes to write.
* @param {number} start The start of the range to write.
* @param {number} end The end of the range to write.
*/
writeSerializedMessage(bytes, start, end) {
this.appendUint8Array_(bytes.subarray(start, end));
}
/**
* Writes a pre-serialized message to the buffer if the message and endpoints
* are non-null.
* @param {?Uint8Array} bytes The array of bytes to write.
* @param {?number} start The start of the range to write.
* @param {?number} end The end of the range to write.
*/
maybeWriteSerializedMessage(bytes, start, end) {
if (bytes != null && start != null && end != null) {
this.writeSerializedMessage(bytes, start, end);
}
}
/**
* Resets the writer, throwing away any accumulated buffers.
*/
reset() {
this.blocks_ = [];
this.encoder_.end();
this.totalLength_ = 0;
}
/**
* Converts the encoded data into a Uint8Array.
* @return {!Uint8Array}
*/
getResultBuffer() {
// flush the encoder to avoid a special case below.
this.pushBlock(this.encoder_.end());
const resultLength = this.totalLength_;
// NOTE: some of the Uint8Arrays stored in blocks_ are backing stores for
// ByteString objects and so we should be careful not to leak references to
// them from here. i.o.w. don't add an optimization that directly returns
// references to things in blocks.
const flat = new Uint8Array(resultLength);
const blocks = this.blocks_;
const blockCount = blocks.length;
let offset = 0;
for (let i = 0; i < blockCount; i++) {
const block = blocks[i];
flat.set(block, offset);
offset += block.length;
}
// Post condition: `flattened` must have had every byte written.
assert(offset == flat.length);
// Replace our block list with the flattened block, which lets GC reclaim
// the temp blocks sooner.
this.blocks_ = [flat];
return flat;
}
/**
* Converts the encoded data into a ByteString.
* @return {!ByteString}
*/
getResultBufferAsByteString() {
// Note that this is safe because we never leak or mutate the Uint8Array
// returned by getResultBuffer even though it's stored in `blocks_`.
return unsafeByteStringFromUint8Array(this.getResultBuffer());
}
/**
* Converts the encoded data into a base64-encoded string.
* @param {!Alphabet=} alphabet Which flavor of base64 to
* use.
* @return {string}
*/
getResultBase64String(alphabet) {
if (alphabet === undefined) {
return encodeByteArray(this.getResultBuffer());
} else {
return encodeByteArraySlow(this.getResultBuffer(), alphabet);
}
}
/**
* Encodes a (field number, wire type) tuple into a wire-format field header
* and stores it in the buffer as a varint.
* @param {number} field The field number.
* @param {!WireType} wireType The wire-type of the field, as specified in the
* protocol buffer documentation.
* @private
*/
writeFieldHeader_(field, wireType) {
assert(field >= 1 && field == Math.floor(field));
this.encoder_.writeUnsignedVarint32(makeTag(field, wireType));
}
// TODO(b/221101646): Maybe update AnyFieldType to include ByteString.
/**
* Writes a field of any valid scalar type to the binary stream.
* @param {!FieldType} fieldType
* @param {number} field
* @param {!AnyFieldType|!ByteString} value
*/
writeAny(fieldType, field, value) {
switch (fieldType) {
case FieldType.DOUBLE:
this.writeDouble(field, /** @type {number} */(value));
return;
case FieldType.FLOAT:
this.writeFloat(field, /** @type {number} */(value));
return;
case FieldType.INT64:
this.writeInt64(field, /** @type {number} */(value));
return;
case FieldType.UINT64:
this.writeUint64(field, /** @type {number} */(value));
return;
case FieldType.INT32:
this.writeInt32(field, /** @type {number} */(value));
return;
case FieldType.FIXED64:
this.writeFixed64(field, /** @type {number} */(value));
return;
case FieldType.FIXED32:
this.writeFixed32(field, /** @type {number} */(value));
return;
case FieldType.BOOL:
this.writeBool(field, /** @type {boolean} */(value));
return;
case FieldType.STRING:
this.writeString(field, /** @type {string} */(value));
return;
case FieldType.GROUP:
fail('Group field type not supported in writeAny()');
return;
case FieldType.MESSAGE:
fail('Message field type not supported in writeAny()');
return;
case FieldType.BYTES:
this.writeBytes(field, /** @type {?ByteSource|?ByteString} */(value));
return;
case FieldType.UINT32:
this.writeUint32(field, /** @type {number} */(value));
return;
case FieldType.ENUM:
this.writeEnum(field, /** @type {number} */(value));
return;
case FieldType.SFIXED32:
this.writeSfixed32(field, /** @type {number} */(value));
return;
case FieldType.SFIXED64:
this.writeSfixed64(field, /** @type {number} */(value));
return;
case FieldType.SINT32:
this.writeSint32(field, /** @type {number} */(value));
return;
case FieldType.SINT64:
this.writeSint64(field, /** @type {number} */(value));
return;
default:
fail('Invalid field type in writeAny()');
return;
}
}
/**
* Writes a varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
* @private
*/
writeUnsignedVarint32_(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeUnsignedVarint32(value);
}
/**
* Writes a varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
* @private
*/
writeSignedVarint32_(field, value) {
if (value == null) return;
assertSignedInteger(field, value);
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeSignedVarint32(value);
}
/**
* Writes a varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
* @private
*/
writeUnsignedVarint64_(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.VARINT);
switch (typeof value) {
case 'number':
this.encoder_.writeUnsignedVarint64(value);
break;
case 'bigint': {
const num = UInt64.fromBigInt(/** @type {bigint} */(value));
this.encoder_.writeSplitVarint64(num.lo, num.hi);
break;
}
default: {
const num = UInt64.fromString(/** @type {string} */(value));
this.encoder_.writeSplitVarint64(num.lo, num.hi);
break;
}
}
}
/**
* Writes a varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|string?|!bigint|null|undefined} value The value to write.
* @private
*/
writeSignedVarint64_(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.VARINT);
switch (typeof value) {
case 'number':
this.encoder_.writeSignedVarint64(value);
break;
case 'bigint': {
const num = Int64.fromBigInt(/** @type {bigint} */(value));
this.encoder_.writeSplitVarint64(num.lo, num.hi);
break;
}
default: {
const num = Int64.fromString(/** @type {string} */(value));
this.encoder_.writeSplitVarint64(num.lo, num.hi);
break;
}
}
}
/**
* Writes a zigzag varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
* @private
*/
writeZigzagVarint32_(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeZigzagVarint32(value);
}
/**
* Writes a zigzag varint field to the buffer without range checking.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
* @private
*/
writeZigzagVarint64_(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.VARINT);
switch (typeof value) {
case 'number':
this.encoder_.writeZigzagVarint64(/** @type {number} */(value));
break;
case 'bigint':
this.encoder_.writeZigzagVarint64BigInt(/** @type {bigint} */(value));
break;
default:
this.encoder_.writeZigzagVarint64String(/** @type {string} */(value));
break;
}
}
/**
* Writes an int32 field to the buffer. Numbers outside the range [-2^31,2^31)
* will be truncated.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeInt32(field, value) {
if (value == null) return;
assertThat(field, value, (value >= -TWO_TO_31) && (value < TWO_TO_31));
this.writeSignedVarint32_(field, value);
}
/**
* Writes an int64 field to the buffer. Numbers outside the range [-2^63,2^63)
* will be truncated.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
*/
writeInt64(field, value) {
if (value == null) return;
assertSignedInt64(field, value);
this.writeSignedVarint64_(field, value);
}
/**
* Writes a int64 field (with value as a string) to the buffer.
* @param {number} field The field number.
* @param {string|null|undefined} value The value to write.
* @deprecated Use writeInt64()
*/
writeInt64String(field, value) {
this.writeInt64(field, value);
}
/**
* Writes a uint32 field to the buffer. Numbers outside the range [0,2^32)
* will be truncated.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeUint32(field, value) {
if (value == null) return;
assertThat(field, value, (value >= 0) && (value < TWO_TO_32));
this.writeUnsignedVarint32_(field, value);
}
/**
* Writes a uint64 field to the buffer. Numbers outside the range [0,2^64)
* will be truncated.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
*/
writeUint64(field, value) {
if (value == null) return;
assertUnsignedInt64(field, value);
this.writeUnsignedVarint64_(field, value);
}
/**
* Writes a uint64 field (with value as a string) to the buffer.
* @param {number} field The field number.
* @param {string|null|undefined} value The value to write.
* @deprecated Use writeUint64()
*/
writeUint64String(field, value) {
this.writeUint64(field, value);
}
/**
* Writes an sint32 field to the buffer. Numbers outside the range
* [-2^31,2^31) will be truncated.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeSint32(field, value) {
if (value == null) return;
assertThat(field, value, (value >= -TWO_TO_31) && (value < TWO_TO_31));
this.writeZigzagVarint32_(field, value);
}
/**
* Writes an sint64 field to the buffer. Numbers outside the range
* [-2^63,2^63) will be truncated.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
*/
writeSint64(field, value) {
if (value == null) return;
assertSignedInt64(field, value);
this.writeZigzagVarint64_(field, value);
}
/**
* Writes an sint64 field to the buffer. Numbers outside the range
* [-2^63,2^63) will be truncated.
* @param {number} field The field number.
* @param {string|null|undefined} value The decimal string to write.
* @deprecated Use writeSint64();
*/
writeSint64String(field, value) {
this.writeSint64(field, value);
}
/**
* Writes a fixed32 field to the buffer. Numbers outside the range [0,2^32)
* will be truncated.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeFixed32(field, value) {
if (value == null) return;
assertThat(field, value, (value >= 0) && (value < TWO_TO_32));
this.writeFieldHeader_(field, WireType.FIXED32);
this.encoder_.writeUint32(value);
}
/**
* Writes a fixed64 field to the buffer. Numbers outside the range [0,2^64)
* will be truncated.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
*/
writeFixed64(field, value) {
if (value == null) return;
assertUnsignedInt64(field, value);
this.writeFieldHeader_(field, WireType.FIXED64);
switch (typeof value) {
case 'number':
this.encoder_.writeUint64(value);
break;
case 'bigint': {
const num = UInt64.fromBigInt(/** @type {bigint} */(value));
this.encoder_.writeSplitFixed64(num.lo, num.hi);
break;
}
default: {
const num = UInt64.fromString(/** @type {string} */(value));
this.encoder_.writeSplitFixed64(num.lo, num.hi);
break;
}
}
}
/**
* Writes a fixed64 field (with value as a string) to the buffer.
* @param {number} field The field number.
* @param {string|null|undefined} value The value to write.
* @deprecated Use writeFixed64().
*/
writeFixed64String(field, value) {
this.writeFixed64(field, value);
}
/**
* Writes a sfixed32 field to the buffer. Numbers outside the range
* [-2^31,2^31) will be truncated.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeSfixed32(field, value) {
if (value == null) return;
assertThat(field, value, (value >= -TWO_TO_31) && (value < TWO_TO_31));
this.writeFieldHeader_(field, WireType.FIXED32);
this.encoder_.writeInt32(value);
}
/**
* Writes a sfixed64 field to the buffer. Numbers outside the range
* [-2^63,2^63) will be truncated.
* @param {number} field The field number.
* @param {number|string|!bigint|null|undefined} value The value to write.
*/
writeSfixed64(field, value) {
if (value == null) return;
assertSignedInt64(field, value);
this.writeFieldHeader_(field, WireType.FIXED64);
switch (typeof value) {
case 'number':
this.encoder_.writeInt64(value);
break;
case 'bigint':
const int64Big = Int64.fromBigInt(/** @type {bigint} */(value));
this.encoder_.writeSplitFixed64(int64Big.lo, int64Big.hi);
break;
default:
const int64Str = Int64.fromString(/** @type {string} */(value));
this.encoder_.writeSplitFixed64(int64Str.lo, int64Str.hi);
break;
}
}
/**
* Writes a sfixed64 string field to the buffer. Numbers outside the range
* [-2^63,2^63) will be truncated.
* @param {number} field The field number.
* @param {string|null|undefined} value The value to write.
* @deprecated Use writeSfixed64().
*/
writeSfixed64String(field, value) {
this.writeSfixed64(field, value);
}
/**
* Writes a single-precision floating point field to the buffer. Numbers
* requiring more than 32 bits of precision will be truncated.
* @param {number} field The field number.
* @param {number?|string|null|undefined} value The value to write, accepts
* 'Infinity'/'-Infinity'/'NaN' for JSPB wire format compatibility.
*/
writeFloat(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.FIXED32);
this.encoder_.writeFloat(value);
}
/**
* Writes a double-precision floating point field to the buffer. As this is
* the native format used by JavaScript, no precision will be lost.
* @param {number} field The field number.
* @param {number?|string|null|undefined} value The value to write, accepts
* 'Infinity'/'-Infinity'/'NaN' for JSPB wire format compatibility.
*/
writeDouble(field, value) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.FIXED64);
this.encoder_.writeDouble(value);
}
/**
* Writes a boolean field to the buffer. We allow numbers as input
* because the JSPB code generator uses 0/1 instead of true/false to save
* space in the string representation of the proto.
* @param {number} field The field number.
* @param {boolean?|number|null|undefined} value The value to write.
*/
writeBool(field, value) {
if (value == null) return;
assertThat(
field, value, typeof value === 'boolean' || typeof value === 'number');
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeBool(value);
}
/**
* Writes an enum field to the buffer.
* @param {number} field The field number.
* @param {number|null|undefined} value The value to write.
*/
writeEnum(field, value) {
if (value == null) return;
// Converting since value might be object typed integer here.
const intValue = /** number */ parseInt(value, 10);
assertSignedInteger(field, intValue);
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeSignedVarint32(intValue);
}
/**
* Writes a string field to the buffer.
* @param {number} field The field number.
* @param {string|null|undefined} value The string to write.
*/
writeString(field, value) {
if (value == null) return;
this.writeUint8Array(
field,
encodeUtf8(
value, /** rejectUnpairedSurrogates=*/ REJECT_UNPAIRED_SURROGATES));
}
/**
* Writes an arbitrary byte field to the buffer. Note - to match the behavior
* of the C++ implementation, empty byte arrays _are_ serialized.
* @param {number} field The field number.
* @param {?ByteSource|?ByteString|undefined} value The array of bytes to
* write.
*/
writeBytes(field, value) {
if (value == null) return;
this.writeUint8Array(
field,
bufferFromSource(value, /* treatNewDataAsImmutable= */ true).buffer);
}
/**
* @param {number} field The field number.
* @param {!Uint8Array} value The array of bytes to write.
* @private
*/
writeUint8Array(field, value) {
this.writeFieldHeader_(field, WireType.DELIMITED);
this.encoder_.writeUnsignedVarint32(value.length);
this.appendUint8Array_(value);
}
/**
* Writes a message to the buffer.
* @param {number} field The field number.
* @param {?MessageType|undefined} value The message to write.
* @param {function(MessageTypeNonNull, !BinaryWriter)} writerCallback
* Will be invoked with the value to write and the writer to write it
* with.
* @template MessageType
* Use go/closure-ttl to declare a non-nullable version of MessageType.
* Replace the null in blah|null with none. This is necessary because the
* compiler will infer MessageType to be nullable if the value parameter is
* nullable.
* @template MessageTypeNonNull :=
* cond(isUnknown(MessageType), unknown(),
* mapunion(MessageType, (X) =>
* cond(eq(X, 'undefined'), none(), cond(eq(X, 'null'), none(), X))))
* =:
*/
writeMessage(field, value, writerCallback) {
if (value == null) return;
const bookmark = this.beginDelimited_(field);
writerCallback(value, this);
this.endDelimited_(bookmark);
}
/**
* Writes a message set extension to the buffer.
* @param {number} field The field number for the extension.
* @param {?MessageType|undefined} value The extension message object to
* write. Note that message set can only have extensions with type of
* optional message.
* @param {function(!MessageTypeNonNull, !BinaryWriter)} writerCallback
* Will be invoked with the value to write and the writer to write it
* with.
* @template MessageType
* Use go/closure-ttl to declare a non-nullable version of MessageType.
* Replace the null in blah|null with none. This is necessary because the
* compiler will infer MessageType to be nullable if the value parameter is
* nullable.
* @template MessageTypeNonNull :=
* cond(isUnknown(MessageType), unknown(),
* mapunion(MessageType, (X) =>
* cond(eq(X, 'undefined'), none(), cond(eq(X, 'null'), none(), X))))
* =:
*/
writeMessageSet(field, value, writerCallback) {
if (value == null) return;
// The wire format for a message set is defined by
// google3/net/proto/message_set.proto
this.writeFieldHeader_(1, WireType.START_GROUP);
this.writeFieldHeader_(2, WireType.VARINT);
this.encoder_.writeSignedVarint32(field);
const bookmark = this.beginDelimited_(3);
writerCallback(value, this);
this.endDelimited_(bookmark);
this.writeFieldHeader_(1, WireType.END_GROUP);
}
/**
* Writes a group message to the buffer.
*
* @param {number} field The field number.
* @param {?MessageType|undefined} value The message to write, wrapped with
* START_GROUP / END_GROUP tags. Will be a no-op if 'value' is null.
* @param {function(MessageTypeNonNull, !BinaryWriter)} writerCallback
* Will be invoked with the value to write and the writer to write it
* with.
* @template MessageType
* Use go/closure-ttl to declare a non-nullable version of MessageType.
* Replace the null in blah|null with none. This is necessary because the
* compiler will infer MessageType to be nullable if the value parameter is
* nullable.
* @template MessageTypeNonNull :=
* cond(isUnknown(MessageType), unknown(),
* mapunion(MessageType, (X) =>
* cond(eq(X, 'undefined'), none(), cond(eq(X, 'null'), none(), X))))
* =:
*/
writeGroup(field, value, writerCallback) {
if (value == null) return;
this.writeFieldHeader_(field, WireType.START_GROUP);
writerCallback(value, this);
this.writeFieldHeader_(field, WireType.END_GROUP);
}
/**
* Writes a 64-bit field to the buffer as a fixed64.
* @param {number} field The field number.
* @param {number} lowBits The low 32 bits.
* @param {number} highBits The high 32 bits.
*/
writeSplitFixed64(field, lowBits, highBits) {
this.writeFieldHeader_(field, WireType.FIXED64);
this.encoder_.writeSplitFixed64(lowBits, highBits);
}
/**
* Writes a 64-bit field to the buffer as a varint.
* @param {number} field The field number.
* @param {number} lowBits The low 32 bits.
* @param {number} highBits The high 32 bits.
*/
writeSplitVarint64(field, lowBits, highBits) {
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeSplitVarint64(lowBits, highBits);
}
/**
* Writes a 64-bit field to the buffer as a zigzag encoded varint.
* @param {number} field The field number.
* @param {number} lowBits The low 32 bits.
* @param {number} highBits The high 32 bits.
*/
writeSplitZigzagVarint64(field, lowBits, highBits) {
this.writeFieldHeader_(field, WireType.VARINT);
this.encoder_.writeSplitZigzagVarint64(lowBits >>> 0, highBits >>> 0);
}
/**
* Writes an array of numbers to the buffer as a repeated 32-bit int field.
* @param {number} field The field number.
* @param {?Array<number>|undefined} value The array of ints to write.
*/
writeRepeatedInt32(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeSignedVarint32_(field, value[i]);
}
}
/**
* Writes an array of numbers to the buffer as a repeated 64-bit int field.
* @param {number} field The field number.
* @param {?Array<number|string|!bigint>|undefined} value The array of ints
* to write.
*/
writeRepeatedInt64(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeSignedVarint64_(field, value[i]);
}
}
/**
* Writes an array of 64-bit values to the buffer as a fixed64.
* @param {number} field The field number.
* @param {?Array<T>|undefined} value The value.
* @param {function(T): number} lo Function to get low bits.
* @param {function(T): number} hi Function to get high bits.
* @template T
*/
writeRepeatedSplitFixed64(field, value, lo, hi) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeSplitFixed64(field, lo(value[i]), hi(value[i]));
}
}
/**
* Writes an array of 64-bit values to the buffer as a varint.
* @param {number} field The field number.
* @param {?Array<T>|undefined} value The value.
* @param {function(T): number} lo Function to get low bits.
* @param {function(T): number} hi Function to get high bits.
* @template T
*/
writeRepeatedSplitVarint64(field, value, lo, hi) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeSplitVarint64(field, lo(value[i]), hi(value[i]));
}
}
/**
* Writes an array of 64-bit values to the buffer as a zigzag varint.
* @param {number} field The field number.
* @param {?Array<T>|undefined} value The value.
* @param {function(T): number} lo Function to get low bits.
* @param {function(T): number} hi Function to get high bits.
* @template T
*/
writeRepeatedSplitZigzagVarint64(field, value, lo, hi) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeSplitZigzagVarint64(field, lo(value[i]), hi(value[i]));
}
}
/**
* Writes an array of numbers formatted as strings to the buffer as a repeated
* 64-bit int field.
* @param {number} field The field number.
* @param {?Array<string>|undefined} value The array of ints to write.
* @deprecated use writeRepeatedInt64().
*/
writeRepeatedInt64String(field, value) {
this.writeRepeatedInt64(field, value);
}
/**
* Writes an array numbers to the buffer as a repeated unsigned 32-bit int
* field.
* @param {number} field The field number.
* @param {?Array<number>|undefined} value The array of ints to write.
*/
writeRepeatedUint32(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeUnsignedVarint32_(field, value[i]);
}
}
/**
* Writes an array numbers or decimal strings to the buffer as a repeated
* unsigned 64-bit int field.
* @param {number} field The field number.
* @param {?Array<number|string|!bigint>|undefined} value The array of ints
* to write.
*/
writeRepeatedUint64(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeUnsignedVarint64_(field, value[i]);
}
}
/**
* Writes an array of numbers formatted as strings to the buffer as a repeated
* unsigned 64-bit int field.
* @param {number} field The field number.
* @param {?Array<string>|undefined} value The array of ints to write.
* @deprecated Use writeRepeatedUint64().
*/
writeRepeatedUint64String(field, value) {
this.writeRepeatedUint64(field, value);
}
/**
* Writes an array numbers to the buffer as a repeated signed 32-bit int
* field.
* @param {number} field The field number.
* @param {?Array<number>|undefined} value The array of ints to write.
*/
writeRepeatedSint32(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeZigzagVarint32_(field, value[i]);
}
}
/**
* Writes an array numbers or decimal strings to the buffer as a repeated
* signed 64-bit int field.
* @param {number} field The field number.
* @param {?Array<number|string|!bigint>|undefined} value The array of ints
* to write.
*/
writeRepeatedSint64(field, value) {
if (value == null) return;
for (let i = 0; i < value.length; i++) {
this.writeZigzagVarint64_(field, value[i]);