Imported Upstream version 3.8.0
[platform/upstream/protobuf.git] / js / message.js
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 /**
32  * @fileoverview Definition of jspb.Message.
33  *
34  * @author mwr@google.com (Mark Rawling)
35  */
36
37 goog.provide('jspb.ExtensionFieldBinaryInfo');
38 goog.provide('jspb.ExtensionFieldInfo');
39 goog.provide('jspb.Message');
40
41 goog.require('goog.array');
42 goog.require('goog.asserts');
43 goog.require('goog.crypt.base64');
44 goog.require('jspb.BinaryReader');
45 goog.require('jspb.Map');
46
47 // Not needed in compilation units that have no protos with xids.
48 goog.forwardDeclare('xid.String');
49
50
51
52 /**
53  * Stores information for a single extension field.
54  *
55  * For example, an extension field defined like so:
56  *
57  *     extend BaseMessage {
58  *       optional MyMessage my_field = 123;
59  *     }
60  *
61  * will result in an ExtensionFieldInfo object with these properties:
62  *
63  *     {
64  *       fieldIndex: 123,
65  *       fieldName: {my_field_renamed: 0},
66  *       ctor: proto.example.MyMessage,
67  *       toObjectFn: proto.example.MyMessage.toObject,
68  *       isRepeated: 0
69  *     }
70  *
71  * We include `toObjectFn` to allow the JSCompiler to perform dead-code removal
72  * on unused toObject() methods.
73  *
74  * If an extension field is primitive, ctor and toObjectFn will be null.
75  * isRepeated should be 0 or 1.
76  *
77  * binary{Reader,Writer}Fn and (if message type) binaryMessageSerializeFn are
78  * always provided. binaryReaderFn and binaryWriterFn are references to the
79  * appropriate methods on BinaryReader/BinaryWriter to read/write the value of
80  * this extension, and binaryMessageSerializeFn is a reference to the message
81  * class's .serializeBinary method, if available.
82  *
83  * @param {number} fieldNumber
84  * @param {Object} fieldName This has the extension field name as a property.
85  * @param {?function(new: jspb.Message, Array=)} ctor
86  * @param {?function((boolean|undefined),!jspb.Message):!Object} toObjectFn
87  * @param {number} isRepeated
88  * @constructor
89  * @struct
90  * @template T
91  */
92 jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
93     isRepeated) {
94   /** @const */
95   this.fieldIndex = fieldNumber;
96   /** @const */
97   this.fieldName = fieldName;
98   /** @const */
99   this.ctor = ctor;
100   /** @const */
101   this.toObjectFn = toObjectFn;
102   /** @const */
103   this.isRepeated = isRepeated;
104 };
105
106 /**
107  * Stores binary-related information for a single extension field.
108  * @param {!jspb.ExtensionFieldInfo<T>} fieldInfo
109  * @param {function(this:jspb.BinaryReader,number,?)} binaryReaderFn
110  * @param {function(this:jspb.BinaryWriter,number,?)
111  *        |function(this:jspb.BinaryWriter,number,?,?,?,?,?)} binaryWriterFn
112  * @param {function(?,?)=} opt_binaryMessageSerializeFn
113  * @param {function(?,?)=} opt_binaryMessageDeserializeFn
114  * @param {boolean=} opt_isPacked
115  * @constructor
116  * @struct
117  * @template T
118  */
119 jspb.ExtensionFieldBinaryInfo = function(fieldInfo, binaryReaderFn, binaryWriterFn,
120     opt_binaryMessageSerializeFn, opt_binaryMessageDeserializeFn, opt_isPacked) {
121   /** @const */
122   this.fieldInfo = fieldInfo;
123   /** @const */
124   this.binaryReaderFn = binaryReaderFn;
125   /** @const */
126   this.binaryWriterFn = binaryWriterFn;
127   /** @const */
128   this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
129   /** @const */
130   this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
131   /** @const */
132   this.isPacked = opt_isPacked;
133 };
134
135 /**
136  * @return {boolean} Does this field represent a sub Message?
137  */
138 jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
139   return !!this.ctor;
140 };
141
142
143 /**
144  * Base class for all JsPb messages.
145  *
146  * Several common methods (toObject, serializeBinary, in particular) are not
147  * defined on the prototype to encourage code patterns that minimize code bloat
148  * due to otherwise unused code on all protos contained in the project.
149  *
150  * If you want to call these methods on a generic message, either
151  * pass in your instance of method as a parameter:
152  *     someFunction(instanceOfKnownProto,
153  *                  KnownProtoClass.prototype.serializeBinary);
154  * or use a lambda that knows the type:
155  *     someFunction(()=>instanceOfKnownProto.serializeBinary());
156  * or, if you don't care about code size, just suppress the
157  *     WARNING - Property serializeBinary never defined on jspb.Message
158  * and call it the intuitive way.
159  *
160  * @constructor
161  * @struct
162  */
163 jspb.Message = function() {
164 };
165
166
167 /**
168  * @define {boolean} Whether to generate toObject methods for objects. Turn
169  *     this off, if you do not want toObject to be ever used in your project.
170  *     When turning off this flag, consider adding a conformance test that bans
171  *     calling toObject. Enabling this will disable the JSCompiler's ability to
172  *     dead code eliminate fields used in protocol buffers that are never used
173  *     in an application.
174  */
175 jspb.Message.GENERATE_TO_OBJECT =
176     goog.define('jspb.Message.GENERATE_TO_OBJECT', true);
177
178
179 /**
180  * @define {boolean} Whether to generate fromObject methods for objects. Turn
181  *     this off, if you do not want fromObject to be ever used in your project.
182  *     When turning off this flag, consider adding a conformance test that bans
183  *     calling fromObject. Enabling this might disable the JSCompiler's ability
184  *     to dead code eliminate fields used in protocol buffers that are never
185  *     used in an application.
186  *     By default this is enabled for test code only.
187  */
188 jspb.Message.GENERATE_FROM_OBJECT = goog.define(
189     'jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
190
191
192 /**
193  * @define {boolean} Whether to generate toString methods for objects. Turn
194  *     this off if you do not use toString in your project and want to trim it
195  *     from the compiled JS.
196  */
197 jspb.Message.GENERATE_TO_STRING =
198     goog.define('jspb.Message.GENERATE_TO_STRING', true);
199
200
201 /**
202  * @define {boolean} Whether arrays passed to initialize() can be assumed to be
203  *     local (e.g. not from another iframe) and thus safely classified with
204  *     instanceof Array.
205  */
206 jspb.Message.ASSUME_LOCAL_ARRAYS =
207     goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
208
209
210 // TODO(jakubvrana): Turn this off by default.
211 /**
212  * @define {boolean} Disabling the serialization of empty trailing fields
213  *     reduces the size of serialized protos. The price is an extra iteration of
214  *     the proto before serialization. This is enabled by default to be
215  *     backwards compatible. Projects are advised to turn this flag always off.
216  */
217 jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS =
218     goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
219
220
221 /**
222  * Does this JavaScript environment support Uint8Aray typed arrays?
223  * @type {boolean}
224  * @private
225  */
226 jspb.Message.SUPPORTS_UINT8ARRAY_ = (typeof Uint8Array == 'function');
227
228
229 /**
230  * The internal data array.
231  * @type {!Array}
232  * @protected
233  */
234 jspb.Message.prototype.array;
235
236
237 /**
238  * Wrappers are the constructed instances of message-type fields. They are built
239  * on demand from the raw array data. Includes message fields, repeated message
240  * fields and extension message fields. Indexed by field number.
241  * @type {Object}
242  * @private
243  */
244 jspb.Message.prototype.wrappers_;
245
246
247 /**
248  * The object that contains extension fields, if any. This is an object that
249  * maps from a proto field number to the field's value.
250  * @type {Object}
251  * @private
252  */
253 jspb.Message.prototype.extensionObject_;
254
255
256 /**
257  * Non-extension fields with a field number at or above the pivot are
258  * stored in the extension object (in addition to all extension fields).
259  * @type {number}
260  * @private
261  */
262 jspb.Message.prototype.pivot_;
263
264
265 /**
266  * The JsPb message_id of this proto.
267  * @type {string|undefined} the message id or undefined if this message
268  *     has no id.
269  * @private
270  */
271 jspb.Message.prototype.messageId_;
272
273
274 /**
275  * Repeated fields that have been converted to their proper type. This is used
276  * for numbers stored as strings (typically "NaN", "Infinity" and "-Infinity")
277  * and for booleans stored as numbers (0 or 1).
278  * @private {!Object<number,boolean>|undefined}
279  */
280 jspb.Message.prototype.convertedPrimitiveFields_;
281
282 /**
283  * Repeated fields numbers.
284  * @protected {?Array<number>|undefined}
285  */
286 jspb.Message.prototype.repeatedFields;
287
288
289 /**
290  * The xid of this proto type (The same for all instances of a proto). Provides
291  * a way to identify a proto by stable obfuscated name.
292  * @see {xid}.
293  * Available if {@link jspb.generate_xid} is added as a Message option to
294  * a protocol buffer.
295  * @const {!xid.String|undefined} The xid or undefined if message is
296  *     annotated to generate the xid.
297  */
298 jspb.Message.prototype.messageXid;
299
300
301
302 /**
303  * Returns the JsPb message_id of this proto.
304  * @return {string|undefined} the message id or undefined if this message
305  *     has no id.
306  */
307 jspb.Message.prototype.getJsPbMessageId = function() {
308   return this.messageId_;
309 };
310
311
312 /**
313  * An offset applied to lookups into this.array to account for the presence or
314  * absence of a messageId at position 0. For response messages, this will be 0.
315  * Otherwise, it will be -1 so that the first array position is not wasted.
316  * @type {number}
317  * @private
318  */
319 jspb.Message.prototype.arrayIndexOffset_;
320
321
322 /**
323  * Returns the index into msg.array at which the proto field with tag number
324  * fieldNumber will be located.
325  * @param {!jspb.Message} msg Message for which we're calculating an index.
326  * @param {number} fieldNumber The field number.
327  * @return {number} The index.
328  * @private
329  */
330 jspb.Message.getIndex_ = function(msg, fieldNumber) {
331   return fieldNumber + msg.arrayIndexOffset_;
332 };
333
334 // This is only here to ensure we are not back sliding on ES6 requiements for
335 // protos in g3.
336 jspb.Message.hiddenES6Property_ = class {};
337
338
339 /**
340  * Returns the tag number based on the index in msg.array.
341  * @param {!jspb.Message} msg Message for which we're calculating an index.
342  * @param {number} index The tag number.
343  * @return {number} The field number.
344  * @private
345  */
346 jspb.Message.getFieldNumber_ = function(msg, index) {
347   return index - msg.arrayIndexOffset_;
348 };
349
350
351 /**
352  * Initializes a JsPb Message.
353  * @param {!jspb.Message} msg The JsPb proto to modify.
354  * @param {Array|undefined} data An initial data array.
355  * @param {string|number} messageId For response messages, the message id or ''
356  *     if no message id is specified. For non-response messages, 0.
357  * @param {number} suggestedPivot The field number at which to start putting
358  *     fields into the extension object. This is only used if data does not
359  *     contain an extension object already. -1 if no extension object is
360  *     required for this message type.
361  * @param {Array<number>} repeatedFields The message's repeated fields.
362  * @param {Array<!Array<number>>=} opt_oneofFields The fields belonging to
363  *     each of the message's oneof unions.
364  * @protected
365  */
366 jspb.Message.initialize = function(
367     msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
368   msg.wrappers_ = null;
369   if (!data) {
370     data = messageId ? [messageId] : [];
371   }
372   msg.messageId_ = messageId ? String(messageId) : undefined;
373   // If the messageId is 0, this message is not a response message, so we shift
374   // array indices down by 1 so as not to waste the first position in the array,
375   // which would otherwise go unused.
376   msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
377   msg.array = data;
378   jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
379   msg.convertedPrimitiveFields_ = {};
380
381   if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
382     // TODO(jakubvrana): This is same for all instances, move to prototype.
383     // TODO(jakubvrana): There are indexOf calls on this in serializtion,
384     // consider switching to a set.
385     msg.repeatedFields = repeatedFields;
386   }
387
388   if (repeatedFields) {
389     for (var i = 0; i < repeatedFields.length; i++) {
390       var fieldNumber = repeatedFields[i];
391       if (fieldNumber < msg.pivot_) {
392         var index = jspb.Message.getIndex_(msg, fieldNumber);
393         msg.array[index] =
394             msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_;
395       } else {
396         jspb.Message.maybeInitEmptyExtensionObject_(msg);
397         msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] ||
398             jspb.Message.EMPTY_LIST_SENTINEL_;
399       }
400     }
401   }
402
403   if (opt_oneofFields && opt_oneofFields.length) {
404     // Compute the oneof case for each union. This ensures only one value is
405     // set in the union.
406     for (var i = 0; i < opt_oneofFields.length; i++) {
407       jspb.Message.computeOneofCase(msg, opt_oneofFields[i]);
408     }
409   }
410 };
411
412
413 /**
414  * Used to mark empty repeated fields. Serializes to null when serialized
415  * to JSON.
416  * When reading a repeated field readers must check the return value against
417  * this value and return and replace it with a new empty array if it is
418  * present.
419  * @private @const {!Object}
420  */
421 jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ?
422     Object.freeze([]) :
423     [];
424
425
426 /**
427  * Returns true if the provided argument is an array.
428  * @param {*} o The object to classify as array or not.
429  * @return {boolean} True if the provided object is an array.
430  * @private
431  */
432 jspb.Message.isArray_ = function(o) {
433   return jspb.Message.ASSUME_LOCAL_ARRAYS ? o instanceof Array :
434                                             goog.isArray(o);
435 };
436
437 /**
438  * Returns true if the provided argument is an extension object.
439  * @param {*} o The object to classify as array or not.
440  * @return {boolean} True if the provided object is an extension object.
441  * @private
442  */
443 jspb.Message.isExtensionObject_ = function(o) {
444   // Normal fields are never objects, so we can be sure that if we find an
445   // object here, then it's the extension object. However, we must ensure that
446   // the object is not an array, since arrays are valid field values (bytes
447   // fields can also be array).
448   // NOTE(lukestebbing): We avoid looking at .length to avoid a JIT bug
449   // in Safari on iOS 8. See the description of CL/86511464 for details.
450   return (o !== null && typeof o == 'object' &&
451       !jspb.Message.isArray_(o) &&
452       !(jspb.Message.SUPPORTS_UINT8ARRAY_ && o instanceof Uint8Array));
453 };
454
455
456 /**
457  * If the array contains an extension object in its last position, then the
458  * object is kept in place and its position is used as the pivot.  If not,
459  * decides the pivot of the message based on suggestedPivot without
460  * materializing the extension object.
461  *
462  * @param {!jspb.Message} msg The JsPb proto to modify.
463  * @param {number} suggestedPivot See description for initialize().
464  * @private
465  */
466 jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
467   // There are 3 variants that need to be dealt with which are the
468   // combination of whether there exists an extension object (EO) and
469   // whether there is a suggested pivot (SP).
470   //
471   // EO,    ?    : pivot is the index of the EO
472   // no-EO, no-SP: pivot is MAX_INT
473   // no-EO, SP   : pivot is the max(lastindex + 1, SP)
474
475   var msgLength = msg.array.length;
476   var lastIndex = -1;
477   if (msgLength) {
478     lastIndex = msgLength - 1;
479     var obj = msg.array[lastIndex];
480     if (jspb.Message.isExtensionObject_(obj)) {
481       msg.pivot_ = jspb.Message.getFieldNumber_(msg, lastIndex);
482       msg.extensionObject_ = obj;
483       return;
484     }
485   }
486
487   if (suggestedPivot > -1) {
488     // If a extension object is not present, set the pivot value as being
489     // after the last value in the array to avoid overwriting values, etc.
490     msg.pivot_ = Math.max(
491         suggestedPivot, jspb.Message.getFieldNumber_(msg, lastIndex + 1));
492     // Avoid changing the shape of the proto with an empty extension object by
493     // deferring the materialization of the extension object until the first
494     // time a field set into it (may be due to getting a repeated proto field
495     // from it, in which case a new empty array is set into it at first).
496     msg.extensionObject_ = null;
497   } else {
498     // suggestedPivot is -1, which means that we don't have an extension object
499     // at all, in which case all fields are stored in the array.
500     msg.pivot_ = Number.MAX_VALUE;
501   }
502 };
503
504
505 /**
506  * Creates an empty extensionObject_ if non exists.
507  * @param {!jspb.Message} msg The JsPb proto to modify.
508  * @private
509  */
510 jspb.Message.maybeInitEmptyExtensionObject_ = function(msg) {
511   var pivotIndex = jspb.Message.getIndex_(msg, msg.pivot_);
512   if (!msg.array[pivotIndex]) {
513     msg.extensionObject_ = msg.array[pivotIndex] = {};
514   }
515 };
516
517
518 /**
519  * Converts a JsPb repeated message field into an object list.
520  * @param {!Array<T>} field The repeated message field to be
521  *     converted.
522  * @param {?function(boolean=): Object|
523  *     function((boolean|undefined),T): Object} toObjectFn The toObject
524  *     function for this field.  We need to pass this for effective dead code
525  *     removal.
526  * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
527  *     for transitional soy proto support: http://goto/soy-param-migration
528  * @return {!Array<Object>} An array of converted message objects.
529  * @template T
530  */
531 jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) {
532   // Not using goog.array.map in the generated code to keep it small.
533   // And not using it here to avoid a function call.
534   var result = [];
535   for (var i = 0; i < field.length; i++) {
536     result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]);
537   }
538   return result;
539 };
540
541
542 /**
543  * Adds a proto's extension data to a Soy rendering object.
544  * @param {!jspb.Message} proto The proto whose extensions to convert.
545  * @param {!Object} obj The Soy object to add converted extension data to.
546  * @param {!Object} extensions The proto class' registered extensions.
547  * @param {function(this:?, jspb.ExtensionFieldInfo) : *} getExtensionFn
548  *     The proto class' getExtension function. Passed for effective dead code
549  *     removal.
550  * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
551  *     for transitional soy proto support: http://goto/soy-param-migration
552  */
553 jspb.Message.toObjectExtension = function(proto, obj, extensions,
554     getExtensionFn, opt_includeInstance) {
555   for (var fieldNumber in extensions) {
556     var fieldInfo = extensions[fieldNumber];
557     var value = getExtensionFn.call(proto, fieldInfo);
558     if (value != null) {
559       for (var name in fieldInfo.fieldName) {
560         if (fieldInfo.fieldName.hasOwnProperty(name)) {
561           break; // the compiled field name
562         }
563       }
564       if (!fieldInfo.toObjectFn) {
565         obj[name] = value;
566       } else {
567         if (fieldInfo.isRepeated) {
568           obj[name] = jspb.Message.toObjectList(
569               /** @type {!Array<!jspb.Message>} */ (value),
570               fieldInfo.toObjectFn, opt_includeInstance);
571         } else {
572           obj[name] = fieldInfo.toObjectFn(
573               opt_includeInstance, /** @type {!jspb.Message} */ (value));
574         }
575       }
576     }
577   }
578 };
579
580
581 /**
582  * Writes a proto's extension data to a binary-format output stream.
583  * @param {!jspb.Message} proto The proto whose extensions to convert.
584  * @param {*} writer The binary-format writer to write to.
585  * @param {!Object} extensions The proto class' registered extensions.
586  * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo) : *} getExtensionFn The proto
587  *     class' getExtension function. Passed for effective dead code removal.
588  */
589 jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
590     getExtensionFn) {
591   for (var fieldNumber in extensions) {
592     var binaryFieldInfo = extensions[fieldNumber];
593     var fieldInfo = binaryFieldInfo.fieldInfo;
594
595     // The old codegen doesn't add the extra fields to ExtensionFieldInfo, so we
596     // need to gracefully error-out here rather than produce a null dereference
597     // below.
598     if (!binaryFieldInfo.binaryWriterFn) {
599       throw new Error('Message extension present that was generated ' +
600                       'without binary serialization support');
601     }
602     var value = getExtensionFn.call(proto, fieldInfo);
603     if (value != null) {
604       if (fieldInfo.isMessageType()) {
605         // If the message type of the extension was generated without binary
606         // support, there may not be a binary message serializer function, and
607         // we can't know when we codegen the extending message that the extended
608         // message may require binary support, so we can *only* catch this error
609         // here, at runtime (and this decoupled codegen is the whole point of
610         // extensions!).
611         if (binaryFieldInfo.binaryMessageSerializeFn) {
612           binaryFieldInfo.binaryWriterFn.call(writer, fieldInfo.fieldIndex,
613               value, binaryFieldInfo.binaryMessageSerializeFn);
614         } else {
615           throw new Error('Message extension present holding submessage ' +
616                           'without binary support enabled, and message is ' +
617                           'being serialized to binary format');
618         }
619       } else {
620         binaryFieldInfo.binaryWriterFn.call(
621             writer, fieldInfo.fieldIndex, value);
622       }
623     }
624   }
625 };
626
627
628 /**
629  * Reads an extension field from the given reader and, if a valid extension,
630  * sets the extension value.
631  * @param {!jspb.Message} msg A jspb proto.
632  * @param {!jspb.BinaryReader} reader
633  * @param {!Object} extensions The extensions object.
634  * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo)} getExtensionFn
635  * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo, ?)} setExtensionFn
636  */
637 jspb.Message.readBinaryExtension = function(msg, reader, extensions,
638     getExtensionFn, setExtensionFn) {
639   var binaryFieldInfo = extensions[reader.getFieldNumber()];
640   if (!binaryFieldInfo) {
641     reader.skipField();
642     return;
643   }
644   var fieldInfo = binaryFieldInfo.fieldInfo;
645   if (!binaryFieldInfo.binaryReaderFn) {
646     throw new Error('Deserializing extension whose generated code does not ' +
647                     'support binary format');
648   }
649
650   var value;
651   if (fieldInfo.isMessageType()) {
652     value = new fieldInfo.ctor();
653     binaryFieldInfo.binaryReaderFn.call(
654         reader, value, binaryFieldInfo.binaryMessageDeserializeFn);
655   } else {
656     // All other types.
657     value = binaryFieldInfo.binaryReaderFn.call(reader);
658   }
659
660   if (fieldInfo.isRepeated && !binaryFieldInfo.isPacked) {
661     var currentList = getExtensionFn.call(msg, fieldInfo);
662     if (!currentList) {
663       setExtensionFn.call(msg, fieldInfo, [value]);
664     } else {
665       currentList.push(value);
666     }
667   } else {
668     setExtensionFn.call(msg, fieldInfo, value);
669   }
670 };
671
672
673 /**
674  * Gets the value of a non-extension field.
675  * @param {!jspb.Message} msg A jspb proto.
676  * @param {number} fieldNumber The field number.
677  * @return {string|number|boolean|Uint8Array|Array|null|undefined}
678  * The field's value.
679  * @protected
680  */
681 jspb.Message.getField = function(msg, fieldNumber) {
682   if (fieldNumber < msg.pivot_) {
683     var index = jspb.Message.getIndex_(msg, fieldNumber);
684     var val = msg.array[index];
685     if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
686       return msg.array[index] = [];
687     }
688     return val;
689   } else {
690     if (!msg.extensionObject_) {
691       return undefined;
692     }
693     var val = msg.extensionObject_[fieldNumber];
694     if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
695       return msg.extensionObject_[fieldNumber] = [];
696     }
697     return val;
698   }
699 };
700
701
702 /**
703  * Gets the value of a non-extension repeated field.
704  * @param {!jspb.Message} msg A jspb proto.
705  * @param {number} fieldNumber The field number.
706  * @return {!Array}
707  * The field's value.
708  * @protected
709  */
710 jspb.Message.getRepeatedField = function(msg, fieldNumber) {
711   return /** @type {!Array} */ (jspb.Message.getField(msg, fieldNumber));
712 };
713
714
715 /**
716  * Gets the value of an optional float or double field.
717  * @param {!jspb.Message} msg A jspb proto.
718  * @param {number} fieldNumber The field number.
719  * @return {?number|undefined} The field's value.
720  * @protected
721  */
722 jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
723   var value = jspb.Message.getField(msg, fieldNumber);
724   // Converts "NaN", "Infinity" and "-Infinity" to their corresponding numbers.
725   return value == null ? value : +value;
726 };
727
728
729 /**
730  * Gets the value of an optional boolean field.
731  * @param {!jspb.Message} msg A jspb proto.
732  * @param {number} fieldNumber The field number.
733  * @return {?boolean|undefined} The field's value.
734  * @protected
735  */
736 jspb.Message.getBooleanField = function(msg, fieldNumber) {
737   var value = jspb.Message.getField(msg, fieldNumber);
738   // TODO(b/122673075): always return null when the value is null-ish.
739   return value == null ? (value) : !!value;
740 };
741
742
743 /**
744  * Gets the value of a repeated float or double field.
745  * @param {!jspb.Message} msg A jspb proto.
746  * @param {number} fieldNumber The field number.
747  * @return {!Array<number>} The field's value.
748  * @protected
749  */
750 jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
751   var values = jspb.Message.getRepeatedField(msg, fieldNumber);
752   if (!msg.convertedPrimitiveFields_) {
753     msg.convertedPrimitiveFields_ = {};
754   }
755   if (!msg.convertedPrimitiveFields_[fieldNumber]) {
756     for (var i = 0; i < values.length; i++) {
757       // Converts "NaN", "Infinity" and "-Infinity" to their corresponding
758       // numbers.
759       values[i] = +values[i];
760     }
761     msg.convertedPrimitiveFields_[fieldNumber] = true;
762   }
763   return /** @type {!Array<number>} */ (values);
764 };
765
766 /**
767  * Gets the value of a repeated boolean field.
768  * @param {!jspb.Message} msg A jspb proto.
769  * @param {number} fieldNumber The field number.
770  * @return {!Array<boolean>} The field's value.
771  * @protected
772  */
773 jspb.Message.getRepeatedBooleanField = function(msg, fieldNumber) {
774   var values = jspb.Message.getRepeatedField(msg, fieldNumber);
775   if (!msg.convertedPrimitiveFields_) {
776     msg.convertedPrimitiveFields_ = {};
777   }
778   if (!msg.convertedPrimitiveFields_[fieldNumber]) {
779     for (var i = 0; i < values.length; i++) {
780       // Converts 0 and 1 to their corresponding booleans.
781       values[i] = !!values[i];
782     }
783     msg.convertedPrimitiveFields_[fieldNumber] = true;
784   }
785   return /** @type {!Array<boolean>} */ (values);
786 };
787
788
789 /**
790  * Coerce a 'bytes' field to a base 64 string.
791  * @param {string|Uint8Array|null} value
792  * @return {?string} The field's coerced value.
793  */
794 jspb.Message.bytesAsB64 = function(value) {
795   if (value == null || goog.isString(value)) {
796     return value;
797   }
798   if (jspb.Message.SUPPORTS_UINT8ARRAY_ && value instanceof Uint8Array) {
799     return goog.crypt.base64.encodeByteArray(value);
800   }
801   goog.asserts.fail('Cannot coerce to b64 string: ' + goog.typeOf(value));
802   return null;
803 };
804
805
806 /**
807  * Coerce a 'bytes' field to a Uint8Array byte buffer.
808  * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
809  * Mini. @see http://caniuse.com/Uint8Array
810  * @param {string|Uint8Array|null} value
811  * @return {?Uint8Array} The field's coerced value.
812  */
813 jspb.Message.bytesAsU8 = function(value) {
814   if (value == null || value instanceof Uint8Array) {
815     return value;
816   }
817   if (goog.isString(value)) {
818     return goog.crypt.base64.decodeStringToUint8Array(value);
819   }
820   goog.asserts.fail('Cannot coerce to Uint8Array: ' + goog.typeOf(value));
821   return null;
822 };
823
824
825 /**
826  * Coerce a repeated 'bytes' field to an array of base 64 strings.
827  * Note: the returned array should be treated as immutable.
828  * @param {!Array<string>|!Array<!Uint8Array>} value
829  * @return {!Array<string?>} The field's coerced value.
830  */
831 jspb.Message.bytesListAsB64 = function(value) {
832   jspb.Message.assertConsistentTypes_(value);
833   if (!value.length || goog.isString(value[0])) {
834     return /** @type {!Array<string>} */ (value);
835   }
836   return goog.array.map(value, jspb.Message.bytesAsB64);
837 };
838
839
840 /**
841  * Coerce a repeated 'bytes' field to an array of Uint8Array byte buffers.
842  * Note: the returned array should be treated as immutable.
843  * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
844  * Mini. @see http://caniuse.com/Uint8Array
845  * @param {!Array<string>|!Array<!Uint8Array>} value
846  * @return {!Array<Uint8Array?>} The field's coerced value.
847  */
848 jspb.Message.bytesListAsU8 = function(value) {
849   jspb.Message.assertConsistentTypes_(value);
850   if (!value.length || value[0] instanceof Uint8Array) {
851     return /** @type {!Array<!Uint8Array>} */ (value);
852   }
853   return goog.array.map(value, jspb.Message.bytesAsU8);
854 };
855
856
857 /**
858  * Asserts that all elements of an array are of the same type.
859  * @param {Array?} array The array to test.
860  * @private
861  */
862 jspb.Message.assertConsistentTypes_ = function(array) {
863   if (goog.DEBUG && array && array.length > 1) {
864     var expected = goog.typeOf(array[0]);
865     goog.array.forEach(array, function(e) {
866       if (goog.typeOf(e) != expected) {
867         goog.asserts.fail('Inconsistent type in JSPB repeated field array. ' +
868             'Got ' + goog.typeOf(e) + ' expected ' + expected);
869       }
870     });
871   }
872 };
873
874
875 /**
876  * Gets the value of a non-extension primitive field, with proto3 (non-nullable
877  * primitives) semantics. Returns `defaultValue` if the field is not otherwise
878  * set.
879  * @template T
880  * @param {!jspb.Message} msg A jspb proto.
881  * @param {number} fieldNumber The field number.
882  * @param {T} defaultValue The default value.
883  * @return {T} The field's value.
884  * @protected
885  */
886 jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
887   var value = jspb.Message.getField(msg, fieldNumber);
888   if (value == null) {
889     return defaultValue;
890   } else {
891     return value;
892   }
893 };
894
895
896 /**
897  * Gets the value of a boolean field, with proto3 (non-nullable primitives)
898  * semantics. Returns `defaultValue` if the field is not otherwise set.
899  * @template T
900  * @param {!jspb.Message} msg A jspb proto.
901  * @param {number} fieldNumber The field number.
902  * @param {boolean} defaultValue The default value.
903  * @return {boolean} The field's value.
904  * @protected
905  */
906 jspb.Message.getBooleanFieldWithDefault = function(
907     msg, fieldNumber, defaultValue) {
908   var value = jspb.Message.getBooleanField(msg, fieldNumber);
909   if (value == null) {
910     return defaultValue;
911   } else {
912     return value;
913   }
914 };
915
916
917 /**
918  * Gets the value of a floating point field, with proto3 (non-nullable
919  * primitives) semantics. Returns `defaultValue` if the field is not otherwise
920  * set.
921  * @template T
922  * @param {!jspb.Message} msg A jspb proto.
923  * @param {number} fieldNumber The field number.
924  * @param {number} defaultValue The default value.
925  * @return {number} The field's value.
926  * @protected
927  */
928 jspb.Message.getFloatingPointFieldWithDefault = function(
929     msg, fieldNumber, defaultValue) {
930   var value = jspb.Message.getOptionalFloatingPointField(msg, fieldNumber);
931   if (value == null) {
932     return defaultValue;
933   } else {
934     return value;
935   }
936 };
937
938
939 /**
940  * Alias for getFieldWithDefault used by older generated code.
941  * @template T
942  * @param {!jspb.Message} msg A jspb proto.
943  * @param {number} fieldNumber The field number.
944  * @param {T} defaultValue The default value.
945  * @return {T} The field's value.
946  * @protected
947  */
948 jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
949
950
951 /**
952  * Gets the value of a map field, lazily creating the map container if
953  * necessary.
954  *
955  * This should only be called from generated code, because it requires knowledge
956  * of serialization/parsing callbacks (which are required by the map at
957  * construction time, and the map may be constructed here).
958  *
959  * @template K, V
960  * @param {!jspb.Message} msg
961  * @param {number} fieldNumber
962  * @param {boolean|undefined} noLazyCreate
963  * @param {?=} opt_valueCtor
964  * @return {!jspb.Map<K, V>|undefined}
965  * @protected
966  */
967 jspb.Message.getMapField = function(msg, fieldNumber, noLazyCreate,
968     opt_valueCtor) {
969   if (!msg.wrappers_) {
970     msg.wrappers_ = {};
971   }
972   // If we already have a map in the map wrappers, return that.
973   if (fieldNumber in msg.wrappers_) {
974     return msg.wrappers_[fieldNumber];
975   } else if (noLazyCreate) {
976     return undefined;
977   } else {
978     // Wrap the underlying elements array with a Map.
979     var arr = jspb.Message.getField(msg, fieldNumber);
980     if (!arr) {
981       arr = [];
982       jspb.Message.setField(msg, fieldNumber, arr);
983     }
984     return msg.wrappers_[fieldNumber] =
985         new jspb.Map(
986             /** @type {!Array<!Array<!Object>>} */ (arr), opt_valueCtor);
987   }
988 };
989
990
991 /**
992  * Sets the value of a non-extension field.
993  * @param {!jspb.Message} msg A jspb proto.
994  * @param {number} fieldNumber The field number.
995  * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
996  * @protected
997  */
998 jspb.Message.setField = function(msg, fieldNumber, value) {
999   if (fieldNumber < msg.pivot_) {
1000     msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
1001   } else {
1002     jspb.Message.maybeInitEmptyExtensionObject_(msg);
1003     msg.extensionObject_[fieldNumber] = value;
1004   }
1005 };
1006
1007
1008 /**
1009  * Sets the value of a non-extension integer field of a proto3
1010  * @param {!jspb.Message} msg A jspb proto.
1011  * @param {number} fieldNumber The field number.
1012  * @param {number} value New value
1013  * @protected
1014  */
1015 jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
1016   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1017 };
1018
1019
1020 /**
1021  * Sets the value of a non-extension floating point field of a proto3
1022  * @param {!jspb.Message} msg A jspb proto.
1023  * @param {number} fieldNumber The field number.
1024  * @param {number} value New value
1025  * @protected
1026  */
1027 jspb.Message.setProto3FloatField = function(msg, fieldNumber, value) {
1028   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0.0);
1029 };
1030
1031
1032 /**
1033  * Sets the value of a non-extension boolean field of a proto3
1034  * @param {!jspb.Message} msg A jspb proto.
1035  * @param {number} fieldNumber The field number.
1036  * @param {boolean} value New value
1037  * @protected
1038  */
1039 jspb.Message.setProto3BooleanField = function(msg, fieldNumber, value) {
1040   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, false);
1041 };
1042
1043
1044 /**
1045  * Sets the value of a non-extension String field of a proto3
1046  * @param {!jspb.Message} msg A jspb proto.
1047  * @param {number} fieldNumber The field number.
1048  * @param {string} value New value
1049  * @protected
1050  */
1051 jspb.Message.setProto3StringField = function(msg, fieldNumber, value) {
1052   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
1053 };
1054
1055
1056 /**
1057  * Sets the value of a non-extension Bytes field of a proto3
1058  * @param {!jspb.Message} msg A jspb proto.
1059  * @param {number} fieldNumber The field number.
1060  * @param {!Uint8Array|string} value New value
1061  * @protected
1062  */
1063 jspb.Message.setProto3BytesField = function(msg, fieldNumber, value) {
1064   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
1065 };
1066
1067
1068 /**
1069  * Sets the value of a non-extension enum field of a proto3
1070  * @param {!jspb.Message} msg A jspb proto.
1071  * @param {number} fieldNumber The field number.
1072  * @param {number} value New value
1073  * @protected
1074  */
1075 jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
1076   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1077 };
1078
1079
1080 /**
1081  * Sets the value of a non-extension int field of a proto3 that has jstype set
1082  * to String.
1083  * @param {!jspb.Message} msg A jspb proto.
1084  * @param {number} fieldNumber The field number.
1085  * @param {string} value New value
1086  * @protected
1087  */
1088 jspb.Message.setProto3StringIntField = function(msg, fieldNumber, value) {
1089   jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "0");
1090 };
1091
1092 /**
1093  * Sets the value of a non-extension primitive field, with proto3 (non-nullable
1094  * primitives) semantics of ignoring values that are equal to the type's
1095  * default.
1096  * @param {!jspb.Message} msg A jspb proto.
1097  * @param {number} fieldNumber The field number.
1098  * @param {!Uint8Array|string|number|boolean|undefined} value New value
1099  * @param {!Uint8Array|string|number|boolean} defaultValue The default value.
1100  * @private
1101  */
1102 jspb.Message.setFieldIgnoringDefault_ = function(
1103     msg, fieldNumber, value, defaultValue) {
1104   if (value !== defaultValue) {
1105     jspb.Message.setField(msg, fieldNumber, value);
1106   } else {
1107     msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
1108   }
1109 };
1110
1111
1112 /**
1113  * Adds a value to a repeated, primitive field.
1114  * @param {!jspb.Message} msg A jspb proto.
1115  * @param {number} fieldNumber The field number.
1116  * @param {string|number|boolean|!Uint8Array} value New value
1117  * @param {number=} opt_index Index where to put new value.
1118  * @protected
1119  */
1120 jspb.Message.addToRepeatedField = function(msg, fieldNumber, value, opt_index) {
1121   var arr = jspb.Message.getRepeatedField(msg, fieldNumber);
1122   if (opt_index != undefined) {
1123     arr.splice(opt_index, 0, value);
1124   } else {
1125     arr.push(value);
1126   }
1127 };
1128
1129
1130 /**
1131  * Sets the value of a field in a oneof union and clears all other fields in
1132  * the union.
1133  * @param {!jspb.Message} msg A jspb proto.
1134  * @param {number} fieldNumber The field number.
1135  * @param {!Array<number>} oneof The fields belonging to the union.
1136  * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
1137  * @protected
1138  */
1139 jspb.Message.setOneofField = function(msg, fieldNumber, oneof, value) {
1140   var currentCase = jspb.Message.computeOneofCase(msg, oneof);
1141   if (currentCase && currentCase !== fieldNumber && value !== undefined) {
1142     if (msg.wrappers_ && currentCase in msg.wrappers_) {
1143       msg.wrappers_[currentCase] = undefined;
1144     }
1145     jspb.Message.setField(msg, currentCase, undefined);
1146   }
1147   jspb.Message.setField(msg, fieldNumber, value);
1148 };
1149
1150
1151 /**
1152  * Computes the selection in a oneof group for the given message, ensuring
1153  * only one field is set in the process.
1154  *
1155  * According to the protobuf language guide (
1156  * https://developers.google.com/protocol-buffers/docs/proto#oneof), "if the
1157  * parser encounters multiple members of the same oneof on the wire, only the
1158  * last member seen is used in the parsed message." Since JSPB serializes
1159  * messages to a JSON array, the "last member seen" will always be the field
1160  * with the greatest field number (directly corresponding to the greatest
1161  * array index).
1162  *
1163  * @param {!jspb.Message} msg A jspb proto.
1164  * @param {!Array<number>} oneof The field numbers belonging to the union.
1165  * @return {number} The field number currently set in the union, or 0 if none.
1166  * @protected
1167  */
1168 jspb.Message.computeOneofCase = function(msg, oneof) {
1169   var oneofField;
1170   var oneofValue;
1171
1172   for (var i = 0; i < oneof.length; i++) {
1173     var fieldNumber = oneof[i];
1174     var value = jspb.Message.getField(msg, fieldNumber);
1175     if (value != null) {
1176       oneofField = fieldNumber;
1177       oneofValue = value;
1178       jspb.Message.setField(msg, fieldNumber, undefined);
1179     }
1180   }
1181
1182   if (oneofField) {
1183     // NB: We know the value is unique, so we can call jspb.Message.setField
1184     // directly instead of jpsb.Message.setOneofField. Also, setOneofField
1185     // calls this function.
1186     jspb.Message.setField(msg, oneofField, oneofValue);
1187     return oneofField;
1188   }
1189
1190   return 0;
1191 };
1192
1193
1194 /**
1195  * Gets and wraps a proto field on access.
1196  * @param {!jspb.Message} msg A jspb proto.
1197  * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1198  * @param {number} fieldNumber The field number.
1199  * @param {number=} opt_required True (1) if this is a required field.
1200  * @return {jspb.Message} The field as a jspb proto.
1201  * @protected
1202  */
1203 jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
1204   // TODO(mwr): Consider copying data and/or arrays.
1205   if (!msg.wrappers_) {
1206     msg.wrappers_ = {};
1207   }
1208   if (!msg.wrappers_[fieldNumber]) {
1209     var data = /** @type {Array} */ (jspb.Message.getField(msg, fieldNumber));
1210     if (opt_required || data) {
1211       // TODO(mwr): Remove existence test for always valid default protos.
1212       msg.wrappers_[fieldNumber] = new ctor(data);
1213     }
1214   }
1215   return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
1216 };
1217
1218
1219 /**
1220  * Gets and wraps a repeated proto field on access.
1221  * @param {!jspb.Message} msg A jspb proto.
1222  * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1223  * @param {number} fieldNumber The field number.
1224  * @return {!Array<!jspb.Message>} The repeated field as an array of protos.
1225  * @protected
1226  */
1227 jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
1228   jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1229   var val = msg.wrappers_[fieldNumber];
1230   if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
1231     val = msg.wrappers_[fieldNumber] = [];
1232   }
1233   return /** @type {!Array<!jspb.Message>} */ (val);
1234 };
1235
1236
1237 /**
1238  * Wraps underlying array into proto message representation if it wasn't done
1239  * before.
1240  * @param {!jspb.Message} msg A jspb proto.
1241  * @param {function(new:jspb.Message, ?Array)} ctor Constructor for the field.
1242  * @param {number} fieldNumber The field number.
1243  * @private
1244  */
1245 jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
1246   if (!msg.wrappers_) {
1247     msg.wrappers_ = {};
1248   }
1249   if (!msg.wrappers_[fieldNumber]) {
1250     var data = jspb.Message.getRepeatedField(msg, fieldNumber);
1251     for (var wrappers = [], i = 0; i < data.length; i++) {
1252       wrappers[i] = new ctor(data[i]);
1253     }
1254     msg.wrappers_[fieldNumber] = wrappers;
1255   }
1256 };
1257
1258
1259 /**
1260  * Sets a proto field and syncs it to the backing array.
1261  * @param {!jspb.Message} msg A jspb proto.
1262  * @param {number} fieldNumber The field number.
1263  * @param {?jspb.Message|?jspb.Map|undefined} value A new value for this proto
1264  * field.
1265  * @protected
1266  */
1267 jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
1268   if (!msg.wrappers_) {
1269     msg.wrappers_ = {};
1270   }
1271   var data = value ? value.toArray() : value;
1272   msg.wrappers_[fieldNumber] = value;
1273   jspb.Message.setField(msg, fieldNumber, data);
1274 };
1275
1276
1277 /**
1278  * Sets a proto field in a oneof union and syncs it to the backing array.
1279  * @param {!jspb.Message} msg A jspb proto.
1280  * @param {number} fieldNumber The field number.
1281  * @param {!Array<number>} oneof The fields belonging to the union.
1282  * @param {jspb.Message|undefined} value A new value for this proto field.
1283  * @protected
1284  */
1285 jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
1286   if (!msg.wrappers_) {
1287     msg.wrappers_ = {};
1288   }
1289   var data = value ? value.toArray() : value;
1290   msg.wrappers_[fieldNumber] = value;
1291   jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
1292 };
1293
1294
1295 /**
1296  * Sets a repeated proto field and syncs it to the backing array.
1297  * @param {!jspb.Message} msg A jspb proto.
1298  * @param {number} fieldNumber The field number.
1299  * @param {Array<!jspb.Message>|undefined} value An array of protos.
1300  * @protected
1301  */
1302 jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
1303   if (!msg.wrappers_) {
1304     msg.wrappers_ = {};
1305   }
1306   value = value || [];
1307   for (var data = [], i = 0; i < value.length; i++) {
1308     data[i] = value[i].toArray();
1309   }
1310   msg.wrappers_[fieldNumber] = value;
1311   jspb.Message.setField(msg, fieldNumber, data);
1312 };
1313
1314
1315 /**
1316  * Add a message to a repeated proto field.
1317  * @param {!jspb.Message} msg A jspb proto.
1318  * @param {number} fieldNumber The field number.
1319  * @param {T_CHILD|undefined} value Proto that will be added to the
1320  *     repeated field.
1321  * @param {function(new:T_CHILD, ?Array=)} ctor The constructor of the
1322  *     message type.
1323  * @param {number|undefined} index Index at which to insert the value.
1324  * @return {T_CHILD_NOT_UNDEFINED} proto that was inserted to the repeated field
1325  * @template MessageType
1326  * Use go/closure-ttl to declare a non-undefined version of T_CHILD. Replace the
1327  * undefined in blah|undefined with none. This is necessary because the compiler
1328  * will infer T_CHILD to be |undefined.
1329  * @template T_CHILD
1330  * @template T_CHILD_NOT_UNDEFINED :=
1331  *     cond(isUnknown(T_CHILD), unknown(),
1332  *       mapunion(T_CHILD, (X) =>
1333  *         cond(eq(X, 'undefined'), none(), X)))
1334  * =:
1335  * @protected
1336  */
1337 jspb.Message.addToRepeatedWrapperField = function(
1338     msg, fieldNumber, value, ctor, index) {
1339   jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1340   var wrapperArray = msg.wrappers_[fieldNumber];
1341   if (!wrapperArray) {
1342     wrapperArray = msg.wrappers_[fieldNumber] = [];
1343   }
1344   var insertedValue = value ? value : new ctor();
1345   var array = jspb.Message.getRepeatedField(msg, fieldNumber);
1346   if (index != undefined) {
1347     wrapperArray.splice(index, 0, insertedValue);
1348     array.splice(index, 0, insertedValue.toArray());
1349   } else {
1350     wrapperArray.push(insertedValue);
1351     array.push(insertedValue.toArray());
1352   }
1353   return insertedValue;
1354 };
1355
1356
1357 /**
1358  * Converts a JsPb repeated message field into a map. The map will contain
1359  * protos unless an optional toObject function is given, in which case it will
1360  * contain objects suitable for Soy rendering.
1361  * @param {!Array<T>} field The repeated message field to be
1362  *     converted.
1363  * @param {function() : string?} mapKeyGetterFn The function to get the key of
1364  *     the map.
1365  * @param {?function(boolean=): Object|
1366  *     function((boolean|undefined),T): Object} opt_toObjectFn The
1367  *     toObject function for this field. We need to pass this for effective
1368  *     dead code removal.
1369  * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
1370  *     for transitional soy proto support: http://goto/soy-param-migration
1371  * @return {!Object<string, Object>} A map of proto or Soy objects.
1372  * @template T
1373  */
1374 jspb.Message.toMap = function(
1375     field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
1376   var result = {};
1377   for (var i = 0; i < field.length; i++) {
1378     result[mapKeyGetterFn.call(field[i])] = opt_toObjectFn ?
1379         opt_toObjectFn.call(field[i], opt_includeInstance,
1380             /** @type {!jspb.Message} */ (field[i])) : field[i];
1381   }
1382   return result;
1383 };
1384
1385
1386 /**
1387  * Syncs all map fields' contents back to their underlying arrays.
1388  * @private
1389  */
1390 jspb.Message.prototype.syncMapFields_ = function() {
1391   // This iterates over submessage, map, and repeated fields, which is intended.
1392   // Submessages can contain maps which also need to be synced.
1393   //
1394   // There is a lot of opportunity for optimization here.  For example we could
1395   // statically determine that some messages have no submessages with maps and
1396   // optimize this method away for those just by generating one extra static
1397   // boolean per message type.
1398   if (this.wrappers_) {
1399     for (var fieldNumber in this.wrappers_) {
1400       var val = this.wrappers_[fieldNumber];
1401       if (goog.isArray(val)) {
1402         for (var i = 0; i < val.length; i++) {
1403           if (val[i]) {
1404             val[i].toArray();
1405           }
1406         }
1407       } else {
1408         // Works for submessages and maps.
1409         if (val) {
1410           val.toArray();
1411         }
1412       }
1413     }
1414   }
1415 };
1416
1417
1418 /**
1419  * Returns the internal array of this proto.
1420  * <p>Note: If you use this array to construct a second proto, the content
1421  * would then be partially shared between the two protos.
1422  * @return {!Array} The proto represented as an array.
1423  */
1424 jspb.Message.prototype.toArray = function() {
1425   this.syncMapFields_();
1426   return this.array;
1427 };
1428
1429
1430
1431 if (jspb.Message.GENERATE_TO_STRING) {
1432
1433 /**
1434  * Creates a string representation of the internal data array of this proto.
1435  * <p>NOTE: This string is *not* suitable for use in server requests.
1436  * @return {string} A string representation of this proto.
1437  * @override
1438  */
1439 jspb.Message.prototype.toString = function() {
1440   this.syncMapFields_();
1441   return this.array.toString();
1442 };
1443
1444 }
1445
1446 /**
1447  * Gets the value of the extension field from the extended object.
1448  * @param {jspb.ExtensionFieldInfo<T>} fieldInfo Specifies the field to get.
1449  * @return {T} The value of the field.
1450  * @template T
1451  */
1452 jspb.Message.prototype.getExtension = function(fieldInfo) {
1453   if (!this.extensionObject_) {
1454     return undefined;
1455   }
1456   if (!this.wrappers_) {
1457     this.wrappers_ = {};
1458   }
1459   var fieldNumber = fieldInfo.fieldIndex;
1460   if (fieldInfo.isRepeated) {
1461     if (fieldInfo.isMessageType()) {
1462       if (!this.wrappers_[fieldNumber]) {
1463         this.wrappers_[fieldNumber] =
1464             goog.array.map(this.extensionObject_[fieldNumber] || [],
1465                 function(arr) {
1466                   return new fieldInfo.ctor(arr);
1467                 });
1468       }
1469       return this.wrappers_[fieldNumber];
1470     } else {
1471       return this.extensionObject_[fieldNumber];
1472     }
1473   } else {
1474     if (fieldInfo.isMessageType()) {
1475       if (!this.wrappers_[fieldNumber] && this.extensionObject_[fieldNumber]) {
1476         this.wrappers_[fieldNumber] = new fieldInfo.ctor(
1477             /** @type {Array|undefined} */ (
1478                 this.extensionObject_[fieldNumber]));
1479       }
1480       return this.wrappers_[fieldNumber];
1481     } else {
1482       return this.extensionObject_[fieldNumber];
1483     }
1484   }
1485 };
1486
1487
1488 /**
1489  * Sets the value of the extension field in the extended object.
1490  * @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
1491  * @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
1492  *     to set.
1493  * @return {THIS} For chaining
1494  * @this {THIS}
1495  * @template THIS
1496  */
1497 jspb.Message.prototype.setExtension = function(fieldInfo, value) {
1498   // Cast self, since the inferred THIS is unknown inside the function body.
1499   // https://github.com/google/closure-compiler/issues/1411#issuecomment-232442220
1500   var self = /** @type {!jspb.Message} */ (this);
1501   if (!self.wrappers_) {
1502     self.wrappers_ = {};
1503   }
1504   jspb.Message.maybeInitEmptyExtensionObject_(self);
1505   var fieldNumber = fieldInfo.fieldIndex;
1506   if (fieldInfo.isRepeated) {
1507     value = value || [];
1508     if (fieldInfo.isMessageType()) {
1509       self.wrappers_[fieldNumber] = value;
1510       self.extensionObject_[fieldNumber] = goog.array.map(
1511           /** @type {!Array<!jspb.Message>} */ (value), function(msg) {
1512         return msg.toArray();
1513       });
1514     } else {
1515       self.extensionObject_[fieldNumber] = value;
1516     }
1517   } else {
1518     if (fieldInfo.isMessageType()) {
1519       self.wrappers_[fieldNumber] = value;
1520       self.extensionObject_[fieldNumber] =
1521           value ? /** @type {!jspb.Message} */ (value).toArray() : value;
1522     } else {
1523       self.extensionObject_[fieldNumber] = value;
1524     }
1525   }
1526   return self;
1527 };
1528
1529
1530 /**
1531  * Creates a difference object between two messages.
1532  *
1533  * The result will contain the top-level fields of m2 that differ from those of
1534  * m1 at any level of nesting. No data is cloned, the result object will
1535  * share its top-level elements with m2 (but not with m1).
1536  *
1537  * Note that repeated fields should not have null/undefined elements, but if
1538  * they do, this operation will treat repeated fields of different length as
1539  * the same if the only difference between them is due to trailing
1540  * null/undefined values.
1541  *
1542  * @param {!jspb.Message} m1 The first message object.
1543  * @param {!jspb.Message} m2 The second message object.
1544  * @return {!jspb.Message} The difference returned as a proto message.
1545  *     Note that the returned message may be missing required fields. This is
1546  *     currently tolerated in Js, but would cause an error if you tried to
1547  *     send such a proto to the server. You can access the raw difference
1548  *     array with result.toArray().
1549  * @throws {Error} If the messages are responses with different types.
1550  */
1551 jspb.Message.difference = function(m1, m2) {
1552   if (!(m1 instanceof m2.constructor)) {
1553     throw new Error('Messages have different types.');
1554   }
1555   var arr1 = m1.toArray();
1556   var arr2 = m2.toArray();
1557   var res = [];
1558   var start = 0;
1559   var length = arr1.length > arr2.length ? arr1.length : arr2.length;
1560   if (m1.getJsPbMessageId()) {
1561     res[0] = m1.getJsPbMessageId();
1562     start = 1;
1563   }
1564   for (var i = start; i < length; i++) {
1565     if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
1566       res[i] = arr2[i];
1567     }
1568   }
1569   return new m1.constructor(res);
1570 };
1571
1572
1573 /**
1574  * Tests whether two messages are equal.
1575  * @param {jspb.Message|undefined} m1 The first message object.
1576  * @param {jspb.Message|undefined} m2 The second message object.
1577  * @return {boolean} true if both messages are null/undefined, or if both are
1578  *     of the same type and have the same field values.
1579  */
1580 jspb.Message.equals = function(m1, m2) {
1581   return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
1582       jspb.Message.compareFields(m1.toArray(), m2.toArray()));
1583 };
1584
1585
1586 /**
1587  * Compares two message extension fields recursively.
1588  * @param {!Object} extension1 The first field.
1589  * @param {!Object} extension2 The second field.
1590  * @return {boolean} true if the extensions are null/undefined, or otherwise
1591  *     equal.
1592  */
1593 jspb.Message.compareExtensions = function(extension1, extension2) {
1594   extension1 = extension1 || {};
1595   extension2 = extension2 || {};
1596
1597   var keys = {};
1598   for (var name in extension1) {
1599     keys[name] = 0;
1600   }
1601   for (var name in extension2) {
1602     keys[name] = 0;
1603   }
1604   for (name in keys) {
1605     if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
1606       return false;
1607     }
1608   }
1609   return true;
1610 };
1611
1612
1613 /**
1614  * Compares two message fields recursively.
1615  * @param {*} field1 The first field.
1616  * @param {*} field2 The second field.
1617  * @return {boolean} true if the fields are null/undefined, or otherwise equal.
1618  */
1619 jspb.Message.compareFields = function(field1, field2) {
1620   // If the fields are trivially equal, they're equal.
1621   if (field1 == field2) return true;
1622
1623   if (!goog.isObject(field1) || !goog.isObject(field2)) {
1624     // NaN != NaN so we cover this case.
1625     if ((goog.isNumber(field1) && isNaN(field1)) ||
1626         (goog.isNumber(field2) && isNaN(field2))) {
1627       // One of the fields might be a string 'NaN'.
1628       return String(field1) == String(field2);
1629     }
1630     // If the fields aren't trivially equal and one of them isn't an object,
1631     // they can't possibly be equal.
1632     return false;
1633   }
1634
1635   // We have two objects. If they're different types, they're not equal.
1636   field1 = /** @type {!Object} */(field1);
1637   field2 = /** @type {!Object} */(field2);
1638   if (field1.constructor != field2.constructor) return false;
1639
1640   // If both are Uint8Arrays, compare them element-by-element.
1641   if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
1642     var bytes1 = /** @type {!Uint8Array} */(field1);
1643     var bytes2 = /** @type {!Uint8Array} */(field2);
1644     if (bytes1.length != bytes2.length) return false;
1645     for (var i = 0; i < bytes1.length; i++) {
1646       if (bytes1[i] != bytes2[i]) return false;
1647     }
1648     return true;
1649   }
1650
1651   // If they're both Arrays, compare them element by element except for the
1652   // optional extension objects at the end, which we compare separately.
1653   if (field1.constructor === Array) {
1654     var typedField1 = /** @type {!Array<?>} */ (field1);
1655     var typedField2 = /** @type {!Array<?>} */ (field2);
1656     var extension1 = undefined;
1657     var extension2 = undefined;
1658
1659     var length = Math.max(typedField1.length, typedField2.length);
1660     for (var i = 0; i < length; i++) {
1661       var val1 = typedField1[i];
1662       var val2 = typedField2[i];
1663
1664       if (val1 && (val1.constructor == Object)) {
1665         goog.asserts.assert(extension1 === undefined);
1666         goog.asserts.assert(i === typedField1.length - 1);
1667         extension1 = val1;
1668         val1 = undefined;
1669       }
1670
1671       if (val2 && (val2.constructor == Object)) {
1672         goog.asserts.assert(extension2 === undefined);
1673         goog.asserts.assert(i === typedField2.length - 1);
1674         extension2 = val2;
1675         val2 = undefined;
1676       }
1677
1678       if (!jspb.Message.compareFields(val1, val2)) {
1679         return false;
1680       }
1681     }
1682
1683     if (extension1 || extension2) {
1684       extension1 = extension1 || {};
1685       extension2 = extension2 || {};
1686       return jspb.Message.compareExtensions(extension1, extension2);
1687     }
1688
1689     return true;
1690   }
1691
1692   // If they're both plain Objects (i.e. extensions), compare them as
1693   // extensions.
1694   if (field1.constructor === Object) {
1695     return jspb.Message.compareExtensions(field1, field2);
1696   }
1697
1698   throw new Error('Invalid type in JSPB array');
1699 };
1700
1701
1702 /**
1703  * Templated, type-safe cloneMessage definition.
1704  * @return {THIS}
1705  * @this {THIS}
1706  * @template THIS
1707  */
1708 jspb.Message.prototype.cloneMessage = function() {
1709   return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1710 };
1711
1712 /**
1713  * Alias clone to cloneMessage. goog.object.unsafeClone uses clone to
1714  * efficiently copy objects. Without this alias, copying jspb messages comes
1715  * with a large performance penalty.
1716  * @return {THIS}
1717  * @this {THIS}
1718  * @template THIS
1719  */
1720 jspb.Message.prototype.clone = function() {
1721   return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1722 };
1723
1724 /**
1725  * Static clone function. NOTE: A type-safe method called "cloneMessage"
1726  * exists
1727  * on each generated JsPb class. Do not call this function directly.
1728  * @param {!jspb.Message} msg A message to clone.
1729  * @return {!jspb.Message} A deep clone of the given message.
1730  */
1731 jspb.Message.clone = function(msg) {
1732   // Although we could include the wrappers, we leave them out here.
1733   return jspb.Message.cloneMessage(msg);
1734 };
1735
1736
1737 /**
1738  * @param {!jspb.Message} msg A message to clone.
1739  * @return {!jspb.Message} A deep clone of the given message.
1740  * @protected
1741  */
1742 jspb.Message.cloneMessage = function(msg) {
1743   // Although we could include the wrappers, we leave them out here.
1744   return new msg.constructor(jspb.Message.clone_(msg.toArray()));
1745 };
1746
1747
1748 /**
1749  * Takes 2 messages of the same type and copies the contents of the first
1750  * message into the second. After this the 2 messages will equals in terms of
1751  * value semantics but share no state. All data in the destination message will
1752  * be overridden.
1753  *
1754  * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
1755  * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
1756  *     as its contents.
1757  * @template MESSAGE
1758  */
1759 jspb.Message.copyInto = function(fromMessage, toMessage) {
1760   goog.asserts.assertInstanceof(fromMessage, jspb.Message);
1761   goog.asserts.assertInstanceof(toMessage, jspb.Message);
1762   goog.asserts.assert(fromMessage.constructor == toMessage.constructor,
1763       'Copy source and target message should have the same type.');
1764   var copyOfFrom = jspb.Message.clone(fromMessage);
1765
1766   var to = toMessage.toArray();
1767   var from = copyOfFrom.toArray();
1768
1769   // Empty destination in case it has more values at the end of the array.
1770   to.length = 0;
1771   // and then copy everything from the new to the existing message.
1772   for (var i = 0; i < from.length; i++) {
1773     to[i] = from[i];
1774   }
1775
1776   // This is either null or empty for a fresh copy.
1777   toMessage.wrappers_ = copyOfFrom.wrappers_;
1778   // Just a reference into the shared array.
1779   toMessage.extensionObject_ = copyOfFrom.extensionObject_;
1780 };
1781
1782
1783 /**
1784  * Helper for cloning an internal JsPb object.
1785  * @param {!Object} obj A JsPb object, eg, a field, to be cloned.
1786  * @return {!Object} A clone of the input object.
1787  * @private
1788  */
1789 jspb.Message.clone_ = function(obj) {
1790   var o;
1791   if (goog.isArray(obj)) {
1792     // Allocate array of correct size.
1793     var clonedArray = new Array(obj.length);
1794     // Use array iteration where possible because it is faster than for-in.
1795     for (var i = 0; i < obj.length; i++) {
1796       o = obj[i];
1797       if (o != null) {
1798         // NOTE:redundant null check existing for NTI compatibility.
1799         // see b/70515949
1800         clonedArray[i] = (typeof o == 'object') ?
1801             jspb.Message.clone_(goog.asserts.assert(o)) :
1802             o;
1803       }
1804     }
1805     return clonedArray;
1806   }
1807   if (jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array) {
1808     return new Uint8Array(obj);
1809   }
1810   var clone = {};
1811   for (var key in obj) {
1812     o = obj[key];
1813     if (o != null) {
1814       // NOTE:redundant null check existing for NTI compatibility.
1815       // see b/70515949
1816       clone[key] = (typeof o == 'object') ?
1817           jspb.Message.clone_(goog.asserts.assert(o)) :
1818           o;
1819     }
1820   }
1821   return clone;
1822 };
1823
1824
1825 /**
1826  * Registers a JsPb message type id with its constructor.
1827  * @param {string} id The id for this type of message.
1828  * @param {Function} constructor The message constructor.
1829  */
1830 jspb.Message.registerMessageType = function(id, constructor) {
1831   jspb.Message.registry_[id] = constructor;
1832   // This is needed so we can later access messageId directly on the contructor,
1833   // otherwise it is not available due to 'property collapsing' by the compiler.
1834   /**
1835    * @suppress {strictMissingProperties} messageId is not defined on Function
1836    */
1837   constructor.messageId = id;
1838 };
1839
1840
1841 /**
1842  * The registry of message ids to message constructors.
1843  * @private
1844  */
1845 jspb.Message.registry_ = {};
1846
1847
1848 /**
1849  * The extensions registered on MessageSet. This is a map of extension
1850  * field number to field info object. This should be considered as a
1851  * private API.
1852  *
1853  * This is similar to [jspb class name].extensions object for
1854  * non-MessageSet. We special case MessageSet so that we do not need
1855  * to goog.require MessageSet from classes that extends MessageSet.
1856  *
1857  * @type {!Object<number, jspb.ExtensionFieldInfo>}
1858  */
1859 jspb.Message.messageSetExtensions = {};
1860
1861 /**
1862  * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}
1863  */
1864 jspb.Message.messageSetExtensionsBinary = {};