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