• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 requirements 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 serialization,
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                                            Array.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 || typeof value === 'string') {
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 (typeof value === 'string') {
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 || typeof value[0] === 'string') {
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 {T} msg A jspb proto.
980 * @param {number} fieldNumber The field number.
981 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
982 * @return {T} return msg
983 * @template T
984 * @protected
985 */
986jspb.Message.setField = function(msg, fieldNumber, value) {
987  // TODO(b/35241823): replace this with a bounded generic when available
988  goog.asserts.assertInstanceof(msg, jspb.Message);
989  if (fieldNumber < msg.pivot_) {
990    msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
991  } else {
992    jspb.Message.maybeInitEmptyExtensionObject_(msg);
993    msg.extensionObject_[fieldNumber] = value;
994  }
995  return msg;
996};
997
998
999/**
1000 * Sets the value of a non-extension integer field of a proto3
1001 * @param {T} msg A jspb proto.
1002 * @param {number} fieldNumber The field number.
1003 * @param {number} value New value
1004 * @return {T} return msg
1005 * @template T
1006 * @protected
1007 */
1008jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
1009  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1010};
1011
1012
1013/**
1014 * Sets the value of a non-extension floating point field of a proto3
1015 * @param {T} msg A jspb proto.
1016 * @param {number} fieldNumber The field number.
1017 * @param {number} value New value
1018 * @return {T} return msg
1019 * @template T
1020 * @protected
1021 */
1022jspb.Message.setProto3FloatField = function(msg, fieldNumber, value) {
1023  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0.0);
1024};
1025
1026
1027/**
1028 * Sets the value of a non-extension boolean field of a proto3
1029 * @param {T} msg A jspb proto.
1030 * @param {number} fieldNumber The field number.
1031 * @param {boolean} value New value
1032 * @return {T} return msg
1033 * @template T
1034 * @protected
1035 */
1036jspb.Message.setProto3BooleanField = function(msg, fieldNumber, value) {
1037  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, false);
1038};
1039
1040
1041/**
1042 * Sets the value of a non-extension String field of a proto3
1043 * @param {T} msg A jspb proto.
1044 * @param {number} fieldNumber The field number.
1045 * @param {string} value New value
1046 * @return {T} return msg
1047 * @template T
1048 * @protected
1049 */
1050jspb.Message.setProto3StringField = function(msg, fieldNumber, value) {
1051  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, '');
1052};
1053
1054
1055/**
1056 * Sets the value of a non-extension Bytes field of a proto3
1057 * @param {T} msg A jspb proto.
1058 * @param {number} fieldNumber The field number.
1059 * @param {!Uint8Array|string} value New value
1060 * @return {T} return msg
1061 * @template T
1062 * @protected
1063 */
1064jspb.Message.setProto3BytesField = function(msg, fieldNumber, value) {
1065  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, '');
1066};
1067
1068
1069/**
1070 * Sets the value of a non-extension enum field of a proto3
1071 * @param {T} msg A jspb proto.
1072 * @param {number} fieldNumber The field number.
1073 * @param {number} value New value
1074 * @return {T} return msg
1075 * @template T
1076 * @protected
1077 */
1078jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
1079  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1080};
1081
1082
1083/**
1084 * Sets the value of a non-extension int field of a proto3 that has jstype set
1085 * to String.
1086 * @param {T} msg A jspb proto.
1087 * @param {number} fieldNumber The field number.
1088 * @param {string} value New value
1089 * @return {T} return msg
1090 * @template T
1091 * @protected
1092 */
1093jspb.Message.setProto3StringIntField = function(msg, fieldNumber, value) {
1094  return jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, '0');
1095};
1096
1097/**
1098 * Sets the value of a non-extension primitive field, with proto3 (non-nullable
1099 * primitives) semantics of ignoring values that are equal to the type's
1100 * default.
1101 * @param {T} msg A jspb proto.
1102 * @param {number} fieldNumber The field number.
1103 * @param {!Uint8Array|string|number|boolean|undefined} value New value
1104 * @param {!Uint8Array|string|number|boolean} defaultValue The default value.
1105 * @return {T} return msg
1106 * @template T
1107 * @private
1108 */
1109jspb.Message.setFieldIgnoringDefault_ = function(
1110    msg, fieldNumber, value, defaultValue) {
1111  // TODO(b/35241823): replace this with a bounded generic when available
1112  goog.asserts.assertInstanceof(msg, jspb.Message);
1113  if (value !== defaultValue) {
1114    jspb.Message.setField(msg, fieldNumber, value);
1115  } else if (fieldNumber < msg.pivot_) {
1116    msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
1117  } else {
1118    jspb.Message.maybeInitEmptyExtensionObject_(msg);
1119    delete msg.extensionObject_[fieldNumber];
1120  }
1121  return msg;
1122};
1123
1124
1125/**
1126 * Adds a value to a repeated, primitive field.
1127 * @param {T} msg A jspb proto.
1128 * @param {number} fieldNumber The field number.
1129 * @param {string|number|boolean|!Uint8Array} value New value
1130 * @param {number=} opt_index Index where to put new value.
1131 * @return {T} return msg
1132 * @template T
1133 * @protected
1134 */
1135jspb.Message.addToRepeatedField = function(msg, fieldNumber, value, opt_index) {
1136  // TODO(b/35241823): replace this with a bounded generic when available
1137  goog.asserts.assertInstanceof(msg, jspb.Message);
1138  var arr = jspb.Message.getRepeatedField(msg, fieldNumber);
1139  if (opt_index != undefined) {
1140    arr.splice(opt_index, 0, value);
1141  } else {
1142    arr.push(value);
1143  }
1144  return msg;
1145};
1146
1147
1148/**
1149 * Sets the value of a field in a oneof union and clears all other fields in
1150 * the union.
1151 * @param {T} msg A jspb proto.
1152 * @param {number} fieldNumber The field number.
1153 * @param {!Array<number>} oneof The fields belonging to the union.
1154 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
1155 * @return {T} return msg
1156 * @template T
1157 * @protected
1158 */
1159jspb.Message.setOneofField = function(msg, fieldNumber, oneof, value) {
1160  // TODO(b/35241823): replace this with a bounded generic when available
1161  goog.asserts.assertInstanceof(msg, jspb.Message);
1162  var currentCase = jspb.Message.computeOneofCase(msg, oneof);
1163  if (currentCase && currentCase !== fieldNumber && value !== undefined) {
1164    if (msg.wrappers_ && currentCase in msg.wrappers_) {
1165      msg.wrappers_[currentCase] = undefined;
1166    }
1167    jspb.Message.setField(msg, currentCase, undefined);
1168  }
1169  return jspb.Message.setField(msg, fieldNumber, value);
1170};
1171
1172
1173/**
1174 * Computes the selection in a oneof group for the given message, ensuring
1175 * only one field is set in the process.
1176 *
1177 * According to the protobuf language guide (
1178 * https://developers.google.com/protocol-buffers/docs/proto#oneof), "if the
1179 * parser encounters multiple members of the same oneof on the wire, only the
1180 * last member seen is used in the parsed message." Since JSPB serializes
1181 * messages to a JSON array, the "last member seen" will always be the field
1182 * with the greatest field number (directly corresponding to the greatest
1183 * array index).
1184 *
1185 * @param {!jspb.Message} msg A jspb proto.
1186 * @param {!Array<number>} oneof The field numbers belonging to the union.
1187 * @return {number} The field number currently set in the union, or 0 if none.
1188 * @protected
1189 */
1190jspb.Message.computeOneofCase = function(msg, oneof) {
1191  var oneofField;
1192  var oneofValue;
1193
1194  for (var i = 0; i < oneof.length; i++) {
1195    var fieldNumber = oneof[i];
1196    var value = jspb.Message.getField(msg, fieldNumber);
1197    if (value != null) {
1198      oneofField = fieldNumber;
1199      oneofValue = value;
1200      jspb.Message.setField(msg, fieldNumber, undefined);
1201    }
1202  }
1203
1204  if (oneofField) {
1205    // NB: We know the value is unique, so we can call jspb.Message.setField
1206    // directly instead of jpsb.Message.setOneofField. Also, setOneofField
1207    // calls this function.
1208    jspb.Message.setField(msg, oneofField, oneofValue);
1209    return oneofField;
1210  }
1211
1212  return 0;
1213};
1214
1215
1216/**
1217 * Gets and wraps a proto field on access.
1218 * @param {!jspb.Message} msg A jspb proto.
1219 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1220 * @param {number} fieldNumber The field number.
1221 * @param {number=} opt_required True (1) if this is a required field.
1222 * @return {jspb.Message} The field as a jspb proto.
1223 * @protected
1224 */
1225jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
1226  // TODO(mwr): Consider copying data and/or arrays.
1227  if (!msg.wrappers_) {
1228    msg.wrappers_ = {};
1229  }
1230  if (!msg.wrappers_[fieldNumber]) {
1231    var data = /** @type {Array} */ (jspb.Message.getField(msg, fieldNumber));
1232    if (opt_required || data) {
1233      // TODO(mwr): Remove existence test for always valid default protos.
1234      msg.wrappers_[fieldNumber] = new ctor(data);
1235    }
1236  }
1237  return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
1238};
1239
1240
1241/**
1242 * Gets and wraps a repeated proto field on access.
1243 * @param {!jspb.Message} msg A jspb proto.
1244 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1245 * @param {number} fieldNumber The field number.
1246 * @return {!Array<!jspb.Message>} The repeated field as an array of protos.
1247 * @protected
1248 */
1249jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
1250  jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1251  var val = msg.wrappers_[fieldNumber];
1252  if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
1253    val = msg.wrappers_[fieldNumber] = [];
1254  }
1255  return /** @type {!Array<!jspb.Message>} */ (val);
1256};
1257
1258
1259/**
1260 * Wraps underlying array into proto message representation if it wasn't done
1261 * before.
1262 * @param {!jspb.Message} msg A jspb proto.
1263 * @param {function(new:jspb.Message, ?Array)} ctor Constructor for the field.
1264 * @param {number} fieldNumber The field number.
1265 * @private
1266 */
1267jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
1268  if (!msg.wrappers_) {
1269    msg.wrappers_ = {};
1270  }
1271  if (!msg.wrappers_[fieldNumber]) {
1272    var data = jspb.Message.getRepeatedField(msg, fieldNumber);
1273    for (var wrappers = [], i = 0; i < data.length; i++) {
1274      wrappers[i] = new ctor(data[i]);
1275    }
1276    msg.wrappers_[fieldNumber] = wrappers;
1277  }
1278};
1279
1280
1281/**
1282 * Sets a proto field and syncs it to the backing array.
1283 * @param {T} msg A jspb proto.
1284 * @param {number} fieldNumber The field number.
1285 * @param {?jspb.Message|?jspb.Map|undefined} value A new value for this proto
1286 * field.
1287 * @return {T} the msg
1288 * @template T
1289 * @protected
1290 */
1291jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
1292  // TODO(b/35241823): replace this with a bounded generic when available
1293  goog.asserts.assertInstanceof(msg, jspb.Message);
1294  if (!msg.wrappers_) {
1295    msg.wrappers_ = {};
1296  }
1297  var data = value ? value.toArray() : value;
1298  msg.wrappers_[fieldNumber] = value;
1299  return jspb.Message.setField(msg, fieldNumber, data);
1300};
1301
1302
1303
1304/**
1305 * Sets a proto field in a oneof union and syncs it to the backing array.
1306 * @param {T} msg A jspb proto.
1307 * @param {number} fieldNumber The field number.
1308 * @param {!Array<number>} oneof The fields belonging to the union.
1309 * @param {jspb.Message|undefined} value A new value for this proto field.
1310 * @return {T} the msg
1311 * @template T
1312 * @protected
1313 */
1314jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
1315  // TODO(b/35241823): replace this with a bounded generic when available
1316  goog.asserts.assertInstanceof(msg, jspb.Message);
1317  if (!msg.wrappers_) {
1318    msg.wrappers_ = {};
1319  }
1320  var data = value ? value.toArray() : value;
1321  msg.wrappers_[fieldNumber] = value;
1322  return jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
1323};
1324
1325
1326/**
1327 * Sets a repeated proto field and syncs it to the backing array.
1328 * @param {T} msg A jspb proto.
1329 * @param {number} fieldNumber The field number.
1330 * @param {Array<!jspb.Message>|undefined} value An array of protos.
1331 * @return {T} the msg
1332 * @template T
1333 * @protected
1334 */
1335jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
1336  // TODO(b/35241823): replace this with a bounded generic when available
1337  goog.asserts.assertInstanceof(msg, jspb.Message);
1338  if (!msg.wrappers_) {
1339    msg.wrappers_ = {};
1340  }
1341  value = value || [];
1342  for (var data = [], i = 0; i < value.length; i++) {
1343    data[i] = value[i].toArray();
1344  }
1345  msg.wrappers_[fieldNumber] = value;
1346  return jspb.Message.setField(msg, fieldNumber, data);
1347};
1348
1349
1350/**
1351 * Add a message to a repeated proto field.
1352 * @param {!jspb.Message} msg A jspb proto.
1353 * @param {number} fieldNumber The field number.
1354 * @param {T_CHILD|undefined} value Proto that will be added to the
1355 *     repeated field.
1356 * @param {function(new:T_CHILD, ?Array=)} ctor The constructor of the
1357 *     message type.
1358 * @param {number|undefined} index Index at which to insert the value.
1359 * @return {T_CHILD_NOT_UNDEFINED} proto that was inserted to the repeated field
1360 * @template MessageType
1361 * Use go/closure-ttl to declare a non-undefined version of T_CHILD. Replace the
1362 * undefined in blah|undefined with none. This is necessary because the compiler
1363 * will infer T_CHILD to be |undefined.
1364 * @template T_CHILD
1365 * @template T_CHILD_NOT_UNDEFINED :=
1366 *     cond(isUnknown(T_CHILD), unknown(),
1367 *       mapunion(T_CHILD, (X) =>
1368 *         cond(eq(X, 'undefined'), none(), X)))
1369 * =:
1370 * @protected
1371 */
1372jspb.Message.addToRepeatedWrapperField = function(
1373    msg, fieldNumber, value, ctor, index) {
1374  jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1375  var wrapperArray = msg.wrappers_[fieldNumber];
1376  if (!wrapperArray) {
1377    wrapperArray = msg.wrappers_[fieldNumber] = [];
1378  }
1379  var insertedValue = value ? value : new ctor();
1380  var array = jspb.Message.getRepeatedField(msg, fieldNumber);
1381  if (index != undefined) {
1382    wrapperArray.splice(index, 0, insertedValue);
1383    array.splice(index, 0, insertedValue.toArray());
1384  } else {
1385    wrapperArray.push(insertedValue);
1386    array.push(insertedValue.toArray());
1387  }
1388  return insertedValue;
1389};
1390
1391
1392/**
1393 * Converts a JsPb repeated message field into a map. The map will contain
1394 * protos unless an optional toObject function is given, in which case it will
1395 * contain objects suitable for Soy rendering.
1396 * @param {!Array<T>} field The repeated message field to be
1397 *     converted.
1398 * @param {function() : string?} mapKeyGetterFn The function to get the key of
1399 *     the map.
1400 * @param {?function(boolean=): Object|
1401 *     function((boolean|undefined),T): Object} opt_toObjectFn The
1402 *     toObject function for this field. We need to pass this for effective
1403 *     dead code removal.
1404 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
1405 *     for transitional soy proto support: http://goto/soy-param-migration
1406 * @return {!Object<string, Object>} A map of proto or Soy objects.
1407 * @template T
1408 */
1409jspb.Message.toMap = function(
1410    field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
1411  var result = {};
1412  for (var i = 0; i < field.length; i++) {
1413    result[mapKeyGetterFn.call(field[i])] = opt_toObjectFn ?
1414        opt_toObjectFn.call(field[i], opt_includeInstance,
1415            /** @type {!jspb.Message} */ (field[i])) : field[i];
1416  }
1417  return result;
1418};
1419
1420
1421/**
1422 * Syncs all map fields' contents back to their underlying arrays.
1423 * @private
1424 */
1425jspb.Message.prototype.syncMapFields_ = function() {
1426  // This iterates over submessage, map, and repeated fields, which is intended.
1427  // Submessages can contain maps which also need to be synced.
1428  //
1429  // There is a lot of opportunity for optimization here.  For example we could
1430  // statically determine that some messages have no submessages with maps and
1431  // optimize this method away for those just by generating one extra static
1432  // boolean per message type.
1433  if (this.wrappers_) {
1434    for (var fieldNumber in this.wrappers_) {
1435      var val = this.wrappers_[fieldNumber];
1436      if (Array.isArray(val)) {
1437        for (var i = 0; i < val.length; i++) {
1438          if (val[i]) {
1439            val[i].toArray();
1440          }
1441        }
1442      } else {
1443        // Works for submessages and maps.
1444        if (val) {
1445          val.toArray();
1446        }
1447      }
1448    }
1449  }
1450};
1451
1452
1453/**
1454 * Returns the internal array of this proto.
1455 * <p>Note: If you use this array to construct a second proto, the content
1456 * would then be partially shared between the two protos.
1457 * @return {!Array} The proto represented as an array.
1458 */
1459jspb.Message.prototype.toArray = function() {
1460  this.syncMapFields_();
1461  return this.array;
1462};
1463
1464
1465
1466if (jspb.Message.GENERATE_TO_STRING) {
1467
1468/**
1469 * Creates a string representation of the internal data array of this proto.
1470 * <p>NOTE: This string is *not* suitable for use in server requests.
1471 * @return {string} A string representation of this proto.
1472 * @override
1473 */
1474jspb.Message.prototype.toString = function() {
1475  this.syncMapFields_();
1476  return this.array.toString();
1477};
1478
1479}
1480
1481/**
1482 * Gets the value of the extension field from the extended object.
1483 * @param {jspb.ExtensionFieldInfo<T>} fieldInfo Specifies the field to get.
1484 * @return {T} The value of the field.
1485 * @template T
1486 */
1487jspb.Message.prototype.getExtension = function(fieldInfo) {
1488  if (!this.extensionObject_) {
1489    return undefined;
1490  }
1491  if (!this.wrappers_) {
1492    this.wrappers_ = {};
1493  }
1494  var fieldNumber = fieldInfo.fieldIndex;
1495  if (fieldInfo.isRepeated) {
1496    if (fieldInfo.isMessageType()) {
1497      if (!this.wrappers_[fieldNumber]) {
1498        this.wrappers_[fieldNumber] =
1499            goog.array.map(this.extensionObject_[fieldNumber] || [],
1500                function(arr) {
1501                  return new fieldInfo.ctor(arr);
1502                });
1503      }
1504      return this.wrappers_[fieldNumber];
1505    } else {
1506      return this.extensionObject_[fieldNumber];
1507    }
1508  } else {
1509    if (fieldInfo.isMessageType()) {
1510      if (!this.wrappers_[fieldNumber] && this.extensionObject_[fieldNumber]) {
1511        this.wrappers_[fieldNumber] = new fieldInfo.ctor(
1512            /** @type {Array|undefined} */ (
1513                this.extensionObject_[fieldNumber]));
1514      }
1515      return this.wrappers_[fieldNumber];
1516    } else {
1517      return this.extensionObject_[fieldNumber];
1518    }
1519  }
1520};
1521
1522
1523/**
1524 * Sets the value of the extension field in the extended object.
1525 * @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
1526 * @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
1527 *     to set.
1528 * @return {THIS} For chaining
1529 * @this {THIS}
1530 * @template THIS
1531 */
1532jspb.Message.prototype.setExtension = function(fieldInfo, value) {
1533  // Cast self, since the inferred THIS is unknown inside the function body.
1534  // https://github.com/google/closure-compiler/issues/1411#issuecomment-232442220
1535  var self = /** @type {!jspb.Message} */ (this);
1536  if (!self.wrappers_) {
1537    self.wrappers_ = {};
1538  }
1539  jspb.Message.maybeInitEmptyExtensionObject_(self);
1540  var fieldNumber = fieldInfo.fieldIndex;
1541  if (fieldInfo.isRepeated) {
1542    value = value || [];
1543    if (fieldInfo.isMessageType()) {
1544      self.wrappers_[fieldNumber] = value;
1545      self.extensionObject_[fieldNumber] = goog.array.map(
1546          /** @type {!Array<!jspb.Message>} */ (value), function(msg) {
1547        return msg.toArray();
1548      });
1549    } else {
1550      self.extensionObject_[fieldNumber] = value;
1551    }
1552  } else {
1553    if (fieldInfo.isMessageType()) {
1554      self.wrappers_[fieldNumber] = value;
1555      self.extensionObject_[fieldNumber] =
1556          value ? /** @type {!jspb.Message} */ (value).toArray() : value;
1557    } else {
1558      self.extensionObject_[fieldNumber] = value;
1559    }
1560  }
1561  return self;
1562};
1563
1564
1565/**
1566 * Creates a difference object between two messages.
1567 *
1568 * The result will contain the top-level fields of m2 that differ from those of
1569 * m1 at any level of nesting. No data is cloned, the result object will
1570 * share its top-level elements with m2 (but not with m1).
1571 *
1572 * Note that repeated fields should not have null/undefined elements, but if
1573 * they do, this operation will treat repeated fields of different length as
1574 * the same if the only difference between them is due to trailing
1575 * null/undefined values.
1576 *
1577 * @param {!jspb.Message} m1 The first message object.
1578 * @param {!jspb.Message} m2 The second message object.
1579 * @return {!jspb.Message} The difference returned as a proto message.
1580 *     Note that the returned message may be missing required fields. This is
1581 *     currently tolerated in Js, but would cause an error if you tried to
1582 *     send such a proto to the server. You can access the raw difference
1583 *     array with result.toArray().
1584 * @throws {Error} If the messages are responses with different types.
1585 */
1586jspb.Message.difference = function(m1, m2) {
1587  if (!(m1 instanceof m2.constructor)) {
1588    throw new Error('Messages have different types.');
1589  }
1590  var arr1 = m1.toArray();
1591  var arr2 = m2.toArray();
1592  var res = [];
1593  var start = 0;
1594  var length = arr1.length > arr2.length ? arr1.length : arr2.length;
1595  if (m1.getJsPbMessageId()) {
1596    res[0] = m1.getJsPbMessageId();
1597    start = 1;
1598  }
1599  for (var i = start; i < length; i++) {
1600    if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
1601      res[i] = arr2[i];
1602    }
1603  }
1604  return new m1.constructor(res);
1605};
1606
1607
1608/**
1609 * Tests whether two messages are equal.
1610 * @param {jspb.Message|undefined} m1 The first message object.
1611 * @param {jspb.Message|undefined} m2 The second message object.
1612 * @return {boolean} true if both messages are null/undefined, or if both are
1613 *     of the same type and have the same field values.
1614 */
1615jspb.Message.equals = function(m1, m2) {
1616  return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
1617      jspb.Message.compareFields(m1.toArray(), m2.toArray()));
1618};
1619
1620
1621/**
1622 * Compares two message extension fields recursively.
1623 * @param {!Object} extension1 The first field.
1624 * @param {!Object} extension2 The second field.
1625 * @return {boolean} true if the extensions are null/undefined, or otherwise
1626 *     equal.
1627 */
1628jspb.Message.compareExtensions = function(extension1, extension2) {
1629  extension1 = extension1 || {};
1630  extension2 = extension2 || {};
1631
1632  var keys = {};
1633  for (var name in extension1) {
1634    keys[name] = 0;
1635  }
1636  for (var name in extension2) {
1637    keys[name] = 0;
1638  }
1639  for (name in keys) {
1640    if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
1641      return false;
1642    }
1643  }
1644  return true;
1645};
1646
1647
1648/**
1649 * Compares two message fields recursively.
1650 * @param {*} field1 The first field.
1651 * @param {*} field2 The second field.
1652 * @return {boolean} true if the fields are null/undefined, or otherwise equal.
1653 */
1654jspb.Message.compareFields = function(field1, field2) {
1655  // If the fields are trivially equal, they're equal.
1656  if (field1 == field2) return true;
1657
1658  if (!goog.isObject(field1) || !goog.isObject(field2)) {
1659    // NaN != NaN so we cover this case.
1660    if ((typeof field1 === 'number' && isNaN(field1)) ||
1661        (typeof field2 === 'number' && isNaN(field2))) {
1662      // One of the fields might be a string 'NaN'.
1663      return String(field1) == String(field2);
1664    }
1665    // If the fields aren't trivially equal and one of them isn't an object,
1666    // they can't possibly be equal.
1667    return false;
1668  }
1669
1670  // We have two objects. If they're different types, they're not equal.
1671  field1 = /** @type {!Object} */(field1);
1672  field2 = /** @type {!Object} */(field2);
1673  if (field1.constructor != field2.constructor) return false;
1674
1675  // If both are Uint8Arrays, compare them element-by-element.
1676  if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
1677    var bytes1 = /** @type {!Uint8Array} */(field1);
1678    var bytes2 = /** @type {!Uint8Array} */(field2);
1679    if (bytes1.length != bytes2.length) return false;
1680    for (var i = 0; i < bytes1.length; i++) {
1681      if (bytes1[i] != bytes2[i]) return false;
1682    }
1683    return true;
1684  }
1685
1686  // If they're both Arrays, compare them element by element except for the
1687  // optional extension objects at the end, which we compare separately.
1688  if (field1.constructor === Array) {
1689    var typedField1 = /** @type {!Array<?>} */ (field1);
1690    var typedField2 = /** @type {!Array<?>} */ (field2);
1691    var extension1 = undefined;
1692    var extension2 = undefined;
1693
1694    var length = Math.max(typedField1.length, typedField2.length);
1695    for (var i = 0; i < length; i++) {
1696      var val1 = typedField1[i];
1697      var val2 = typedField2[i];
1698
1699      if (val1 && (val1.constructor == Object)) {
1700        goog.asserts.assert(extension1 === undefined);
1701        goog.asserts.assert(i === typedField1.length - 1);
1702        extension1 = val1;
1703        val1 = undefined;
1704      }
1705
1706      if (val2 && (val2.constructor == Object)) {
1707        goog.asserts.assert(extension2 === undefined);
1708        goog.asserts.assert(i === typedField2.length - 1);
1709        extension2 = val2;
1710        val2 = undefined;
1711      }
1712
1713      if (!jspb.Message.compareFields(val1, val2)) {
1714        return false;
1715      }
1716    }
1717
1718    if (extension1 || extension2) {
1719      extension1 = extension1 || {};
1720      extension2 = extension2 || {};
1721      return jspb.Message.compareExtensions(extension1, extension2);
1722    }
1723
1724    return true;
1725  }
1726
1727  // If they're both plain Objects (i.e. extensions), compare them as
1728  // extensions.
1729  if (field1.constructor === Object) {
1730    return jspb.Message.compareExtensions(field1, field2);
1731  }
1732
1733  throw new Error('Invalid type in JSPB array');
1734};
1735
1736
1737/**
1738 * Templated, type-safe cloneMessage definition.
1739 * @return {THIS}
1740 * @this {THIS}
1741 * @template THIS
1742 */
1743jspb.Message.prototype.cloneMessage = function() {
1744  return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1745};
1746
1747/**
1748 * Alias clone to cloneMessage. goog.object.unsafeClone uses clone to
1749 * efficiently copy objects. Without this alias, copying jspb messages comes
1750 * with a large performance penalty.
1751 * @return {THIS}
1752 * @this {THIS}
1753 * @template THIS
1754 */
1755jspb.Message.prototype.clone = function() {
1756  return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1757};
1758
1759/**
1760 * Static clone function. NOTE: A type-safe method called "cloneMessage"
1761 * exists
1762 * on each generated JsPb class. Do not call this function directly.
1763 * @param {!jspb.Message} msg A message to clone.
1764 * @return {!jspb.Message} A deep clone of the given message.
1765 */
1766jspb.Message.clone = function(msg) {
1767  // Although we could include the wrappers, we leave them out here.
1768  return jspb.Message.cloneMessage(msg);
1769};
1770
1771
1772/**
1773 * @param {!jspb.Message} msg A message to clone.
1774 * @return {!jspb.Message} A deep clone of the given message.
1775 * @protected
1776 */
1777jspb.Message.cloneMessage = function(msg) {
1778  // Although we could include the wrappers, we leave them out here.
1779  return new msg.constructor(jspb.Message.clone_(msg.toArray()));
1780};
1781
1782
1783/**
1784 * Takes 2 messages of the same type and copies the contents of the first
1785 * message into the second. After this the 2 messages will equals in terms of
1786 * value semantics but share no state. All data in the destination message will
1787 * be overridden.
1788 *
1789 * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
1790 * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
1791 *     as its contents.
1792 * @template MESSAGE
1793 */
1794jspb.Message.copyInto = function(fromMessage, toMessage) {
1795  goog.asserts.assertInstanceof(fromMessage, jspb.Message);
1796  goog.asserts.assertInstanceof(toMessage, jspb.Message);
1797  goog.asserts.assert(fromMessage.constructor == toMessage.constructor,
1798      'Copy source and target message should have the same type.');
1799  var copyOfFrom = jspb.Message.clone(fromMessage);
1800
1801  var to = toMessage.toArray();
1802  var from = copyOfFrom.toArray();
1803
1804  // Empty destination in case it has more values at the end of the array.
1805  to.length = 0;
1806  // and then copy everything from the new to the existing message.
1807  for (var i = 0; i < from.length; i++) {
1808    to[i] = from[i];
1809  }
1810
1811  // This is either null or empty for a fresh copy.
1812  toMessage.wrappers_ = copyOfFrom.wrappers_;
1813  // Just a reference into the shared array.
1814  toMessage.extensionObject_ = copyOfFrom.extensionObject_;
1815};
1816
1817
1818/**
1819 * Helper for cloning an internal JsPb object.
1820 * @param {!Object} obj A JsPb object, eg, a field, to be cloned.
1821 * @return {!Object} A clone of the input object.
1822 * @private
1823 */
1824jspb.Message.clone_ = function(obj) {
1825  var o;
1826  if (Array.isArray(obj)) {
1827    // Allocate array of correct size.
1828    var clonedArray = new Array(obj.length);
1829    // Use array iteration where possible because it is faster than for-in.
1830    for (var i = 0; i < obj.length; i++) {
1831      o = obj[i];
1832      if (o != null) {
1833        // NOTE:redundant null check existing for NTI compatibility.
1834        // see b/70515949
1835        clonedArray[i] = (typeof o == 'object') ?
1836            jspb.Message.clone_(goog.asserts.assert(o)) :
1837            o;
1838      }
1839    }
1840    return clonedArray;
1841  }
1842  if (jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array) {
1843    return new Uint8Array(obj);
1844  }
1845  var clone = {};
1846  for (var key in obj) {
1847    o = obj[key];
1848    if (o != null) {
1849      // NOTE:redundant null check existing for NTI compatibility.
1850      // see b/70515949
1851      clone[key] = (typeof o == 'object') ?
1852          jspb.Message.clone_(goog.asserts.assert(o)) :
1853          o;
1854    }
1855  }
1856  return clone;
1857};
1858
1859
1860/**
1861 * Registers a JsPb message type id with its constructor.
1862 * @param {string} id The id for this type of message.
1863 * @param {Function} constructor The message constructor.
1864 */
1865jspb.Message.registerMessageType = function(id, constructor) {
1866  // This is needed so we can later access messageId directly on the constructor,
1867  // otherwise it is not available due to 'property collapsing' by the compiler.
1868  /**
1869   * @suppress {strictMissingProperties} messageId is not defined on Function
1870   */
1871  constructor.messageId = id;
1872};
1873/**
1874 * The extensions registered on MessageSet. This is a map of extension
1875 * field number to field info object. This should be considered as a
1876 * private API.
1877 *
1878 * This is similar to [jspb class name].extensions object for
1879 * non-MessageSet. We special case MessageSet so that we do not need
1880 * to goog.require MessageSet from classes that extends MessageSet.
1881 *
1882 * @type {!Object<number, jspb.ExtensionFieldInfo>}
1883 */
1884jspb.Message.messageSetExtensions = {};
1885
1886/**
1887 * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}
1888 */
1889jspb.Message.messageSetExtensionsBinary = {};
1890