1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
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
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.
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.
32 * @fileoverview Definition of jspb.Message.
34 * @author mwr@google.com (Mark Rawling)
37 goog.provide('jspb.ExtensionFieldBinaryInfo');
38 goog.provide('jspb.ExtensionFieldInfo');
39 goog.provide('jspb.Message');
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');
47 // Not needed in compilation units that have no protos with xids.
48 goog.forwardDeclare('xid.String');
53 * Stores information for a single extension field.
55 * For example, an extension field defined like so:
57 * extend BaseMessage {
58 * optional MyMessage my_field = 123;
61 * will result in an ExtensionFieldInfo object with these properties:
65 * fieldName: {my_field_renamed: 0},
66 * ctor: proto.example.MyMessage,
67 * toObjectFn: proto.example.MyMessage.toObject,
71 * We include `toObjectFn` to allow the JSCompiler to perform dead-code removal
72 * on unused toObject() methods.
74 * If an extension field is primitive, ctor and toObjectFn will be null.
75 * isRepeated should be 0 or 1.
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.
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
92 jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
95 this.fieldIndex = fieldNumber;
97 this.fieldName = fieldName;
101 this.toObjectFn = toObjectFn;
103 this.isRepeated = isRepeated;
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
119 jspb.ExtensionFieldBinaryInfo = function(fieldInfo, binaryReaderFn, binaryWriterFn,
120 opt_binaryMessageSerializeFn, opt_binaryMessageDeserializeFn, opt_isPacked) {
122 this.fieldInfo = fieldInfo;
124 this.binaryReaderFn = binaryReaderFn;
126 this.binaryWriterFn = binaryWriterFn;
128 this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
130 this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
132 this.isPacked = opt_isPacked;
136 * @return {boolean} Does this field represent a sub Message?
138 jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
144 * Base class for all JsPb messages.
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.
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.
163 jspb.Message = function() {
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
175 jspb.Message.GENERATE_TO_OBJECT =
176 goog.define('jspb.Message.GENERATE_TO_OBJECT', true);
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.
188 jspb.Message.GENERATE_FROM_OBJECT = goog.define(
189 'jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
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.
197 jspb.Message.GENERATE_TO_STRING =
198 goog.define('jspb.Message.GENERATE_TO_STRING', true);
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
206 jspb.Message.ASSUME_LOCAL_ARRAYS =
207 goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
210 // TODO(jakubvrana): Turn this off by default.
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.
217 jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS =
218 goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
222 * Does this JavaScript environment support Uint8Aray typed arrays?
226 jspb.Message.SUPPORTS_UINT8ARRAY_ = (typeof Uint8Array == 'function');
230 * The internal data array.
234 jspb.Message.prototype.array;
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.
244 jspb.Message.prototype.wrappers_;
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.
253 jspb.Message.prototype.extensionObject_;
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).
262 jspb.Message.prototype.pivot_;
266 * The JsPb message_id of this proto.
267 * @type {string|undefined} the message id or undefined if this message
271 jspb.Message.prototype.messageId_;
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}
280 jspb.Message.prototype.convertedPrimitiveFields_;
283 * Repeated fields numbers.
284 * @protected {?Array<number>|undefined}
286 jspb.Message.prototype.repeatedFields;
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.
293 * Available if {@link jspb.generate_xid} is added as a Message option to
295 * @const {!xid.String|undefined} The xid or undefined if message is
296 * annotated to generate the xid.
298 jspb.Message.prototype.messageXid;
303 * Returns the JsPb message_id of this proto.
304 * @return {string|undefined} the message id or undefined if this message
307 jspb.Message.prototype.getJsPbMessageId = function() {
308 return this.messageId_;
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.
319 jspb.Message.prototype.arrayIndexOffset_;
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.
330 jspb.Message.getIndex_ = function(msg, fieldNumber) {
331 return fieldNumber + msg.arrayIndexOffset_;
334 // This is only here to ensure we are not back sliding on ES6 requiements for
336 jspb.Message.hiddenES6Property_ = class {};
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.
346 jspb.Message.getFieldNumber_ = function(msg, index) {
347 return index - msg.arrayIndexOffset_;
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.
366 jspb.Message.initialize = function(
367 msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
368 msg.wrappers_ = null;
370 data = messageId ? [messageId] : [];
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;
378 jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
379 msg.convertedPrimitiveFields_ = {};
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;
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);
394 msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_;
396 jspb.Message.maybeInitEmptyExtensionObject_(msg);
397 msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] ||
398 jspb.Message.EMPTY_LIST_SENTINEL_;
403 if (opt_oneofFields && opt_oneofFields.length) {
404 // Compute the oneof case for each union. This ensures only one value is
406 for (var i = 0; i < opt_oneofFields.length; i++) {
407 jspb.Message.computeOneofCase(msg, opt_oneofFields[i]);
414 * Used to mark empty repeated fields. Serializes to null when serialized
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
419 * @private @const {!Object}
421 jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ?
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.
432 jspb.Message.isArray_ = function(o) {
433 return jspb.Message.ASSUME_LOCAL_ARRAYS ? o instanceof Array :
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.
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));
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.
462 * @param {!jspb.Message} msg The JsPb proto to modify.
463 * @param {number} suggestedPivot See description for initialize().
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).
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)
475 var msgLength = msg.array.length;
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;
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;
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;
506 * Creates an empty extensionObject_ if non exists.
507 * @param {!jspb.Message} msg The JsPb proto to modify.
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] = {};
519 * Converts a JsPb repeated message field into an object list.
520 * @param {!Array<T>} field The repeated message field to be
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
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.
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.
535 for (var i = 0; i < field.length; i++) {
536 result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]);
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
550 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
551 * for transitional soy proto support: http://goto/soy-param-migration
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);
559 for (var name in fieldInfo.fieldName) {
560 if (fieldInfo.fieldName.hasOwnProperty(name)) {
561 break; // the compiled field name
564 if (!fieldInfo.toObjectFn) {
567 if (fieldInfo.isRepeated) {
568 obj[name] = jspb.Message.toObjectList(
569 /** @type {!Array<!jspb.Message>} */ (value),
570 fieldInfo.toObjectFn, opt_includeInstance);
572 obj[name] = fieldInfo.toObjectFn(
573 opt_includeInstance, /** @type {!jspb.Message} */ (value));
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.
589 jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
591 for (var fieldNumber in extensions) {
592 var binaryFieldInfo = extensions[fieldNumber];
593 var fieldInfo = binaryFieldInfo.fieldInfo;
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
598 if (!binaryFieldInfo.binaryWriterFn) {
599 throw new Error('Message extension present that was generated ' +
600 'without binary serialization support');
602 var value = getExtensionFn.call(proto, fieldInfo);
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
611 if (binaryFieldInfo.binaryMessageSerializeFn) {
612 binaryFieldInfo.binaryWriterFn.call(writer, fieldInfo.fieldIndex,
613 value, binaryFieldInfo.binaryMessageSerializeFn);
615 throw new Error('Message extension present holding submessage ' +
616 'without binary support enabled, and message is ' +
617 'being serialized to binary format');
620 binaryFieldInfo.binaryWriterFn.call(
621 writer, fieldInfo.fieldIndex, value);
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
637 jspb.Message.readBinaryExtension = function(msg, reader, extensions,
638 getExtensionFn, setExtensionFn) {
639 var binaryFieldInfo = extensions[reader.getFieldNumber()];
640 if (!binaryFieldInfo) {
644 var fieldInfo = binaryFieldInfo.fieldInfo;
645 if (!binaryFieldInfo.binaryReaderFn) {
646 throw new Error('Deserializing extension whose generated code does not ' +
647 'support binary format');
651 if (fieldInfo.isMessageType()) {
652 value = new fieldInfo.ctor();
653 binaryFieldInfo.binaryReaderFn.call(
654 reader, value, binaryFieldInfo.binaryMessageDeserializeFn);
657 value = binaryFieldInfo.binaryReaderFn.call(reader);
660 if (fieldInfo.isRepeated && !binaryFieldInfo.isPacked) {
661 var currentList = getExtensionFn.call(msg, fieldInfo);
663 setExtensionFn.call(msg, fieldInfo, [value]);
665 currentList.push(value);
668 setExtensionFn.call(msg, fieldInfo, value);
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}
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] = [];
690 if (!msg.extensionObject_) {
693 var val = msg.extensionObject_[fieldNumber];
694 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
695 return msg.extensionObject_[fieldNumber] = [];
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.
710 jspb.Message.getRepeatedField = function(msg, fieldNumber) {
711 return /** @type {!Array} */ (jspb.Message.getField(msg, fieldNumber));
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.
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;
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.
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;
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.
750 jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
751 var values = jspb.Message.getRepeatedField(msg, fieldNumber);
752 if (!msg.convertedPrimitiveFields_) {
753 msg.convertedPrimitiveFields_ = {};
755 if (!msg.convertedPrimitiveFields_[fieldNumber]) {
756 for (var i = 0; i < values.length; i++) {
757 // Converts "NaN", "Infinity" and "-Infinity" to their corresponding
759 values[i] = +values[i];
761 msg.convertedPrimitiveFields_[fieldNumber] = true;
763 return /** @type {!Array<number>} */ (values);
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.
773 jspb.Message.getRepeatedBooleanField = function(msg, fieldNumber) {
774 var values = jspb.Message.getRepeatedField(msg, fieldNumber);
775 if (!msg.convertedPrimitiveFields_) {
776 msg.convertedPrimitiveFields_ = {};
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];
783 msg.convertedPrimitiveFields_[fieldNumber] = true;
785 return /** @type {!Array<boolean>} */ (values);
790 * Coerce a 'bytes' field to a base 64 string.
791 * @param {string|Uint8Array|null} value
792 * @return {?string} The field's coerced value.
794 jspb.Message.bytesAsB64 = function(value) {
795 if (value == null || goog.isString(value)) {
798 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && value instanceof Uint8Array) {
799 return goog.crypt.base64.encodeByteArray(value);
801 goog.asserts.fail('Cannot coerce to b64 string: ' + goog.typeOf(value));
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.
813 jspb.Message.bytesAsU8 = function(value) {
814 if (value == null || value instanceof Uint8Array) {
817 if (goog.isString(value)) {
818 return goog.crypt.base64.decodeStringToUint8Array(value);
820 goog.asserts.fail('Cannot coerce to Uint8Array: ' + goog.typeOf(value));
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.
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);
836 return goog.array.map(value, jspb.Message.bytesAsB64);
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.
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);
853 return goog.array.map(value, jspb.Message.bytesAsU8);
858 * Asserts that all elements of an array are of the same type.
859 * @param {Array?} array The array to test.
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);
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
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.
886 jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
887 var value = jspb.Message.getField(msg, fieldNumber);
897 * Gets the value of a boolean field, with proto3 (non-nullable primitives)
898 * semantics. Returns `defaultValue` if the field is not otherwise set.
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.
906 jspb.Message.getBooleanFieldWithDefault = function(
907 msg, fieldNumber, defaultValue) {
908 var value = jspb.Message.getBooleanField(msg, fieldNumber);
918 * Gets the value of a floating point field, with proto3 (non-nullable
919 * primitives) semantics. Returns `defaultValue` if the field is not otherwise
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.
928 jspb.Message.getFloatingPointFieldWithDefault = function(
929 msg, fieldNumber, defaultValue) {
930 var value = jspb.Message.getOptionalFloatingPointField(msg, fieldNumber);
940 * Alias for getFieldWithDefault used by older generated code.
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.
948 jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
952 * Gets the value of a map field, lazily creating the map container if
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).
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}
967 jspb.Message.getMapField = function(msg, fieldNumber, noLazyCreate,
969 if (!msg.wrappers_) {
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) {
978 // Wrap the underlying elements array with a Map.
979 var arr = jspb.Message.getField(msg, fieldNumber);
982 jspb.Message.setField(msg, fieldNumber, arr);
984 return msg.wrappers_[fieldNumber] =
986 /** @type {!Array<!Array<!Object>>} */ (arr), opt_valueCtor);
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
998 jspb.Message.setField = function(msg, fieldNumber, value) {
999 if (fieldNumber < msg.pivot_) {
1000 msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
1002 jspb.Message.maybeInitEmptyExtensionObject_(msg);
1003 msg.extensionObject_[fieldNumber] = value;
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
1015 jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
1016 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
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
1027 jspb.Message.setProto3FloatField = function(msg, fieldNumber, value) {
1028 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0.0);
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
1039 jspb.Message.setProto3BooleanField = function(msg, fieldNumber, value) {
1040 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, false);
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
1051 jspb.Message.setProto3StringField = function(msg, fieldNumber, value) {
1052 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
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
1063 jspb.Message.setProto3BytesField = function(msg, fieldNumber, value) {
1064 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
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
1075 jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
1076 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1081 * Sets the value of a non-extension int field of a proto3 that has jstype set
1083 * @param {!jspb.Message} msg A jspb proto.
1084 * @param {number} fieldNumber The field number.
1085 * @param {string} value New value
1088 jspb.Message.setProto3StringIntField = function(msg, fieldNumber, value) {
1089 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "0");
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
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.
1102 jspb.Message.setFieldIgnoringDefault_ = function(
1103 msg, fieldNumber, value, defaultValue) {
1104 if (value !== defaultValue) {
1105 jspb.Message.setField(msg, fieldNumber, value);
1107 msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
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.
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);
1131 * Sets the value of a field in a oneof union and clears all other fields in
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
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;
1145 jspb.Message.setField(msg, currentCase, undefined);
1147 jspb.Message.setField(msg, fieldNumber, value);
1152 * Computes the selection in a oneof group for the given message, ensuring
1153 * only one field is set in the process.
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
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.
1168 jspb.Message.computeOneofCase = function(msg, oneof) {
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;
1178 jspb.Message.setField(msg, fieldNumber, undefined);
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);
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.
1203 jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
1204 // TODO(mwr): Consider copying data and/or arrays.
1205 if (!msg.wrappers_) {
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);
1215 return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
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.
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] = [];
1233 return /** @type {!Array<!jspb.Message>} */ (val);
1238 * Wraps underlying array into proto message representation if it wasn't done
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.
1245 jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
1246 if (!msg.wrappers_) {
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]);
1254 msg.wrappers_[fieldNumber] = wrappers;
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
1267 jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
1268 if (!msg.wrappers_) {
1271 var data = value ? value.toArray() : value;
1272 msg.wrappers_[fieldNumber] = value;
1273 jspb.Message.setField(msg, fieldNumber, data);
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.
1285 jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
1286 if (!msg.wrappers_) {
1289 var data = value ? value.toArray() : value;
1290 msg.wrappers_[fieldNumber] = value;
1291 jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
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.
1302 jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
1303 if (!msg.wrappers_) {
1306 value = value || [];
1307 for (var data = [], i = 0; i < value.length; i++) {
1308 data[i] = value[i].toArray();
1310 msg.wrappers_[fieldNumber] = value;
1311 jspb.Message.setField(msg, fieldNumber, data);
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
1321 * @param {function(new:T_CHILD, ?Array=)} ctor The constructor of the
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.
1330 * @template T_CHILD_NOT_UNDEFINED :=
1331 * cond(isUnknown(T_CHILD), unknown(),
1332 * mapunion(T_CHILD, (X) =>
1333 * cond(eq(X, 'undefined'), none(), X)))
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] = [];
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());
1350 wrapperArray.push(insertedValue);
1351 array.push(insertedValue.toArray());
1353 return insertedValue;
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
1363 * @param {function() : string?} mapKeyGetterFn The function to get the key of
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.
1374 jspb.Message.toMap = function(
1375 field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
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];
1387 * Syncs all map fields' contents back to their underlying arrays.
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.
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++) {
1408 // Works for submessages and maps.
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.
1424 jspb.Message.prototype.toArray = function() {
1425 this.syncMapFields_();
1431 if (jspb.Message.GENERATE_TO_STRING) {
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.
1439 jspb.Message.prototype.toString = function() {
1440 this.syncMapFields_();
1441 return this.array.toString();
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.
1452 jspb.Message.prototype.getExtension = function(fieldInfo) {
1453 if (!this.extensionObject_) {
1456 if (!this.wrappers_) {
1457 this.wrappers_ = {};
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] || [],
1466 return new fieldInfo.ctor(arr);
1469 return this.wrappers_[fieldNumber];
1471 return this.extensionObject_[fieldNumber];
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]));
1480 return this.wrappers_[fieldNumber];
1482 return this.extensionObject_[fieldNumber];
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
1493 * @return {THIS} For chaining
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_ = {};
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();
1515 self.extensionObject_[fieldNumber] = value;
1518 if (fieldInfo.isMessageType()) {
1519 self.wrappers_[fieldNumber] = value;
1520 self.extensionObject_[fieldNumber] =
1521 value ? /** @type {!jspb.Message} */ (value).toArray() : value;
1523 self.extensionObject_[fieldNumber] = value;
1531 * Creates a difference object between two messages.
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).
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.
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.
1551 jspb.Message.difference = function(m1, m2) {
1552 if (!(m1 instanceof m2.constructor)) {
1553 throw new Error('Messages have different types.');
1555 var arr1 = m1.toArray();
1556 var arr2 = m2.toArray();
1559 var length = arr1.length > arr2.length ? arr1.length : arr2.length;
1560 if (m1.getJsPbMessageId()) {
1561 res[0] = m1.getJsPbMessageId();
1564 for (var i = start; i < length; i++) {
1565 if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
1569 return new m1.constructor(res);
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.
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()));
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
1593 jspb.Message.compareExtensions = function(extension1, extension2) {
1594 extension1 = extension1 || {};
1595 extension2 = extension2 || {};
1598 for (var name in extension1) {
1601 for (var name in extension2) {
1604 for (name in keys) {
1605 if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
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.
1619 jspb.Message.compareFields = function(field1, field2) {
1620 // If the fields are trivially equal, they're equal.
1621 if (field1 == field2) return true;
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);
1630 // If the fields aren't trivially equal and one of them isn't an object,
1631 // they can't possibly be equal.
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;
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;
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;
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];
1664 if (val1 && (val1.constructor == Object)) {
1665 goog.asserts.assert(extension1 === undefined);
1666 goog.asserts.assert(i === typedField1.length - 1);
1671 if (val2 && (val2.constructor == Object)) {
1672 goog.asserts.assert(extension2 === undefined);
1673 goog.asserts.assert(i === typedField2.length - 1);
1678 if (!jspb.Message.compareFields(val1, val2)) {
1683 if (extension1 || extension2) {
1684 extension1 = extension1 || {};
1685 extension2 = extension2 || {};
1686 return jspb.Message.compareExtensions(extension1, extension2);
1692 // If they're both plain Objects (i.e. extensions), compare them as
1694 if (field1.constructor === Object) {
1695 return jspb.Message.compareExtensions(field1, field2);
1698 throw new Error('Invalid type in JSPB array');
1703 * Templated, type-safe cloneMessage definition.
1708 jspb.Message.prototype.cloneMessage = function() {
1709 return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
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.
1720 jspb.Message.prototype.clone = function() {
1721 return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1725 * Static clone function. NOTE: A type-safe method called "cloneMessage"
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.
1731 jspb.Message.clone = function(msg) {
1732 // Although we could include the wrappers, we leave them out here.
1733 return jspb.Message.cloneMessage(msg);
1738 * @param {!jspb.Message} msg A message to clone.
1739 * @return {!jspb.Message} A deep clone of the given message.
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()));
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
1754 * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
1755 * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
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);
1766 var to = toMessage.toArray();
1767 var from = copyOfFrom.toArray();
1769 // Empty destination in case it has more values at the end of the array.
1771 // and then copy everything from the new to the existing message.
1772 for (var i = 0; i < from.length; i++) {
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_;
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.
1789 jspb.Message.clone_ = function(obj) {
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++) {
1798 // NOTE:redundant null check existing for NTI compatibility.
1800 clonedArray[i] = (typeof o == 'object') ?
1801 jspb.Message.clone_(goog.asserts.assert(o)) :
1807 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array) {
1808 return new Uint8Array(obj);
1811 for (var key in obj) {
1814 // NOTE:redundant null check existing for NTI compatibility.
1816 clone[key] = (typeof o == 'object') ?
1817 jspb.Message.clone_(goog.asserts.assert(o)) :
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.
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.
1835 * @suppress {strictMissingProperties} messageId is not defined on Function
1837 constructor.messageId = id;
1842 * The registry of message ids to message constructors.
1845 jspb.Message.registry_ = {};
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
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.
1857 * @type {!Object<number, jspb.ExtensionFieldInfo>}
1859 jspb.Message.messageSetExtensions = {};
1862 * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}
1864 jspb.Message.messageSetExtensionsBinary = {};