-
Notifications
You must be signed in to change notification settings - Fork 67
/
message.js
1927 lines (1733 loc) · 61.9 KB
/
message.js
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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://protobuf.dev/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* @fileoverview Definition of jspb.Message.
*
* @suppress {missingRequire} TODO(b/152540451): this shouldn't be needed
* @author [email protected] (Mark Rawling)
*/
goog.provide('jspb.ExtensionFieldBinaryInfo');
goog.provide('jspb.ExtensionFieldInfo');
goog.provide('jspb.Message');
goog.require('goog.array');
goog.require('goog.crypt.base64');
goog.require('jspb.asserts');
goog.require('jspb.BinaryReader');
goog.require('jspb.Map');
/**
* Stores information for a single extension field.
*
* For example, an extension field defined like so:
*
* extend BaseMessage {
* optional MyMessage my_field = 123;
* }
*
* will result in an ExtensionFieldInfo object with these properties:
*
* {
* fieldIndex: 123,
* fieldName: {my_field_renamed: 0},
* ctor: proto.example.MyMessage,
* toObjectFn: proto.example.MyMessage.toObject,
* isRepeated: 0
* }
*
* We include `toObjectFn` to allow the JSCompiler to perform dead-code removal
* on unused toObject() methods.
*
* If an extension field is primitive, ctor and toObjectFn will be null.
* isRepeated should be 0 or 1.
*
* binary{Reader,Writer}Fn and (if message type) binaryMessageSerializeFn are
* always provided. binaryReaderFn and binaryWriterFn are references to the
* appropriate methods on BinaryReader/BinaryWriter to read/write the value of
* this extension, and binaryMessageSerializeFn is a reference to the message
* class's .serializeBinary method, if available.
*
* @param {number} fieldNumber
* @param {Object} fieldName This has the extension field name as a property.
* @param {?function(new: jspb.Message, Array=)} ctor
* @param {?function((boolean|undefined),!jspb.Message):!Object} toObjectFn
* @param {number} isRepeated
* @constructor
* @struct
* @template T
* @export
*/
jspb.ExtensionFieldInfo = function(
fieldNumber, fieldName, ctor, toObjectFn, isRepeated) {
/** @const */
this.fieldIndex = fieldNumber;
/** @const */
this.fieldName = fieldName;
/** @const */
this.ctor = ctor;
/** @const */
this.toObjectFn = toObjectFn;
/** @const */
this.isRepeated = isRepeated;
};
/**
* Stores binary-related information for a single extension field.
* @param {!jspb.ExtensionFieldInfo<T>} fieldInfo
* @param {function(this:jspb.BinaryReader,number,?,?)} binaryReaderFn
* @param {function(this:jspb.BinaryWriter,number,?)
* |function(this:jspb.BinaryWriter,number,?,?,?,?,?)} binaryWriterFn
* @param {function(?,?)=} opt_binaryMessageSerializeFn
* @param {function(?,?)=} opt_binaryMessageDeserializeFn
* @param {boolean=} opt_isPacked
* @constructor
* @struct
* @template T
* @export
*/
jspb.ExtensionFieldBinaryInfo = function(
fieldInfo, binaryReaderFn, binaryWriterFn, opt_binaryMessageSerializeFn,
opt_binaryMessageDeserializeFn, opt_isPacked) {
/** @const */
this.fieldInfo = fieldInfo;
/** @const */
this.binaryReaderFn = binaryReaderFn;
/** @const */
this.binaryWriterFn = binaryWriterFn;
/** @const */
this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
/** @const */
this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
/** @const */
this.isPacked = opt_isPacked;
};
/**
* @return {boolean} Does this field represent a sub Message?
* @export
*/
jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
return !!this.ctor;
};
/**
* Base class for all JsPb messages.
*
* Several common methods (toObject, serializeBinary, in particular) are not
* defined on the prototype to encourage code patterns that minimize code bloat
* due to otherwise unused code on all protos contained in the project.
*
* If you want to call these methods on a generic message, either
* pass in your instance of method as a parameter:
* someFunction(instanceOfKnownProto,
* KnownProtoClass.prototype.serializeBinary);
* or use a lambda that knows the type:
* someFunction(()=>instanceOfKnownProto.serializeBinary());
* or, if you don't care about code size, just suppress the
* WARNING - Property serializeBinary never defined on jspb.Message
* and call it the intuitive way.
*
* @constructor
* @struct
* @export
*/
jspb.Message = function() {};
/**
* @define {boolean} Whether to generate toObject methods for objects. Turn
* this off, if you do not want toObject to be ever used in your project.
* When turning off this flag, consider adding a conformance test that bans
* calling toObject. Enabling this will disable the JSCompiler's ability to
* dead code eliminate fields used in protocol buffers that are never used
* in an application.
* @export
*/
jspb.Message.GENERATE_TO_OBJECT =
goog.define('jspb.Message.GENERATE_TO_OBJECT', true);
/**
* @define {boolean} Whether to generate fromObject methods for objects. Turn
* this off, if you do not want fromObject to be ever used in your project.
* When turning off this flag, consider adding a conformance test that bans
* calling fromObject. Enabling this might disable the JSCompiler's ability
* to dead code eliminate fields used in protocol buffers that are never
* used in an application.
* By default this is enabled for test code only.
* @export
*/
jspb.Message.GENERATE_FROM_OBJECT = goog.define(
'jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
/**
* @define {boolean} Whether to generate toString methods for objects. Turn
* this off if you do not use toString in your project and want to trim it
* from the compiled JS.
*/
jspb.Message.GENERATE_TO_STRING =
goog.define('jspb.Message.GENERATE_TO_STRING', true);
/**
* @define {boolean} Whether arrays passed to initialize() can be assumed to be
* local (e.g. not from another iframe) and thus safely classified with
* instanceof Array.
*/
jspb.Message.ASSUME_LOCAL_ARRAYS =
goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
// TODO(jakubvrana): Turn this off by default.
/**
* @define {boolean} Disabling the serialization of empty trailing fields
* reduces the size of serialized protos. The price is an extra iteration of
* the proto before serialization. This is enabled by default to be
* backwards compatible. Projects are advised to turn this flag always off.
* @private
*/
jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS =
goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
/**
* Does this JavaScript environment support Uint8Aray typed arrays?
* @type {boolean}
* @private
*/
jspb.Message.SUPPORTS_UINT8ARRAY_ = (typeof Uint8Array == 'function');
/**
* The internal data array.
* @type {!Array}
* @private
*/
jspb.Message.prototype.array;
/**
* Wrappers are the constructed instances of message-type fields. They are built
* on demand from the raw array data. Includes message fields, repeated message
* fields and extension message fields. Indexed by field number.
* @type {Object}
* @private
*/
jspb.Message.prototype.wrappers_;
/**
* The object that contains extension fields, if any. This is an object that
* maps from a proto field number to the field's value.
* @type {Object}
* @private
*/
jspb.Message.prototype.extensionObject_;
/**
* Non-extension fields with a field number at or above the pivot are
* stored in the extension object (in addition to all extension fields).
* @type {number}
* @private
*/
jspb.Message.prototype.pivot_;
/**
* The JsPb message_id of this proto.
* @type {string|undefined} the message id or undefined if this message
* has no id.
* @private
*/
jspb.Message.prototype.messageId_;
/**
* Repeated fields that have been converted to their proper type. This is used
* for numbers stored as strings (typically "NaN", "Infinity" and "-Infinity")
* and for booleans stored as numbers (0 or 1).
* @private {!Object<number,boolean>|undefined}
*/
jspb.Message.prototype.convertedPrimitiveFields_;
/**
* Repeated fields numbers.
* @protected {?Array<number>|undefined}
*/
jspb.Message.prototype.repeatedFields;
/**
* Returns the JsPb message_id of this proto.
* @return {string|undefined} the message id or undefined if this message
* has no id.
* @export
*/
jspb.Message.prototype.getJsPbMessageId = function() {
return this.messageId_;
};
/**
* An offset applied to lookups into this.array to account for the presence or
* absence of a messageId at position 0. For response messages, this will be 0.
* Otherwise, it will be -1 so that the first array position is not wasted.
* @type {number}
* @private
*/
jspb.Message.prototype.arrayIndexOffset_;
/**
* Returns the index into msg.array at which the proto field with tag number
* fieldNumber will be located.
* @param {!jspb.Message} msg Message for which we're calculating an index.
* @param {number} fieldNumber The field number.
* @return {number} The index.
* @private
*/
jspb.Message.getIndex_ = function(msg, fieldNumber) {
return fieldNumber + msg.arrayIndexOffset_;
};
// This is only here to ensure we are not back sliding on ES6 requirements for
// protos in g3.
jspb.Message.hiddenES6Property_ = class {};
/**
* Returns the tag number based on the index in msg.array.
* @param {!jspb.Message} msg Message for which we're calculating an index.
* @param {number} index The tag number.
* @return {number} The field number.
* @private
*/
jspb.Message.getFieldNumber_ = function(msg, index) {
return index - msg.arrayIndexOffset_;
};
/**
* Initializes a JsPb Message.
* @param {!jspb.Message} msg The JsPb proto to modify.
* @param {Array|undefined} data An initial data array.
* @param {string|number} messageId For response messages, the message id or ''
* if no message id is specified. For non-response messages, 0.
* @param {number} suggestedPivot The field number at which to start putting
* fields into the extension object. This is only used if data does not
* contain an extension object already. -1 if no extension object is
* required for this message type.
* @param {Array<number>} repeatedFields The message's repeated fields.
* @param {Array<!Array<number>>=} opt_oneofFields The fields belonging to
* each of the message's oneof unions.
* @export
*/
jspb.Message.initialize = function(
msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
msg.wrappers_ = null;
if (!data) {
data = messageId ? [messageId] : [];
}
msg.messageId_ = messageId ? String(messageId) : undefined;
// If the messageId is 0, this message is not a response message, so we shift
// array indices down by 1 so as not to waste the first position in the array,
// which would otherwise go unused.
msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
msg.array = data;
jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
msg.convertedPrimitiveFields_ = {};
if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
// TODO(jakubvrana): This is same for all instances, move to prototype.
// TODO(jakubvrana): There are indexOf calls on this in serialization,
// consider switching to a set.
msg.repeatedFields = repeatedFields;
}
if (repeatedFields) {
for (var i = 0; i < repeatedFields.length; i++) {
var fieldNumber = repeatedFields[i];
if (fieldNumber < msg.pivot_) {
var index = jspb.Message.getIndex_(msg, fieldNumber);
msg.array[index] =
msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_;
} else {
jspb.Message.maybeInitEmptyExtensionObject_(msg);
msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] ||
jspb.Message.EMPTY_LIST_SENTINEL_;
}
}
}
if (opt_oneofFields && opt_oneofFields.length) {
// Compute the oneof case for each union. This ensures only one value is
// set in the union.
for (var i = 0; i < opt_oneofFields.length; i++) {
jspb.Message.computeOneofCase(msg, opt_oneofFields[i]);
}
}
};
/**
* Used to mark empty repeated fields. Serializes to null when serialized
* to JSON.
* When reading a repeated field readers must check the return value against
* this value and return and replace it with a new empty array if it is
* present.
* @private @const {!Object}
*/
jspb.Message.EMPTY_LIST_SENTINEL_ =
goog.DEBUG && Object.freeze ? Object.freeze([]) : [];
/**
* Returns true if the provided argument is an array.
* @param {*} o The object to classify as array or not.
* @return {boolean} True if the provided object is an array.
* @private
*/
jspb.Message.isArray_ = function(o) {
return jspb.Message.ASSUME_LOCAL_ARRAYS ? o instanceof Array :
Array.isArray(o);
};
/**
* Returns true if the provided argument is an extension object.
* @param {*} o The object to classify as array or not.
* @return {boolean} True if the provided object is an extension object.
* @private
*/
jspb.Message.isExtensionObject_ = function(o) {
// Normal fields are never objects, so we can be sure that if we find an
// object here, then it's the extension object. However, we must ensure that
// the object is not an array, since arrays are valid field values (bytes
// fields can also be array).
// NOTE(lukestebbing): We avoid looking at .length to avoid a JIT bug
// in Safari on iOS 8. See the description of CL/86511464 for details.
return (
o !== null && typeof o == 'object' && !jspb.Message.isArray_(o) &&
!(jspb.Message.SUPPORTS_UINT8ARRAY_ && o instanceof Uint8Array));
};
/**
* If the array contains an extension object in its last position, then the
* object is kept in place and its position is used as the pivot. If not,
* decides the pivot of the message based on suggestedPivot without
* materializing the extension object.
*
* @param {!jspb.Message} msg The JsPb proto to modify.
* @param {number} suggestedPivot See description for initialize().
* @private
*/
jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
// There are 3 variants that need to be dealt with which are the
// combination of whether there exists an extension object (EO) and
// whether there is a suggested pivot (SP).
//
// EO, ? : pivot is the index of the EO
// no-EO, no-SP: pivot is MAX_INT
// no-EO, SP : pivot is the max(lastindex + 1, SP)
var msgLength = msg.array.length;
var lastIndex = -1;
if (msgLength) {
lastIndex = msgLength - 1;
var obj = msg.array[lastIndex];
if (jspb.Message.isExtensionObject_(obj)) {
msg.pivot_ = jspb.Message.getFieldNumber_(msg, lastIndex);
msg.extensionObject_ = obj;
return;
}
}
if (suggestedPivot > -1) {
// If a extension object is not present, set the pivot value as being
// after the last value in the array to avoid overwriting values, etc.
msg.pivot_ = Math.max(
suggestedPivot, jspb.Message.getFieldNumber_(msg, lastIndex + 1));
// Avoid changing the shape of the proto with an empty extension object by
// deferring the materialization of the extension object until the first
// time a field set into it (may be due to getting a repeated proto field
// from it, in which case a new empty array is set into it at first).
msg.extensionObject_ = null;
} else {
// suggestedPivot is -1, which means that we don't have an extension object
// at all, in which case all fields are stored in the array.
msg.pivot_ = Number.MAX_VALUE;
}
};
/**
* Creates an empty extensionObject_ if non exists.
* @param {!jspb.Message} msg The JsPb proto to modify.
* @private
*/
jspb.Message.maybeInitEmptyExtensionObject_ = function(msg) {
var pivotIndex = jspb.Message.getIndex_(msg, msg.pivot_);
if (!msg.array[pivotIndex]) {
msg.extensionObject_ = msg.array[pivotIndex] = {};
}
};
/**
* Converts a JsPb repeated message field into an object list.
* @param {!Array<T>} field The repeated message field to be
* converted.
* @param {?function(boolean=): Object|
* function((boolean|undefined),T): Object} toObjectFn The toObject
* function for this field. We need to pass this for effective dead code
* removal.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
* @return {!Array<Object>} An array of converted message objects.
* @template T
* @export
*/
jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) {
// Not using goog.array.map in the generated code to keep it small.
// And not using it here to avoid a function call.
var result = [];
for (var i = 0; i < field.length; i++) {
result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]);
}
return result;
};
/**
* Adds a proto's extension data to a Soy rendering object.
* @param {!jspb.Message} proto The proto whose extensions to convert.
* @param {!Object} obj The Soy object to add converted extension data to.
* @param {!Object} extensions The proto class' registered extensions.
* @param {function(this:?, jspb.ExtensionFieldInfo) : *} getExtensionFn
* The proto class' getExtension function. Passed for effective dead code
* removal.
* @param {boolean=} opt_includeInstance Whether to include the JSPB instance
* for transitional soy proto support: http://goto/soy-param-migration
* @export
*/
jspb.Message.toObjectExtension = function(
proto, obj, extensions, getExtensionFn, opt_includeInstance) {
for (var fieldNumber in extensions) {
var fieldInfo = extensions[fieldNumber];
var value = getExtensionFn.call(proto, fieldInfo);
if (value != null) {
for (var name in fieldInfo.fieldName) {
if (fieldInfo.fieldName.hasOwnProperty(name)) {
break; // the compiled field name
}
}
if (!fieldInfo.toObjectFn) {
obj[name] = value;
} else {
if (fieldInfo.isRepeated) {
obj[name] = jspb.Message.toObjectList(
/** @type {!Array<!jspb.Message>} */ (value),
fieldInfo.toObjectFn, opt_includeInstance);
} else {
obj[name] = fieldInfo.toObjectFn(
opt_includeInstance, /** @type {!jspb.Message} */ (value));
}
}
}
}
};
/**
* Writes a proto's extension data to a binary-format output stream.
* @param {!jspb.Message} proto The proto whose extensions to convert.
* @param {*} writer The binary-format writer to write to.
* @param {!Object} extensions The proto class' registered extensions.
* @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo) : *}
* getExtensionFn The proto class' getExtension function. Passed for
* effective dead code removal.
* @export
*/
jspb.Message.serializeBinaryExtensions = function(
proto, writer, extensions, getExtensionFn) {
for (var fieldNumber in extensions) {
var binaryFieldInfo = extensions[fieldNumber];
var fieldInfo = binaryFieldInfo.fieldInfo;
// The old codegen doesn't add the extra fields to ExtensionFieldInfo, so we
// need to gracefully error-out here rather than produce a null dereference
// below.
if (!binaryFieldInfo.binaryWriterFn) {
throw new Error(
'Message extension present that was generated ' +
'without binary serialization support');
}
var value = getExtensionFn.call(proto, fieldInfo);
if (value != null) {
if (fieldInfo.isMessageType()) {
// If the message type of the extension was generated without binary
// support, there may not be a binary message serializer function, and
// we can't know when we codegen the extending message that the extended
// message may require binary support, so we can *only* catch this error
// here, at runtime (and this decoupled codegen is the whole point of
// extensions!).
if (binaryFieldInfo.binaryMessageSerializeFn) {
binaryFieldInfo.binaryWriterFn.call(
writer, fieldInfo.fieldIndex, value,
binaryFieldInfo.binaryMessageSerializeFn);
} else {
throw new Error(
'Message extension present holding submessage ' +
'without binary support enabled, and message is ' +
'being serialized to binary format');
}
} else {
binaryFieldInfo.binaryWriterFn.call(
writer, fieldInfo.fieldIndex, value);
}
}
}
};
/**
* Reads an extension field from the given reader and, if a valid extension,
* sets the extension value.
* @param {!jspb.Message} msg A jspb proto.
* @param {!jspb.BinaryReader} reader
* @param {!Object} extensions The extensions object.
* @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo)} getExtensionFn
* @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo, ?)}
* setExtensionFn
* @export
*/
jspb.Message.readBinaryExtension = function(
msg, reader, extensions, getExtensionFn, setExtensionFn) {
var binaryFieldInfo = extensions[reader.getFieldNumber()];
if (!binaryFieldInfo) {
reader.skipField();
return;
}
var fieldInfo = binaryFieldInfo.fieldInfo;
if (!binaryFieldInfo.binaryReaderFn) {
throw new Error(
'Deserializing extension whose generated code does not ' +
'support binary format');
}
var value;
if (fieldInfo.isMessageType()) {
value = new fieldInfo.ctor();
binaryFieldInfo.binaryReaderFn.call(
reader, value, binaryFieldInfo.binaryMessageDeserializeFn);
} else {
// All other types.
value = binaryFieldInfo.binaryReaderFn.call(reader);
}
if (fieldInfo.isRepeated && !binaryFieldInfo.isPacked) {
var currentList = getExtensionFn.call(msg, fieldInfo);
if (!currentList) {
setExtensionFn.call(msg, fieldInfo, [value]);
} else {
currentList.push(value);
}
} else {
setExtensionFn.call(msg, fieldInfo, value);
}
};
/**
* Gets the value of a non-extension field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {string|number|boolean|Uint8Array|Array|null|undefined}
* The field's value.
* @export
*/
jspb.Message.getField = function(msg, fieldNumber) {
if (fieldNumber < msg.pivot_) {
var index = jspb.Message.getIndex_(msg, fieldNumber);
var val = msg.array[index];
if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
return msg.array[index] = [];
}
return val;
} else {
if (!msg.extensionObject_) {
return undefined;
}
var val = msg.extensionObject_[fieldNumber];
if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
return msg.extensionObject_[fieldNumber] = [];
}
return val;
}
};
/**
* Gets the value of a non-extension repeated field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {!Array}
* The field's value.
* @export
*/
jspb.Message.getRepeatedField = function(msg, fieldNumber) {
return /** @type {!Array} */ (jspb.Message.getField(msg, fieldNumber));
};
/**
* Gets the value of an optional float or double field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {?number|undefined} The field's value.
* @export
*/
jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
var value = jspb.Message.getField(msg, fieldNumber);
// Converts "NaN", "Infinity" and "-Infinity" to their corresponding numbers.
return value == null ? value : +value;
};
/**
* Gets the value of an optional boolean field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {?boolean|undefined} The field's value.
* @export
*/
jspb.Message.getBooleanField = function(msg, fieldNumber) {
var value = jspb.Message.getField(msg, fieldNumber);
// TODO(b/122673075): always return null when the value is null-ish.
return value == null ? (value) : !!value;
};
/**
* Gets the value of a repeated float or double field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {!Array<number>} The field's value.
* @export
*/
jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
var values = jspb.Message.getRepeatedField(msg, fieldNumber);
if (!msg.convertedPrimitiveFields_) {
msg.convertedPrimitiveFields_ = {};
}
if (!msg.convertedPrimitiveFields_[fieldNumber]) {
for (var i = 0; i < values.length; i++) {
// Converts "NaN", "Infinity" and "-Infinity" to their corresponding
// numbers.
values[i] = +values[i];
}
msg.convertedPrimitiveFields_[fieldNumber] = true;
}
return /** @type {!Array<number>} */ (values);
};
/**
* Gets the value of a repeated boolean field.
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @return {!Array<boolean>} The field's value.
* @export
*/
jspb.Message.getRepeatedBooleanField = function(msg, fieldNumber) {
var values = jspb.Message.getRepeatedField(msg, fieldNumber);
if (!msg.convertedPrimitiveFields_) {
msg.convertedPrimitiveFields_ = {};
}
if (!msg.convertedPrimitiveFields_[fieldNumber]) {
for (var i = 0; i < values.length; i++) {
// Converts 0 and 1 to their corresponding booleans.
values[i] = !!values[i];
}
msg.convertedPrimitiveFields_[fieldNumber] = true;
}
return /** @type {!Array<boolean>} */ (values);
};
/**
* Coerce a 'bytes' field to a base 64 string.
* @param {string|Uint8Array|null} value
* @return {?string} The field's coerced value.
* @export
*/
jspb.Message.bytesAsB64 = function(value) {
if (value == null || typeof value === 'string') {
return value;
}
if (jspb.Message.SUPPORTS_UINT8ARRAY_ && value instanceof Uint8Array) {
return goog.crypt.base64.encodeByteArray(value);
}
jspb.asserts.fail('Cannot coerce to b64 string: ' + goog.typeOf(value));
return null;
};
/**
* Coerce a 'bytes' field to a Uint8Array byte buffer.
* Note that Uint8Array is not supported on IE versions before 10 nor on Opera
* Mini. @see http://caniuse.com/Uint8Array
* @param {string|Uint8Array|null} value
* @return {?Uint8Array} The field's coerced value.
* @export
*/
jspb.Message.bytesAsU8 = function(value) {
if (value == null || value instanceof Uint8Array) {
return value;
}
if (typeof value === 'string') {
return goog.crypt.base64.decodeStringToUint8Array(value);
}
jspb.asserts.fail('Cannot coerce to Uint8Array: ' + goog.typeOf(value));
return null;
};
/**
* Coerce a repeated 'bytes' field to an array of base 64 strings.
* Note: the returned array should be treated as immutable.
* @param {!Array<string>|!Array<!Uint8Array>} value
* @return {!Array<string?>} The field's coerced value.
* @export
*/
jspb.Message.bytesListAsB64 = function(value) {
jspb.Message.assertConsistentTypes_(value);
if (!value.length || typeof value[0] === 'string') {
return /** @type {!Array<string>} */ (value);
}
return goog.array.map(value, jspb.Message.bytesAsB64);
};
/**
* Coerce a repeated 'bytes' field to an array of Uint8Array byte buffers.
* Note: the returned array should be treated as immutable.
* Note that Uint8Array is not supported on IE versions before 10 nor on Opera
* Mini. @see http://caniuse.com/Uint8Array
* @param {!Array<string>|!Array<!Uint8Array>} value
* @return {!Array<Uint8Array?>} The field's coerced value.
* @export
*/
jspb.Message.bytesListAsU8 = function(value) {
jspb.Message.assertConsistentTypes_(value);
if (!value.length || value[0] instanceof Uint8Array) {
return /** @type {!Array<!Uint8Array>} */ (value);
}
return goog.array.map(value, jspb.Message.bytesAsU8);
};
/**
* Asserts that all elements of an array are of the same type.
* @param {Array?} array The array to test.
* @private
*/
jspb.Message.assertConsistentTypes_ = function(array) {
if (goog.DEBUG && array && array.length > 1) {
var expected = goog.typeOf(array[0]);
goog.array.forEach(array, function(e) {
if (goog.typeOf(e) != expected) {
jspb.asserts.fail(
'Inconsistent type in JSPB repeated field array. ' +
'Got ' + goog.typeOf(e) + ' expected ' + expected);
}
});
}
};
/**
* Gets the value of a non-extension primitive field, with proto3 (non-nullable
* primitives) semantics. Returns `defaultValue` if the field is not otherwise
* set.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {T} defaultValue The default value.
* @return {T} The field's value.
* @export
*/
jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
var value = jspb.Message.getField(msg, fieldNumber);
if (value == null) {
return defaultValue;
} else {
return value;
}
};
/**
* Gets the value of a boolean field, with proto3 (non-nullable primitives)
* semantics. Returns `defaultValue` if the field is not otherwise set.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {boolean} defaultValue The default value.
* @return {boolean} The field's value.
* @export
*/
jspb.Message.getBooleanFieldWithDefault = function(
msg, fieldNumber, defaultValue) {
var value = jspb.Message.getBooleanField(msg, fieldNumber);
if (value == null) {
return defaultValue;
} else {
return value;
}
};
/**
* Gets the value of a floating point field, with proto3 (non-nullable
* primitives) semantics. Returns `defaultValue` if the field is not otherwise
* set.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {number} defaultValue The default value.
* @return {number} The field's value.
* @export
*/
jspb.Message.getFloatingPointFieldWithDefault = function(
msg, fieldNumber, defaultValue) {
var value = jspb.Message.getOptionalFloatingPointField(msg, fieldNumber);
if (value == null) {
return defaultValue;
} else {
return value;
}
};
/**
* Alias for getFieldWithDefault used by older generated code.
* @template T
* @param {!jspb.Message} msg A jspb proto.
* @param {number} fieldNumber The field number.
* @param {T} defaultValue The default value.
* @return {T} The field's value.
* @export
*/
jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
/**
* Gets the value of a map field, lazily creating the map container if
* necessary.
*
* This should only be called from generated code, because it requires knowledge
* of serialization/parsing callbacks (which are required by the map at
* construction time, and the map may be constructed here).
*
* @template K, V
* @param {!jspb.Message} msg
* @param {number} fieldNumber
* @param {boolean|undefined} noLazyCreate
* @param {?=} opt_valueCtor
* @return {!jspb.Map<K, V>|undefined}
* @export
*/
jspb.Message.getMapField = function(
msg, fieldNumber, noLazyCreate, opt_valueCtor) {
if (!msg.wrappers_) {
msg.wrappers_ = {};
}
// If we already have a map in the map wrappers, return that.
if (fieldNumber in msg.wrappers_) {
return msg.wrappers_[fieldNumber];
}
var arr = jspb.Message.getField(msg, fieldNumber);
// Wrap the underlying elements array with a Map.
if (!arr) {
if (noLazyCreate) {
return undefined;
}
arr = [];
jspb.Message.setField(msg, fieldNumber, arr);
}
return msg.wrappers_[fieldNumber] = new jspb.Map(
/** @type {!Array<!Array<!Object>>} */ (arr), opt_valueCtor);
};
/**
* Sets the value of a non-extension field.
* @param {T} msg A jspb proto.