blob: 17b562e16ef810aac351cb7b9eb8e8b269f74ea2 [file] [log] [blame]
Feng Xiaoe841bac2015-12-11 17:09:20 -08001// 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
Josh Haberman7429b912016-07-18 15:58:58 -070037goog.provide('jspb.ExtensionFieldBinaryInfo');
Josh Habermane0e73772016-07-18 20:49:11 -070038goog.provide('jspb.ExtensionFieldInfo');
Feng Xiaoe841bac2015-12-11 17:09:20 -080039goog.provide('jspb.Message');
40
41goog.require('goog.array');
42goog.require('goog.asserts');
Jisi Liu3b3c8ab2016-03-30 11:39:59 -070043goog.require('goog.crypt.base64');
Adam Cozzetted64a2d92016-06-29 15:23:27 -070044goog.require('jspb.Map');
Feng Xiaoe841bac2015-12-11 17:09:20 -080045
46// Not needed in compilation units that have no protos with xids.
47goog.forwardDeclare('xid.String');
48
49
50
51/**
52 * Stores information for a single extension field.
53 *
54 * For example, an extension field defined like so:
55 *
56 * extend BaseMessage {
57 * optional MyMessage my_field = 123;
58 * }
59 *
60 * will result in an ExtensionFieldInfo object with these properties:
61 *
62 * {
63 * fieldIndex: 123,
64 * fieldName: {my_field_renamed: 0},
65 * ctor: proto.example.MyMessage,
66 * toObjectFn: proto.example.MyMessage.toObject,
67 * isRepeated: 0
68 * }
69 *
70 * We include `toObjectFn` to allow the JSCompiler to perform dead-code removal
71 * on unused toObject() methods.
72 *
73 * If an extension field is primitive, ctor and toObjectFn will be null.
74 * isRepeated should be 0 or 1.
75 *
76 * binary{Reader,Writer}Fn and (if message type) binaryMessageSerializeFn are
77 * always provided. binaryReaderFn and binaryWriterFn are references to the
78 * appropriate methods on BinaryReader/BinaryWriter to read/write the value of
79 * this extension, and binaryMessageSerializeFn is a reference to the message
80 * class's .serializeBinary method, if available.
81 *
82 * @param {number} fieldNumber
83 * @param {Object} fieldName This has the extension field name as a property.
84 * @param {?function(new: jspb.Message, Array=)} ctor
85 * @param {?function((boolean|undefined),!jspb.Message):!Object} toObjectFn
86 * @param {number} isRepeated
Feng Xiaoe841bac2015-12-11 17:09:20 -080087 * @constructor
88 * @struct
89 * @template T
90 */
91jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
Josh Haberman7429b912016-07-18 15:58:58 -070092 isRepeated) {
Feng Xiaoe841bac2015-12-11 17:09:20 -080093 /** @const */
94 this.fieldIndex = fieldNumber;
95 /** @const */
96 this.fieldName = fieldName;
97 /** @const */
98 this.ctor = ctor;
99 /** @const */
100 this.toObjectFn = toObjectFn;
101 /** @const */
Feng Xiaoe841bac2015-12-11 17:09:20 -0800102 this.isRepeated = isRepeated;
Feng Xiaoe841bac2015-12-11 17:09:20 -0800103};
104
Josh Haberman7429b912016-07-18 15:58:58 -0700105/**
106 * Stores binary-related information for a single extension field.
107 * @param {!jspb.ExtensionFieldInfo<T>} fieldInfo
Feng Xiaod36c0c52017-03-29 14:32:48 -0700108 * @param {function(this:jspb.BinaryReader,number,?)} binaryReaderFn
109 * @param {function(this:jspb.BinaryWriter,number,?)
110 * |function(this:jspb.BinaryWriter,number,?,?,?,?,?)} binaryWriterFn
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700111 * @param {function(?,?)=} opt_binaryMessageSerializeFn
112 * @param {function(?,?)=} opt_binaryMessageDeserializeFn
113 * @param {boolean=} opt_isPacked
Josh Haberman7429b912016-07-18 15:58:58 -0700114 * @constructor
115 * @struct
116 * @template T
117 */
118jspb.ExtensionFieldBinaryInfo = function(fieldInfo, binaryReaderFn, binaryWriterFn,
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700119 opt_binaryMessageSerializeFn, opt_binaryMessageDeserializeFn, opt_isPacked) {
Josh Haberman7429b912016-07-18 15:58:58 -0700120 /** @const */
121 this.fieldInfo = fieldInfo;
122 /** @const */
123 this.binaryReaderFn = binaryReaderFn;
124 /** @const */
125 this.binaryWriterFn = binaryWriterFn;
126 /** @const */
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700127 this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
Josh Haberman7429b912016-07-18 15:58:58 -0700128 /** @const */
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700129 this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
Josh Haberman7429b912016-07-18 15:58:58 -0700130 /** @const */
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700131 this.isPacked = opt_isPacked;
Josh Haberman7429b912016-07-18 15:58:58 -0700132};
Feng Xiaoe841bac2015-12-11 17:09:20 -0800133
134/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700135 * @return {boolean} Does this field represent a sub Message?
136 */
137jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
138 return !!this.ctor;
139};
140
141
142/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800143 * Base class for all JsPb messages.
Feng Xiaod36c0c52017-03-29 14:32:48 -0700144 *
145 * Several common methods (toObject, serializeBinary, in particular) are not
146 * defined on the prototype to encourage code patterns that minimize code bloat
147 * due to otherwise unused code on all protos contained in the project.
148 *
149 * If you want to call these methods on a generic message, either
150 * pass in your instance of method as a parameter:
151 * someFunction(instanceOfKnownProto,
152 * KnownProtoClass.prototype.serializeBinary);
153 * or use a lambda that knows the type:
154 * someFunction(()=>instanceOfKnownProto.serializeBinary());
155 * or, if you don't care about code size, just suppress the
156 * WARNING - Property serializeBinary never defined on jspb.Message
157 * and call it the intuitive way.
158 *
Feng Xiaoe841bac2015-12-11 17:09:20 -0800159 * @constructor
160 * @struct
161 */
162jspb.Message = function() {
163};
164
165
166/**
167 * @define {boolean} Whether to generate toObject methods for objects. Turn
168 * this off, if you do not want toObject to be ever used in your project.
169 * When turning off this flag, consider adding a conformance test that bans
170 * calling toObject. Enabling this will disable the JSCompiler's ability to
171 * dead code eliminate fields used in protocol buffers that are never used
172 * in an application.
173 */
174goog.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 * NOTE: By default no protos actually have a fromObject method. You need to
185 * add the jspb.generate_from_object options to the proto definition to
186 * activate the feature.
187 * By default this is enabled for test code only.
188 */
189goog.define('jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
190
191
192/**
Paul Yang7f3e2372017-01-31 09:17:32 -0800193 * @define {boolean} Whether to generate toString methods for objects. Turn
Jisi Liu09354db2017-07-18 15:38:30 -0700194 * this off if you do not use toString in your project and want to trim it
195 * from the compiled JS.
Paul Yang7f3e2372017-01-31 09:17:32 -0800196 */
197goog.define('jspb.Message.GENERATE_TO_STRING', true);
198
199
200/**
201 * @define {boolean} Whether arrays passed to initialize() can be assumed to be
202 * local (e.g. not from another iframe) and thus safely classified with
203 * instanceof Array.
204 */
205goog.define('jspb.Message.ASSUME_LOCAL_ARRAYS', false);
206
207
Adam Cozzette92a7e772017-12-01 10:05:10 -0800208// 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 */
215goog.define('jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS', true);
216
217
Paul Yang7f3e2372017-01-31 09:17:32 -0800218/**
Josh Habermanf873d322016-06-08 12:38:15 -0700219 * Does this JavaScript environment support Uint8Aray typed arrays?
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700220 * @type {boolean}
221 * @private
222 */
223jspb.Message.SUPPORTS_UINT8ARRAY_ = (typeof Uint8Array == 'function');
224
225
226/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800227 * The internal data array.
228 * @type {!Array}
229 * @protected
230 */
231jspb.Message.prototype.array;
232
233
234/**
235 * Wrappers are the constructed instances of message-type fields. They are built
236 * on demand from the raw array data. Includes message fields, repeated message
237 * fields and extension message fields. Indexed by field number.
238 * @type {Object}
239 * @private
240 */
241jspb.Message.prototype.wrappers_;
242
243
244/**
245 * The object that contains extension fields, if any. This is an object that
246 * maps from a proto field number to the field's value.
247 * @type {Object}
248 * @private
249 */
250jspb.Message.prototype.extensionObject_;
251
252
253/**
254 * Non-extension fields with a field number at or above the pivot are
255 * stored in the extension object (in addition to all extension fields).
256 * @type {number}
257 * @private
258 */
259jspb.Message.prototype.pivot_;
260
261
262/**
263 * The JsPb message_id of this proto.
264 * @type {string|undefined} the message id or undefined if this message
265 * has no id.
266 * @private
267 */
268jspb.Message.prototype.messageId_;
269
270
271/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700272 * Repeated float or double fields which have been converted to include only
273 * numbers and not strings holding "NaN", "Infinity" and "-Infinity".
274 * @private {!Object<number,boolean>|undefined}
275 */
276jspb.Message.prototype.convertedFloatingPointFields_;
277
278
279/**
Adam Cozzette92a7e772017-12-01 10:05:10 -0800280 * Repeated fields numbers.
281 * @protected {?Array<number>|undefined}
282 */
283jspb.Message.prototype.repeatedFields;
284
285
286/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800287 * The xid of this proto type (The same for all instances of a proto). Provides
288 * a way to identify a proto by stable obfuscated name.
289 * @see {xid}.
290 * Available if {@link jspb.generate_xid} is added as a Message option to
291 * a protocol buffer.
292 * @const {!xid.String|undefined} The xid or undefined if message is
293 * annotated to generate the xid.
294 */
295jspb.Message.prototype.messageXid;
296
297
298
299/**
300 * Returns the JsPb message_id of this proto.
301 * @return {string|undefined} the message id or undefined if this message
302 * has no id.
303 */
304jspb.Message.prototype.getJsPbMessageId = function() {
305 return this.messageId_;
306};
307
308
309/**
310 * An offset applied to lookups into this.array to account for the presence or
311 * absence of a messageId at position 0. For response messages, this will be 0.
312 * Otherwise, it will be -1 so that the first array position is not wasted.
313 * @type {number}
314 * @private
315 */
316jspb.Message.prototype.arrayIndexOffset_;
317
318
319/**
320 * Returns the index into msg.array at which the proto field with tag number
321 * fieldNumber will be located.
322 * @param {!jspb.Message} msg Message for which we're calculating an index.
323 * @param {number} fieldNumber The field number.
324 * @return {number} The index.
325 * @private
326 */
327jspb.Message.getIndex_ = function(msg, fieldNumber) {
328 return fieldNumber + msg.arrayIndexOffset_;
329};
330
331
332/**
Adam Cozzette92a7e772017-12-01 10:05:10 -0800333 * Returns the tag number based on the index in msg.array.
334 * @param {!jspb.Message} msg Message for which we're calculating an index.
335 * @param {number} index The tag number.
336 * @return {number} The field number.
337 * @private
338 */
339jspb.Message.getFieldNumber_ = function(msg, index) {
340 return index - msg.arrayIndexOffset_;
341};
342
343
344/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800345 * Initializes a JsPb Message.
346 * @param {!jspb.Message} msg The JsPb proto to modify.
347 * @param {Array|undefined} data An initial data array.
348 * @param {string|number} messageId For response messages, the message id or ''
349 * if no message id is specified. For non-response messages, 0.
350 * @param {number} suggestedPivot The field number at which to start putting
351 * fields into the extension object. This is only used if data does not
352 * contain an extension object already. -1 if no extension object is
353 * required for this message type.
354 * @param {Array<number>} repeatedFields The message's repeated fields.
355 * @param {Array<!Array<number>>=} opt_oneofFields The fields belonging to
356 * each of the message's oneof unions.
357 * @protected
358 */
359jspb.Message.initialize = function(
360 msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
Adam Cozzette0400cca2018-03-13 16:37:29 -0700361 msg.wrappers_ = null;
Feng Xiaoe841bac2015-12-11 17:09:20 -0800362 if (!data) {
363 data = messageId ? [messageId] : [];
364 }
365 msg.messageId_ = messageId ? String(messageId) : undefined;
366 // If the messageId is 0, this message is not a response message, so we shift
367 // array indices down by 1 so as not to waste the first position in the array,
368 // which would otherwise go unused.
369 msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
370 msg.array = data;
Jisi Liu09354db2017-07-18 15:38:30 -0700371 jspb.Message.initPivotAndExtensionObject_(msg, suggestedPivot);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700372 msg.convertedFloatingPointFields_ = {};
373
Adam Cozzette92a7e772017-12-01 10:05:10 -0800374 if (!jspb.Message.SERIALIZE_EMPTY_TRAILING_FIELDS) {
375 // TODO(jakubvrana): This is same for all instances, move to prototype.
376 // TODO(jakubvrana): There are indexOf calls on this in serializtion,
377 // consider switching to a set.
378 msg.repeatedFields = repeatedFields;
379 }
380
Feng Xiaoe841bac2015-12-11 17:09:20 -0800381 if (repeatedFields) {
382 for (var i = 0; i < repeatedFields.length; i++) {
383 var fieldNumber = repeatedFields[i];
384 if (fieldNumber < msg.pivot_) {
385 var index = jspb.Message.getIndex_(msg, fieldNumber);
Adam Cozzette0400cca2018-03-13 16:37:29 -0700386 msg.array[index] =
387 msg.array[index] || jspb.Message.EMPTY_LIST_SENTINEL_;
Feng Xiaoe841bac2015-12-11 17:09:20 -0800388 } else {
Jisi Liu09354db2017-07-18 15:38:30 -0700389 jspb.Message.maybeInitEmptyExtensionObject_(msg);
Adam Cozzette0400cca2018-03-13 16:37:29 -0700390 msg.extensionObject_[fieldNumber] = msg.extensionObject_[fieldNumber] ||
391 jspb.Message.EMPTY_LIST_SENTINEL_;
Feng Xiaoe841bac2015-12-11 17:09:20 -0800392 }
393 }
394 }
395
396 if (opt_oneofFields && opt_oneofFields.length) {
397 // Compute the oneof case for each union. This ensures only one value is
398 // set in the union.
Adam Cozzette92a7e772017-12-01 10:05:10 -0800399 for (var i = 0; i < opt_oneofFields.length; i++) {
400 jspb.Message.computeOneofCase(msg, opt_oneofFields[i]);
401 }
Feng Xiaoe841bac2015-12-11 17:09:20 -0800402 }
403};
404
405
406/**
407 * Used to mark empty repeated fields. Serializes to null when serialized
408 * to JSON.
409 * When reading a repeated field readers must check the return value against
410 * this value and return and replace it with a new empty array if it is
411 * present.
412 * @private @const {!Object}
413 */
414jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ?
415 Object.freeze([]) :
416 [];
417
418
419/**
Paul Yang7f3e2372017-01-31 09:17:32 -0800420 * Returns true if the provided argument is an array.
421 * @param {*} o The object to classify as array or not.
422 * @return {boolean} True if the provided object is an array.
423 * @private
424 */
425jspb.Message.isArray_ = function(o) {
426 return jspb.Message.ASSUME_LOCAL_ARRAYS ? o instanceof Array :
427 goog.isArray(o);
428};
429
Adam Cozzette0894e072018-11-09 11:28:22 -0800430/**
431 * Returns true if the provided argument is an extension object.
432 * @param {*} o The object to classify as array or not.
433 * @return {boolean} True if the provided object is an extension object.
434 * @private
435 */
436jspb.Message.isExtensionObject_ = function(o) {
437 // Normal fields are never objects, so we can be sure that if we find an
438 // object here, then it's the extension object. However, we must ensure that
439 // the object is not an array, since arrays are valid field values (bytes
440 // fields can also be array).
441 // NOTE(lukestebbing): We avoid looking at .length to avoid a JIT bug
442 // in Safari on iOS 8. See the description of CL/86511464 for details.
443 return (o !== null && typeof o == 'object' &&
444 !jspb.Message.isArray_(o) &&
445 !(jspb.Message.SUPPORTS_UINT8ARRAY_ && o instanceof Uint8Array));
446};
447
Paul Yang7f3e2372017-01-31 09:17:32 -0800448
449/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800450 * If the array contains an extension object in its last position, then the
Jisi Liu09354db2017-07-18 15:38:30 -0700451 * object is kept in place and its position is used as the pivot. If not,
452 * decides the pivot of the message based on suggestedPivot without
453 * materializing the extension object.
454 *
Feng Xiaoe841bac2015-12-11 17:09:20 -0800455 * @param {!jspb.Message} msg The JsPb proto to modify.
456 * @param {number} suggestedPivot See description for initialize().
457 * @private
458 */
Jisi Liu09354db2017-07-18 15:38:30 -0700459jspb.Message.initPivotAndExtensionObject_ = function(msg, suggestedPivot) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700460 // There are 3 variants that need to be dealt with which are the
461 // combination of whether there exists an extension object (EO) and
462 // whether there is a suggested pivot (SP).
463 //
464 // EO, ? : pivot is the index of the EO
465 // no-EO, no-SP: pivot is MAX_INT
466 // no-EO, SP : pivot is the max(lastindex + 1, SP)
467
468 var msgLength = msg.array.length;
469 var lastIndex = -1;
470 if (msgLength) {
471 lastIndex = msgLength - 1;
472 var obj = msg.array[lastIndex];
Adam Cozzette0894e072018-11-09 11:28:22 -0800473 if (jspb.Message.isExtensionObject_(obj)) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700474 msg.pivot_ = jspb.Message.getFieldNumber_(msg, lastIndex);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800475 msg.extensionObject_ = obj;
476 return;
477 }
478 }
Jisi Liu09354db2017-07-18 15:38:30 -0700479
Feng Xiaoe841bac2015-12-11 17:09:20 -0800480 if (suggestedPivot > -1) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700481 // If a extension object is not present, set the pivot value as being
482 // after the last value in the array to avoid overwriting values, etc.
483 msg.pivot_ = Math.max(
484 suggestedPivot, jspb.Message.getFieldNumber_(msg, lastIndex + 1));
Jisi Liu09354db2017-07-18 15:38:30 -0700485 // Avoid changing the shape of the proto with an empty extension object by
486 // deferring the materialization of the extension object until the first
487 // time a field set into it (may be due to getting a repeated proto field
488 // from it, in which case a new empty array is set into it at first).
489 msg.extensionObject_ = null;
Feng Xiaoe841bac2015-12-11 17:09:20 -0800490 } else {
Jisi Liu09354db2017-07-18 15:38:30 -0700491 // suggestedPivot is -1, which means that we don't have an extension object
492 // at all, in which case all fields are stored in the array.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800493 msg.pivot_ = Number.MAX_VALUE;
494 }
495};
496
497
498/**
499 * Creates an empty extensionObject_ if non exists.
500 * @param {!jspb.Message} msg The JsPb proto to modify.
501 * @private
502 */
503jspb.Message.maybeInitEmptyExtensionObject_ = function(msg) {
504 var pivotIndex = jspb.Message.getIndex_(msg, msg.pivot_);
505 if (!msg.array[pivotIndex]) {
506 msg.extensionObject_ = msg.array[pivotIndex] = {};
507 }
508};
509
510
511/**
512 * Converts a JsPb repeated message field into an object list.
513 * @param {!Array<T>} field The repeated message field to be
514 * converted.
515 * @param {?function(boolean=): Object|
516 * function((boolean|undefined),T): Object} toObjectFn The toObject
517 * function for this field. We need to pass this for effective dead code
518 * removal.
519 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
520 * for transitional soy proto support: http://goto/soy-param-migration
521 * @return {!Array<Object>} An array of converted message objects.
522 * @template T
523 */
524jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) {
525 // Not using goog.array.map in the generated code to keep it small.
526 // And not using it here to avoid a function call.
527 var result = [];
528 for (var i = 0; i < field.length; i++) {
Adam Cozzette0400cca2018-03-13 16:37:29 -0700529 result[i] = toObjectFn.call(field[i], opt_includeInstance, field[i]);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800530 }
531 return result;
532};
533
534
535/**
536 * Adds a proto's extension data to a Soy rendering object.
537 * @param {!jspb.Message} proto The proto whose extensions to convert.
538 * @param {!Object} obj The Soy object to add converted extension data to.
539 * @param {!Object} extensions The proto class' registered extensions.
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700540 * @param {function(this:?, jspb.ExtensionFieldInfo) : *} getExtensionFn
541 * The proto class' getExtension function. Passed for effective dead code
542 * removal.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800543 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
544 * for transitional soy proto support: http://goto/soy-param-migration
545 */
546jspb.Message.toObjectExtension = function(proto, obj, extensions,
547 getExtensionFn, opt_includeInstance) {
548 for (var fieldNumber in extensions) {
549 var fieldInfo = extensions[fieldNumber];
550 var value = getExtensionFn.call(proto, fieldInfo);
Jisi Liu09354db2017-07-18 15:38:30 -0700551 if (value != null) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800552 for (var name in fieldInfo.fieldName) {
553 if (fieldInfo.fieldName.hasOwnProperty(name)) {
554 break; // the compiled field name
555 }
556 }
557 if (!fieldInfo.toObjectFn) {
558 obj[name] = value;
559 } else {
560 if (fieldInfo.isRepeated) {
561 obj[name] = jspb.Message.toObjectList(
Adam Cozzette0400cca2018-03-13 16:37:29 -0700562 /** @type {!Array<!jspb.Message>} */ (value),
Feng Xiaoe841bac2015-12-11 17:09:20 -0800563 fieldInfo.toObjectFn, opt_includeInstance);
564 } else {
Adam Cozzette0400cca2018-03-13 16:37:29 -0700565 obj[name] = fieldInfo.toObjectFn(
566 opt_includeInstance, /** @type {!jspb.Message} */ (value));
Feng Xiaoe841bac2015-12-11 17:09:20 -0800567 }
568 }
569 }
570 }
571};
572
573
574/**
575 * Writes a proto's extension data to a binary-format output stream.
576 * @param {!jspb.Message} proto The proto whose extensions to convert.
577 * @param {*} writer The binary-format writer to write to.
578 * @param {!Object} extensions The proto class' registered extensions.
Feng Xiaod36c0c52017-03-29 14:32:48 -0700579 * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo) : *} getExtensionFn The proto
Feng Xiaoe841bac2015-12-11 17:09:20 -0800580 * class' getExtension function. Passed for effective dead code removal.
581 */
582jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
583 getExtensionFn) {
584 for (var fieldNumber in extensions) {
Josh Haberman7429b912016-07-18 15:58:58 -0700585 var binaryFieldInfo = extensions[fieldNumber];
586 var fieldInfo = binaryFieldInfo.fieldInfo;
587
Feng Xiaoe841bac2015-12-11 17:09:20 -0800588 // The old codegen doesn't add the extra fields to ExtensionFieldInfo, so we
589 // need to gracefully error-out here rather than produce a null dereference
590 // below.
Josh Haberman7429b912016-07-18 15:58:58 -0700591 if (!binaryFieldInfo.binaryWriterFn) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800592 throw new Error('Message extension present that was generated ' +
593 'without binary serialization support');
594 }
595 var value = getExtensionFn.call(proto, fieldInfo);
Jisi Liu09354db2017-07-18 15:38:30 -0700596 if (value != null) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700597 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800598 // If the message type of the extension was generated without binary
599 // support, there may not be a binary message serializer function, and
600 // we can't know when we codegen the extending message that the extended
601 // message may require binary support, so we can *only* catch this error
602 // here, at runtime (and this decoupled codegen is the whole point of
603 // extensions!).
Josh Haberman7429b912016-07-18 15:58:58 -0700604 if (binaryFieldInfo.binaryMessageSerializeFn) {
605 binaryFieldInfo.binaryWriterFn.call(writer, fieldInfo.fieldIndex,
606 value, binaryFieldInfo.binaryMessageSerializeFn);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800607 } else {
608 throw new Error('Message extension present holding submessage ' +
609 'without binary support enabled, and message is ' +
610 'being serialized to binary format');
611 }
612 } else {
Josh Haberman7429b912016-07-18 15:58:58 -0700613 binaryFieldInfo.binaryWriterFn.call(
614 writer, fieldInfo.fieldIndex, value);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800615 }
616 }
617 }
618};
619
620
621/**
622 * Reads an extension field from the given reader and, if a valid extension,
623 * sets the extension value.
624 * @param {!jspb.Message} msg A jspb proto.
Feng Xiaod36c0c52017-03-29 14:32:48 -0700625 * @param {{
626 * skipField:function(this:jspb.BinaryReader),
627 * getFieldNumber:function(this:jspb.BinaryReader):number
628 * }} reader
Feng Xiaoe841bac2015-12-11 17:09:20 -0800629 * @param {!Object} extensions The extensions object.
Feng Xiaod36c0c52017-03-29 14:32:48 -0700630 * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo)} getExtensionFn
631 * @param {function(this:jspb.Message,!jspb.ExtensionFieldInfo, ?)} setExtensionFn
Feng Xiaoe841bac2015-12-11 17:09:20 -0800632 */
633jspb.Message.readBinaryExtension = function(msg, reader, extensions,
634 getExtensionFn, setExtensionFn) {
Josh Haberman7429b912016-07-18 15:58:58 -0700635 var binaryFieldInfo = extensions[reader.getFieldNumber()];
Josh Haberman7429b912016-07-18 15:58:58 -0700636 if (!binaryFieldInfo) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800637 reader.skipField();
638 return;
639 }
Adam Cozzette5a76e632016-11-17 16:48:38 -0800640 var fieldInfo = binaryFieldInfo.fieldInfo;
Josh Haberman7429b912016-07-18 15:58:58 -0700641 if (!binaryFieldInfo.binaryReaderFn) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800642 throw new Error('Deserializing extension whose generated code does not ' +
643 'support binary format');
644 }
645
646 var value;
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700647 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800648 value = new fieldInfo.ctor();
Josh Haberman7429b912016-07-18 15:58:58 -0700649 binaryFieldInfo.binaryReaderFn.call(
650 reader, value, binaryFieldInfo.binaryMessageDeserializeFn);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800651 } else {
652 // All other types.
Josh Haberman7429b912016-07-18 15:58:58 -0700653 value = binaryFieldInfo.binaryReaderFn.call(reader);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800654 }
655
Josh Haberman7429b912016-07-18 15:58:58 -0700656 if (fieldInfo.isRepeated && !binaryFieldInfo.isPacked) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800657 var currentList = getExtensionFn.call(msg, fieldInfo);
658 if (!currentList) {
659 setExtensionFn.call(msg, fieldInfo, [value]);
660 } else {
661 currentList.push(value);
662 }
663 } else {
664 setExtensionFn.call(msg, fieldInfo, value);
665 }
666};
667
668
669/**
670 * Gets the value of a non-extension field.
671 * @param {!jspb.Message} msg A jspb proto.
672 * @param {number} fieldNumber The field number.
673 * @return {string|number|boolean|Uint8Array|Array|null|undefined}
674 * The field's value.
675 * @protected
676 */
677jspb.Message.getField = function(msg, fieldNumber) {
678 if (fieldNumber < msg.pivot_) {
679 var index = jspb.Message.getIndex_(msg, fieldNumber);
680 var val = msg.array[index];
681 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
682 return msg.array[index] = [];
683 }
684 return val;
685 } else {
Jisi Liu09354db2017-07-18 15:38:30 -0700686 if (!msg.extensionObject_) {
687 return undefined;
688 }
Feng Xiaoe841bac2015-12-11 17:09:20 -0800689 var val = msg.extensionObject_[fieldNumber];
690 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
691 return msg.extensionObject_[fieldNumber] = [];
692 }
693 return val;
694 }
695};
696
697
698/**
Jisi Liu09354db2017-07-18 15:38:30 -0700699 * Gets the value of a non-extension repeated field.
700 * @param {!jspb.Message} msg A jspb proto.
701 * @param {number} fieldNumber The field number.
702 * @return {!Array}
703 * The field's value.
704 * @protected
705 */
706jspb.Message.getRepeatedField = function(msg, fieldNumber) {
707 if (fieldNumber < msg.pivot_) {
708 var index = jspb.Message.getIndex_(msg, fieldNumber);
709 var val = msg.array[index];
710 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
711 return msg.array[index] = [];
712 }
713 return val;
714 }
715
716 var val = msg.extensionObject_[fieldNumber];
717 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
718 return msg.extensionObject_[fieldNumber] = [];
719 }
720 return val;
721};
722
723
724/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700725 * Gets the value of an optional float or double field.
726 * @param {!jspb.Message} msg A jspb proto.
727 * @param {number} fieldNumber The field number.
728 * @return {?number|undefined} The field's value.
729 * @protected
730 */
731jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
732 var value = jspb.Message.getField(msg, fieldNumber);
733 // Converts "NaN", "Infinity" and "-Infinity" to their corresponding numbers.
734 return value == null ? value : +value;
735};
736
737
738/**
739 * Gets the value of a repeated float or double field.
740 * @param {!jspb.Message} msg A jspb proto.
741 * @param {number} fieldNumber The field number.
742 * @return {!Array<number>} The field's value.
743 * @protected
744 */
745jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
Jisi Liu09354db2017-07-18 15:38:30 -0700746 var values = jspb.Message.getRepeatedField(msg, fieldNumber);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700747 if (!msg.convertedFloatingPointFields_) {
748 msg.convertedFloatingPointFields_ = {};
749 }
750 if (!msg.convertedFloatingPointFields_[fieldNumber]) {
751 for (var i = 0; i < values.length; i++) {
752 // Converts "NaN", "Infinity" and "-Infinity" to their corresponding
753 // numbers.
754 values[i] = +values[i];
755 }
756 msg.convertedFloatingPointFields_[fieldNumber] = true;
757 }
758 return /** @type {!Array<number>} */ (values);
759};
760
761
762/**
763 * Coerce a 'bytes' field to a base 64 string.
764 * @param {string|Uint8Array|null} value
765 * @return {?string} The field's coerced value.
766 */
767jspb.Message.bytesAsB64 = function(value) {
768 if (value == null || goog.isString(value)) {
769 return value;
770 }
771 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && value instanceof Uint8Array) {
772 return goog.crypt.base64.encodeByteArray(value);
773 }
774 goog.asserts.fail('Cannot coerce to b64 string: ' + goog.typeOf(value));
775 return null;
776};
777
778
779/**
780 * Coerce a 'bytes' field to a Uint8Array byte buffer.
781 * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
782 * Mini. @see http://caniuse.com/Uint8Array
783 * @param {string|Uint8Array|null} value
784 * @return {?Uint8Array} The field's coerced value.
785 */
786jspb.Message.bytesAsU8 = function(value) {
787 if (value == null || value instanceof Uint8Array) {
788 return value;
789 }
790 if (goog.isString(value)) {
791 return goog.crypt.base64.decodeStringToUint8Array(value);
792 }
793 goog.asserts.fail('Cannot coerce to Uint8Array: ' + goog.typeOf(value));
794 return null;
795};
796
797
798/**
799 * Coerce a repeated 'bytes' field to an array of base 64 strings.
800 * Note: the returned array should be treated as immutable.
801 * @param {!Array<string>|!Array<!Uint8Array>} value
802 * @return {!Array<string?>} The field's coerced value.
803 */
804jspb.Message.bytesListAsB64 = function(value) {
805 jspb.Message.assertConsistentTypes_(value);
806 if (!value.length || goog.isString(value[0])) {
807 return /** @type {!Array<string>} */ (value);
808 }
809 return goog.array.map(value, jspb.Message.bytesAsB64);
810};
811
812
813/**
814 * Coerce a repeated 'bytes' field to an array of Uint8Array byte buffers.
815 * Note: the returned array should be treated as immutable.
816 * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
817 * Mini. @see http://caniuse.com/Uint8Array
818 * @param {!Array<string>|!Array<!Uint8Array>} value
819 * @return {!Array<Uint8Array?>} The field's coerced value.
820 */
821jspb.Message.bytesListAsU8 = function(value) {
822 jspb.Message.assertConsistentTypes_(value);
823 if (!value.length || value[0] instanceof Uint8Array) {
824 return /** @type {!Array<!Uint8Array>} */ (value);
825 }
826 return goog.array.map(value, jspb.Message.bytesAsU8);
827};
828
829
830/**
831 * Asserts that all elements of an array are of the same type.
832 * @param {Array?} array The array to test.
833 * @private
834 */
835jspb.Message.assertConsistentTypes_ = function(array) {
836 if (goog.DEBUG && array && array.length > 1) {
837 var expected = goog.typeOf(array[0]);
838 goog.array.forEach(array, function(e) {
839 if (goog.typeOf(e) != expected) {
840 goog.asserts.fail('Inconsistent type in JSPB repeated field array. ' +
841 'Got ' + goog.typeOf(e) + ' expected ' + expected);
842 }
843 });
844 }
845};
846
847
848/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800849 * Gets the value of a non-extension primitive field, with proto3 (non-nullable
850 * primitives) semantics. Returns `defaultValue` if the field is not otherwise
851 * set.
852 * @template T
853 * @param {!jspb.Message} msg A jspb proto.
854 * @param {number} fieldNumber The field number.
855 * @param {T} defaultValue The default value.
856 * @return {T} The field's value.
857 * @protected
858 */
Bo Yangcc8ca5b2016-09-19 13:45:07 -0700859jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800860 var value = jspb.Message.getField(msg, fieldNumber);
861 if (value == null) {
862 return defaultValue;
863 } else {
864 return value;
865 }
866};
867
868
869/**
Josh Habermanf2eeaf72016-09-28 10:52:32 -0700870 * Alias for getFieldWithDefault used by older generated code.
871 * @template T
872 * @param {!jspb.Message} msg A jspb proto.
873 * @param {number} fieldNumber The field number.
874 * @param {T} defaultValue The default value.
875 * @return {T} The field's value.
876 * @protected
877 */
878jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
879
880
881/**
Adam Cozzetted64a2d92016-06-29 15:23:27 -0700882 * Gets the value of a map field, lazily creating the map container if
883 * necessary.
884 *
885 * This should only be called from generated code, because it requires knowledge
886 * of serialization/parsing callbacks (which are required by the map at
887 * construction time, and the map may be constructed here).
888 *
Adam Cozzetted64a2d92016-06-29 15:23:27 -0700889 * @template K, V
890 * @param {!jspb.Message} msg
891 * @param {number} fieldNumber
892 * @param {boolean|undefined} noLazyCreate
893 * @param {?=} opt_valueCtor
Adam Cozzetted64a2d92016-06-29 15:23:27 -0700894 * @return {!jspb.Map<K, V>|undefined}
895 * @protected
896 */
897jspb.Message.getMapField = function(msg, fieldNumber, noLazyCreate,
Josh Haberman923eae82016-07-18 14:46:12 -0700898 opt_valueCtor) {
Adam Cozzetted64a2d92016-06-29 15:23:27 -0700899 if (!msg.wrappers_) {
900 msg.wrappers_ = {};
901 }
902 // If we already have a map in the map wrappers, return that.
903 if (fieldNumber in msg.wrappers_) {
904 return msg.wrappers_[fieldNumber];
905 } else if (noLazyCreate) {
906 return undefined;
907 } else {
908 // Wrap the underlying elements array with a Map.
909 var arr = jspb.Message.getField(msg, fieldNumber);
910 if (!arr) {
911 arr = [];
912 jspb.Message.setField(msg, fieldNumber, arr);
913 }
914 return msg.wrappers_[fieldNumber] =
915 new jspb.Map(
Josh Haberman923eae82016-07-18 14:46:12 -0700916 /** @type {!Array<!Array<!Object>>} */ (arr), opt_valueCtor);
Adam Cozzetted64a2d92016-06-29 15:23:27 -0700917 }
918};
919
920
921/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800922 * Sets the value of a non-extension field.
923 * @param {!jspb.Message} msg A jspb proto.
924 * @param {number} fieldNumber The field number.
925 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
926 * @protected
927 */
928jspb.Message.setField = function(msg, fieldNumber, value) {
929 if (fieldNumber < msg.pivot_) {
930 msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
931 } else {
Jisi Liu09354db2017-07-18 15:38:30 -0700932 jspb.Message.maybeInitEmptyExtensionObject_(msg);
Feng Xiaoe841bac2015-12-11 17:09:20 -0800933 msg.extensionObject_[fieldNumber] = value;
934 }
935};
936
937
938/**
Adam Cozzette13fd0452017-09-12 10:32:01 -0700939 * Sets the value of a non-extension integer field of a proto3
940 * @param {!jspb.Message} msg A jspb proto.
941 * @param {number} fieldNumber The field number.
942 * @param {number} value New value
943 * @protected
944 */
945jspb.Message.setProto3IntField = function(msg, fieldNumber, value) {
946 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
947};
948
949
950/**
951 * Sets the value of a non-extension floating point field of a proto3
952 * @param {!jspb.Message} msg A jspb proto.
953 * @param {number} fieldNumber The field number.
954 * @param {number} value New value
955 * @protected
956 */
957jspb.Message.setProto3FloatField = function(msg, fieldNumber, value) {
958 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0.0);
959};
960
961
962/**
963 * Sets the value of a non-extension boolean field of a proto3
964 * @param {!jspb.Message} msg A jspb proto.
965 * @param {number} fieldNumber The field number.
966 * @param {boolean} value New value
967 * @protected
968 */
969jspb.Message.setProto3BooleanField = function(msg, fieldNumber, value) {
970 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, false);
971};
972
973
974/**
975 * Sets the value of a non-extension String field of a proto3
976 * @param {!jspb.Message} msg A jspb proto.
977 * @param {number} fieldNumber The field number.
978 * @param {string} value New value
979 * @protected
980 */
981jspb.Message.setProto3StringField = function(msg, fieldNumber, value) {
982 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
983};
984
985
986/**
987 * Sets the value of a non-extension Bytes field of a proto3
988 * @param {!jspb.Message} msg A jspb proto.
989 * @param {number} fieldNumber The field number.
990 * @param {!Uint8Array|string} value New value
991 * @protected
992 */
993jspb.Message.setProto3BytesField = function(msg, fieldNumber, value) {
994 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "");
995};
996
997
998/**
999 * Sets the value of a non-extension enum field of a proto3
1000 * @param {!jspb.Message} msg A jspb proto.
1001 * @param {number} fieldNumber The field number.
1002 * @param {number} value New value
1003 * @protected
1004 */
1005jspb.Message.setProto3EnumField = function(msg, fieldNumber, value) {
1006 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, 0);
1007};
1008
1009
Feng Xiao6bbe1972018-08-08 17:00:41 -07001010/**
1011 * Sets the value of a non-extension int field of a proto3 that has jstype set
1012 * to String.
1013 * @param {!jspb.Message} msg A jspb proto.
1014 * @param {number} fieldNumber The field number.
1015 * @param {string} value New value
1016 * @protected
1017 */
1018jspb.Message.setProto3StringIntField = function(msg, fieldNumber, value) {
1019 jspb.Message.setFieldIgnoringDefault_(msg, fieldNumber, value, "0");
1020};
Adam Cozzette13fd0452017-09-12 10:32:01 -07001021
1022/**
1023 * Sets the value of a non-extension primitive field, with proto3 (non-nullable
1024 * primitives) semantics of ignoring values that are equal to the type's
1025 * default.
Adam Cozzette13fd0452017-09-12 10:32:01 -07001026 * @param {!jspb.Message} msg A jspb proto.
1027 * @param {number} fieldNumber The field number.
1028 * @param {!Uint8Array|string|number|boolean|undefined} value New value
1029 * @param {!Uint8Array|string|number|boolean} defaultValue The default value.
1030 * @private
1031 */
1032jspb.Message.setFieldIgnoringDefault_ = function(
1033 msg, fieldNumber, value, defaultValue) {
Feng Xiao6bbe1972018-08-08 17:00:41 -07001034 if (value !== defaultValue) {
Adam Cozzette13fd0452017-09-12 10:32:01 -07001035 jspb.Message.setField(msg, fieldNumber, value);
1036 } else {
1037 msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = null;
1038 }
1039};
1040
1041
1042/**
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001043 * Adds a value to a repeated, primitive field.
1044 * @param {!jspb.Message} msg A jspb proto.
1045 * @param {number} fieldNumber The field number.
1046 * @param {string|number|boolean|!Uint8Array} value New value
1047 * @param {number=} opt_index Index where to put new value.
1048 * @protected
1049 */
1050jspb.Message.addToRepeatedField = function(msg, fieldNumber, value, opt_index) {
Jisi Liu09354db2017-07-18 15:38:30 -07001051 var arr = jspb.Message.getRepeatedField(msg, fieldNumber);
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001052 if (opt_index != undefined) {
1053 arr.splice(opt_index, 0, value);
1054 } else {
1055 arr.push(value);
1056 }
1057};
1058
1059
1060/**
Feng Xiaoe841bac2015-12-11 17:09:20 -08001061 * Sets the value of a field in a oneof union and clears all other fields in
1062 * the union.
1063 * @param {!jspb.Message} msg A jspb proto.
1064 * @param {number} fieldNumber The field number.
1065 * @param {!Array<number>} oneof The fields belonging to the union.
1066 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
1067 * @protected
1068 */
1069jspb.Message.setOneofField = function(msg, fieldNumber, oneof, value) {
1070 var currentCase = jspb.Message.computeOneofCase(msg, oneof);
1071 if (currentCase && currentCase !== fieldNumber && value !== undefined) {
1072 if (msg.wrappers_ && currentCase in msg.wrappers_) {
1073 msg.wrappers_[currentCase] = undefined;
1074 }
1075 jspb.Message.setField(msg, currentCase, undefined);
1076 }
1077 jspb.Message.setField(msg, fieldNumber, value);
1078};
1079
1080
1081/**
1082 * Computes the selection in a oneof group for the given message, ensuring
1083 * only one field is set in the process.
1084 *
1085 * According to the protobuf language guide (
1086 * https://developers.google.com/protocol-buffers/docs/proto#oneof), "if the
1087 * parser encounters multiple members of the same oneof on the wire, only the
1088 * last member seen is used in the parsed message." Since JSPB serializes
1089 * messages to a JSON array, the "last member seen" will always be the field
1090 * with the greatest field number (directly corresponding to the greatest
1091 * array index).
1092 *
1093 * @param {!jspb.Message} msg A jspb proto.
1094 * @param {!Array<number>} oneof The field numbers belonging to the union.
1095 * @return {number} The field number currently set in the union, or 0 if none.
1096 * @protected
1097 */
1098jspb.Message.computeOneofCase = function(msg, oneof) {
1099 var oneofField;
1100 var oneofValue;
1101
Adam Cozzette92a7e772017-12-01 10:05:10 -08001102 for (var i = 0; i < oneof.length; i++) {
1103 var fieldNumber = oneof[i];
Feng Xiaoe841bac2015-12-11 17:09:20 -08001104 var value = jspb.Message.getField(msg, fieldNumber);
Adam Cozzette92a7e772017-12-01 10:05:10 -08001105 if (value != null) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001106 oneofField = fieldNumber;
1107 oneofValue = value;
1108 jspb.Message.setField(msg, fieldNumber, undefined);
1109 }
Adam Cozzette92a7e772017-12-01 10:05:10 -08001110 }
Feng Xiaoe841bac2015-12-11 17:09:20 -08001111
1112 if (oneofField) {
1113 // NB: We know the value is unique, so we can call jspb.Message.setField
1114 // directly instead of jpsb.Message.setOneofField. Also, setOneofField
1115 // calls this function.
1116 jspb.Message.setField(msg, oneofField, oneofValue);
1117 return oneofField;
1118 }
1119
1120 return 0;
1121};
1122
1123
1124/**
1125 * Gets and wraps a proto field on access.
1126 * @param {!jspb.Message} msg A jspb proto.
1127 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1128 * @param {number} fieldNumber The field number.
1129 * @param {number=} opt_required True (1) if this is a required field.
1130 * @return {jspb.Message} The field as a jspb proto.
1131 * @protected
1132 */
1133jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
1134 // TODO(mwr): Consider copying data and/or arrays.
1135 if (!msg.wrappers_) {
1136 msg.wrappers_ = {};
1137 }
1138 if (!msg.wrappers_[fieldNumber]) {
1139 var data = /** @type {Array} */ (jspb.Message.getField(msg, fieldNumber));
1140 if (opt_required || data) {
1141 // TODO(mwr): Remove existence test for always valid default protos.
1142 msg.wrappers_[fieldNumber] = new ctor(data);
1143 }
1144 }
1145 return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
1146};
1147
1148
1149/**
1150 * Gets and wraps a repeated proto field on access.
1151 * @param {!jspb.Message} msg A jspb proto.
1152 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
1153 * @param {number} fieldNumber The field number.
Feng Xiao6bbe1972018-08-08 17:00:41 -07001154 * @return {!Array<!jspb.Message>} The repeated field as an array of protos.
Feng Xiaoe841bac2015-12-11 17:09:20 -08001155 * @protected
1156 */
1157jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001158 jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1159 var val = msg.wrappers_[fieldNumber];
1160 if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
1161 val = msg.wrappers_[fieldNumber] = [];
1162 }
1163 return /** @type {!Array<!jspb.Message>} */ (val);
1164};
1165
1166
1167/**
1168 * Wraps underlying array into proto message representation if it wasn't done
1169 * before.
1170 * @param {!jspb.Message} msg A jspb proto.
1171 * @param {function(new:jspb.Message, ?Array)} ctor Constructor for the field.
1172 * @param {number} fieldNumber The field number.
1173 * @private
1174 */
1175jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001176 if (!msg.wrappers_) {
1177 msg.wrappers_ = {};
1178 }
1179 if (!msg.wrappers_[fieldNumber]) {
Jisi Liu09354db2017-07-18 15:38:30 -07001180 var data = jspb.Message.getRepeatedField(msg, fieldNumber);
Feng Xiaoe841bac2015-12-11 17:09:20 -08001181 for (var wrappers = [], i = 0; i < data.length; i++) {
1182 wrappers[i] = new ctor(data[i]);
1183 }
1184 msg.wrappers_[fieldNumber] = wrappers;
1185 }
Feng Xiaoe841bac2015-12-11 17:09:20 -08001186};
1187
1188
1189/**
1190 * Sets a proto field and syncs it to the backing array.
1191 * @param {!jspb.Message} msg A jspb proto.
1192 * @param {number} fieldNumber The field number.
Adam Cozzette5a76e632016-11-17 16:48:38 -08001193 * @param {?jspb.Message|?jspb.Map|undefined} value A new value for this proto
1194 * field.
Feng Xiaoe841bac2015-12-11 17:09:20 -08001195 * @protected
1196 */
1197jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
1198 if (!msg.wrappers_) {
1199 msg.wrappers_ = {};
1200 }
1201 var data = value ? value.toArray() : value;
1202 msg.wrappers_[fieldNumber] = value;
1203 jspb.Message.setField(msg, fieldNumber, data);
1204};
1205
1206
1207/**
1208 * Sets a proto field in a oneof union and syncs it to the backing array.
1209 * @param {!jspb.Message} msg A jspb proto.
1210 * @param {number} fieldNumber The field number.
1211 * @param {!Array<number>} oneof The fields belonging to the union.
1212 * @param {jspb.Message|undefined} value A new value for this proto field.
1213 * @protected
1214 */
1215jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
1216 if (!msg.wrappers_) {
1217 msg.wrappers_ = {};
1218 }
1219 var data = value ? value.toArray() : value;
1220 msg.wrappers_[fieldNumber] = value;
1221 jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
1222};
1223
1224
1225/**
1226 * Sets a repeated proto field and syncs it to the backing array.
1227 * @param {!jspb.Message} msg A jspb proto.
1228 * @param {number} fieldNumber The field number.
1229 * @param {Array<!jspb.Message>|undefined} value An array of protos.
1230 * @protected
1231 */
1232jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
1233 if (!msg.wrappers_) {
1234 msg.wrappers_ = {};
1235 }
1236 value = value || [];
1237 for (var data = [], i = 0; i < value.length; i++) {
1238 data[i] = value[i].toArray();
1239 }
1240 msg.wrappers_[fieldNumber] = value;
1241 jspb.Message.setField(msg, fieldNumber, data);
1242};
1243
1244
1245/**
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001246 * Add a message to a repeated proto field.
1247 * @param {!jspb.Message} msg A jspb proto.
1248 * @param {number} fieldNumber The field number.
1249 * @param {T_CHILD|undefined} value Proto that will be added to the
1250 * repeated field.
1251 * @param {function(new:T_CHILD, ?Array=)} ctor The constructor of the
1252 * message type.
1253 * @param {number|undefined} index Index at which to insert the value.
1254 * @return {T_CHILD_NOT_UNDEFINED} proto that was inserted to the repeated field
1255 * @template MessageType
1256 * Use go/closure-ttl to declare a non-undefined version of T_CHILD. Replace the
1257 * undefined in blah|undefined with none. This is necessary because the compiler
1258 * will infer T_CHILD to be |undefined.
1259 * @template T_CHILD
1260 * @template T_CHILD_NOT_UNDEFINED :=
1261 * cond(isUnknown(T_CHILD), unknown(),
1262 * mapunion(T_CHILD, (X) =>
1263 * cond(eq(X, 'undefined'), none(), X)))
1264 * =:
1265 * @protected
1266 */
1267jspb.Message.addToRepeatedWrapperField = function(
1268 msg, fieldNumber, value, ctor, index) {
1269 jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
1270 var wrapperArray = msg.wrappers_[fieldNumber];
1271 if (!wrapperArray) {
1272 wrapperArray = msg.wrappers_[fieldNumber] = [];
1273 }
1274 var insertedValue = value ? value : new ctor();
Jisi Liu09354db2017-07-18 15:38:30 -07001275 var array = jspb.Message.getRepeatedField(msg, fieldNumber);
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001276 if (index != undefined) {
1277 wrapperArray.splice(index, 0, insertedValue);
1278 array.splice(index, 0, insertedValue.toArray());
1279 } else {
1280 wrapperArray.push(insertedValue);
1281 array.push(insertedValue.toArray());
1282 }
1283 return insertedValue;
1284};
1285
1286
1287/**
Feng Xiaoe841bac2015-12-11 17:09:20 -08001288 * Converts a JsPb repeated message field into a map. The map will contain
1289 * protos unless an optional toObject function is given, in which case it will
1290 * contain objects suitable for Soy rendering.
1291 * @param {!Array<T>} field The repeated message field to be
1292 * converted.
1293 * @param {function() : string?} mapKeyGetterFn The function to get the key of
1294 * the map.
1295 * @param {?function(boolean=): Object|
1296 * function((boolean|undefined),T): Object} opt_toObjectFn The
1297 * toObject function for this field. We need to pass this for effective
1298 * dead code removal.
1299 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
1300 * for transitional soy proto support: http://goto/soy-param-migration
Adam Cozzette92a7e772017-12-01 10:05:10 -08001301 * @return {!Object<string, Object>} A map of proto or Soy objects.
Feng Xiaoe841bac2015-12-11 17:09:20 -08001302 * @template T
1303 */
1304jspb.Message.toMap = function(
1305 field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
1306 var result = {};
1307 for (var i = 0; i < field.length; i++) {
1308 result[mapKeyGetterFn.call(field[i])] = opt_toObjectFn ?
1309 opt_toObjectFn.call(field[i], opt_includeInstance,
1310 /** @type {!jspb.Message} */ (field[i])) : field[i];
1311 }
1312 return result;
1313};
1314
1315
1316/**
Adam Cozzetted64a2d92016-06-29 15:23:27 -07001317 * Syncs all map fields' contents back to their underlying arrays.
1318 * @private
1319 */
1320jspb.Message.prototype.syncMapFields_ = function() {
1321 // This iterates over submessage, map, and repeated fields, which is intended.
1322 // Submessages can contain maps which also need to be synced.
1323 //
1324 // There is a lot of opportunity for optimization here. For example we could
1325 // statically determine that some messages have no submessages with maps and
1326 // optimize this method away for those just by generating one extra static
1327 // boolean per message type.
1328 if (this.wrappers_) {
1329 for (var fieldNumber in this.wrappers_) {
1330 var val = this.wrappers_[fieldNumber];
1331 if (goog.isArray(val)) {
1332 for (var i = 0; i < val.length; i++) {
1333 if (val[i]) {
1334 val[i].toArray();
1335 }
1336 }
1337 } else {
1338 // Works for submessages and maps.
1339 if (val) {
1340 val.toArray();
1341 }
1342 }
1343 }
1344 }
1345};
1346
1347
1348/**
Feng Xiaoe841bac2015-12-11 17:09:20 -08001349 * Returns the internal array of this proto.
1350 * <p>Note: If you use this array to construct a second proto, the content
1351 * would then be partially shared between the two protos.
1352 * @return {!Array} The proto represented as an array.
1353 */
1354jspb.Message.prototype.toArray = function() {
Adam Cozzetted64a2d92016-06-29 15:23:27 -07001355 this.syncMapFields_();
Feng Xiaoe841bac2015-12-11 17:09:20 -08001356 return this.array;
1357};
1358
1359
1360
Paul Yang7f3e2372017-01-31 09:17:32 -08001361if (jspb.Message.GENERATE_TO_STRING) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001362
1363/**
1364 * Creates a string representation of the internal data array of this proto.
1365 * <p>NOTE: This string is *not* suitable for use in server requests.
1366 * @return {string} A string representation of this proto.
1367 * @override
1368 */
1369jspb.Message.prototype.toString = function() {
Adam Cozzetted64a2d92016-06-29 15:23:27 -07001370 this.syncMapFields_();
Feng Xiaoe841bac2015-12-11 17:09:20 -08001371 return this.array.toString();
1372};
1373
Paul Yang7f3e2372017-01-31 09:17:32 -08001374}
Feng Xiaoe841bac2015-12-11 17:09:20 -08001375
1376/**
1377 * Gets the value of the extension field from the extended object.
Adam Cozzette92a7e772017-12-01 10:05:10 -08001378 * @param {jspb.ExtensionFieldInfo<T>} fieldInfo Specifies the field to get.
Feng Xiaoe841bac2015-12-11 17:09:20 -08001379 * @return {T} The value of the field.
1380 * @template T
1381 */
1382jspb.Message.prototype.getExtension = function(fieldInfo) {
1383 if (!this.extensionObject_) {
1384 return undefined;
1385 }
1386 if (!this.wrappers_) {
1387 this.wrappers_ = {};
1388 }
1389 var fieldNumber = fieldInfo.fieldIndex;
1390 if (fieldInfo.isRepeated) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001391 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001392 if (!this.wrappers_[fieldNumber]) {
1393 this.wrappers_[fieldNumber] =
1394 goog.array.map(this.extensionObject_[fieldNumber] || [],
1395 function(arr) {
1396 return new fieldInfo.ctor(arr);
1397 });
1398 }
1399 return this.wrappers_[fieldNumber];
1400 } else {
1401 return this.extensionObject_[fieldNumber];
1402 }
1403 } else {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001404 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001405 if (!this.wrappers_[fieldNumber] && this.extensionObject_[fieldNumber]) {
1406 this.wrappers_[fieldNumber] = new fieldInfo.ctor(
1407 /** @type {Array|undefined} */ (
1408 this.extensionObject_[fieldNumber]));
1409 }
1410 return this.wrappers_[fieldNumber];
1411 } else {
1412 return this.extensionObject_[fieldNumber];
1413 }
1414 }
1415};
1416
1417
1418/**
1419 * Sets the value of the extension field in the extended object.
1420 * @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001421 * @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
1422 * to set.
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001423 * @return {THIS} For chaining
1424 * @this {THIS}
1425 * @template THIS
Feng Xiaoe841bac2015-12-11 17:09:20 -08001426 */
1427jspb.Message.prototype.setExtension = function(fieldInfo, value) {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001428 // Cast self, since the inferred THIS is unknown inside the function body.
1429 // https://github.com/google/closure-compiler/issues/1411#issuecomment-232442220
1430 var self = /** @type {!jspb.Message} */ (this);
1431 if (!self.wrappers_) {
1432 self.wrappers_ = {};
Feng Xiaoe841bac2015-12-11 17:09:20 -08001433 }
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001434 jspb.Message.maybeInitEmptyExtensionObject_(self);
Feng Xiaoe841bac2015-12-11 17:09:20 -08001435 var fieldNumber = fieldInfo.fieldIndex;
1436 if (fieldInfo.isRepeated) {
1437 value = value || [];
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001438 if (fieldInfo.isMessageType()) {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001439 self.wrappers_[fieldNumber] = value;
1440 self.extensionObject_[fieldNumber] = goog.array.map(
Adam Cozzette0400cca2018-03-13 16:37:29 -07001441 /** @type {!Array<!jspb.Message>} */ (value), function(msg) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001442 return msg.toArray();
1443 });
1444 } else {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001445 self.extensionObject_[fieldNumber] = value;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001446 }
1447 } else {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001448 if (fieldInfo.isMessageType()) {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001449 self.wrappers_[fieldNumber] = value;
Adam Cozzette0400cca2018-03-13 16:37:29 -07001450 self.extensionObject_[fieldNumber] =
1451 value ? /** @type {!jspb.Message} */ (value).toArray() : value;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001452 } else {
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001453 self.extensionObject_[fieldNumber] = value;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001454 }
1455 }
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001456 return self;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001457};
1458
1459
1460/**
1461 * Creates a difference object between two messages.
1462 *
1463 * The result will contain the top-level fields of m2 that differ from those of
1464 * m1 at any level of nesting. No data is cloned, the result object will
1465 * share its top-level elements with m2 (but not with m1).
1466 *
1467 * Note that repeated fields should not have null/undefined elements, but if
1468 * they do, this operation will treat repeated fields of different length as
1469 * the same if the only difference between them is due to trailing
1470 * null/undefined values.
1471 *
1472 * @param {!jspb.Message} m1 The first message object.
1473 * @param {!jspb.Message} m2 The second message object.
1474 * @return {!jspb.Message} The difference returned as a proto message.
1475 * Note that the returned message may be missing required fields. This is
1476 * currently tolerated in Js, but would cause an error if you tried to
1477 * send such a proto to the server. You can access the raw difference
1478 * array with result.toArray().
1479 * @throws {Error} If the messages are responses with different types.
1480 */
1481jspb.Message.difference = function(m1, m2) {
1482 if (!(m1 instanceof m2.constructor)) {
1483 throw new Error('Messages have different types.');
1484 }
1485 var arr1 = m1.toArray();
1486 var arr2 = m2.toArray();
1487 var res = [];
1488 var start = 0;
1489 var length = arr1.length > arr2.length ? arr1.length : arr2.length;
1490 if (m1.getJsPbMessageId()) {
1491 res[0] = m1.getJsPbMessageId();
1492 start = 1;
1493 }
1494 for (var i = start; i < length; i++) {
1495 if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
1496 res[i] = arr2[i];
1497 }
1498 }
1499 return new m1.constructor(res);
1500};
1501
1502
1503/**
1504 * Tests whether two messages are equal.
1505 * @param {jspb.Message|undefined} m1 The first message object.
1506 * @param {jspb.Message|undefined} m2 The second message object.
1507 * @return {boolean} true if both messages are null/undefined, or if both are
1508 * of the same type and have the same field values.
1509 */
1510jspb.Message.equals = function(m1, m2) {
1511 return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
1512 jspb.Message.compareFields(m1.toArray(), m2.toArray()));
1513};
1514
1515
1516/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001517 * Compares two message extension fields recursively.
1518 * @param {!Object} extension1 The first field.
1519 * @param {!Object} extension2 The second field.
1520 * @return {boolean} true if the extensions are null/undefined, or otherwise
1521 * equal.
1522 */
1523jspb.Message.compareExtensions = function(extension1, extension2) {
1524 extension1 = extension1 || {};
1525 extension2 = extension2 || {};
1526
1527 var keys = {};
1528 for (var name in extension1) {
1529 keys[name] = 0;
1530 }
1531 for (var name in extension2) {
1532 keys[name] = 0;
1533 }
1534 for (name in keys) {
1535 if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
1536 return false;
1537 }
1538 }
1539 return true;
1540};
1541
1542
1543/**
Feng Xiaoe841bac2015-12-11 17:09:20 -08001544 * Compares two message fields recursively.
1545 * @param {*} field1 The first field.
1546 * @param {*} field2 The second field.
1547 * @return {boolean} true if the fields are null/undefined, or otherwise equal.
1548 */
1549jspb.Message.compareFields = function(field1, field2) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001550 // If the fields are trivially equal, they're equal.
1551 if (field1 == field2) return true;
1552
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001553 if (!goog.isObject(field1) || !goog.isObject(field2)) {
Adam Cozzette0400cca2018-03-13 16:37:29 -07001554 // NaN != NaN so we cover this case.
1555 if ((goog.isNumber(field1) && isNaN(field1)) ||
1556 (goog.isNumber(field2) && isNaN(field2))) {
1557 // One of the fields might be a string 'NaN'.
1558 return String(field1) == String(field2);
1559 }
1560 // If the fields aren't trivially equal and one of them isn't an object,
1561 // they can't possibly be equal.
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001562 return false;
1563 }
1564
1565 // We have two objects. If they're different types, they're not equal.
1566 field1 = /** @type {!Object} */(field1);
1567 field2 = /** @type {!Object} */(field2);
1568 if (field1.constructor != field2.constructor) return false;
1569
1570 // If both are Uint8Arrays, compare them element-by-element.
1571 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
1572 var bytes1 = /** @type {!Uint8Array} */(field1);
1573 var bytes2 = /** @type {!Uint8Array} */(field2);
1574 if (bytes1.length != bytes2.length) return false;
1575 for (var i = 0; i < bytes1.length; i++) {
1576 if (bytes1[i] != bytes2[i]) return false;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001577 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001578 return true;
1579 }
1580
1581 // If they're both Arrays, compare them element by element except for the
1582 // optional extension objects at the end, which we compare separately.
1583 if (field1.constructor === Array) {
Adam Cozzette0400cca2018-03-13 16:37:29 -07001584 var typedField1 = /** @type {!Array<?>} */ (field1);
1585 var typedField2 = /** @type {!Array<?>} */ (field2);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001586 var extension1 = undefined;
1587 var extension2 = undefined;
1588
Adam Cozzette0400cca2018-03-13 16:37:29 -07001589 var length = Math.max(typedField1.length, typedField2.length);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001590 for (var i = 0; i < length; i++) {
Adam Cozzette0400cca2018-03-13 16:37:29 -07001591 var val1 = typedField1[i];
1592 var val2 = typedField2[i];
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001593
1594 if (val1 && (val1.constructor == Object)) {
1595 goog.asserts.assert(extension1 === undefined);
Adam Cozzette0400cca2018-03-13 16:37:29 -07001596 goog.asserts.assert(i === typedField1.length - 1);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001597 extension1 = val1;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001598 val1 = undefined;
1599 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001600
1601 if (val2 && (val2.constructor == Object)) {
1602 goog.asserts.assert(extension2 === undefined);
Adam Cozzette0400cca2018-03-13 16:37:29 -07001603 goog.asserts.assert(i === typedField2.length - 1);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001604 extension2 = val2;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001605 val2 = undefined;
1606 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001607
Feng Xiaoe841bac2015-12-11 17:09:20 -08001608 if (!jspb.Message.compareFields(val1, val2)) {
1609 return false;
1610 }
1611 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001612
1613 if (extension1 || extension2) {
1614 extension1 = extension1 || {};
1615 extension2 = extension2 || {};
1616 return jspb.Message.compareExtensions(extension1, extension2);
Feng Xiaoe841bac2015-12-11 17:09:20 -08001617 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001618
Feng Xiaoe841bac2015-12-11 17:09:20 -08001619 return true;
1620 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001621
1622 // If they're both plain Objects (i.e. extensions), compare them as
1623 // extensions.
1624 if (field1.constructor === Object) {
1625 return jspb.Message.compareExtensions(field1, field2);
1626 }
1627
1628 throw new Error('Invalid type in JSPB array');
Feng Xiaoe841bac2015-12-11 17:09:20 -08001629};
1630
1631
1632/**
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001633 * Templated, type-safe cloneMessage definition.
1634 * @return {THIS}
1635 * @this {THIS}
1636 * @template THIS
1637 */
1638jspb.Message.prototype.cloneMessage = function() {
1639 return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1640};
1641
1642/**
1643 * Alias clone to cloneMessage. goog.object.unsafeClone uses clone to
1644 * efficiently copy objects. Without this alias, copying jspb messages comes
1645 * with a large performance penalty.
1646 * @return {THIS}
1647 * @this {THIS}
1648 * @template THIS
1649 */
1650jspb.Message.prototype.clone = function() {
1651 return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
1652};
1653
1654/**
1655 * Static clone function. NOTE: A type-safe method called "cloneMessage"
1656 * exists
Feng Xiaoe841bac2015-12-11 17:09:20 -08001657 * on each generated JsPb class. Do not call this function directly.
1658 * @param {!jspb.Message} msg A message to clone.
1659 * @return {!jspb.Message} A deep clone of the given message.
1660 */
1661jspb.Message.clone = function(msg) {
1662 // Although we could include the wrappers, we leave them out here.
1663 return jspb.Message.cloneMessage(msg);
1664};
1665
1666
1667/**
1668 * @param {!jspb.Message} msg A message to clone.
1669 * @return {!jspb.Message} A deep clone of the given message.
1670 * @protected
1671 */
1672jspb.Message.cloneMessage = function(msg) {
1673 // Although we could include the wrappers, we leave them out here.
1674 return new msg.constructor(jspb.Message.clone_(msg.toArray()));
1675};
1676
1677
1678/**
1679 * Takes 2 messages of the same type and copies the contents of the first
1680 * message into the second. After this the 2 messages will equals in terms of
1681 * value semantics but share no state. All data in the destination message will
1682 * be overridden.
1683 *
1684 * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
1685 * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
1686 * as its contents.
1687 * @template MESSAGE
1688 */
1689jspb.Message.copyInto = function(fromMessage, toMessage) {
1690 goog.asserts.assertInstanceof(fromMessage, jspb.Message);
1691 goog.asserts.assertInstanceof(toMessage, jspb.Message);
1692 goog.asserts.assert(fromMessage.constructor == toMessage.constructor,
1693 'Copy source and target message should have the same type.');
1694 var copyOfFrom = jspb.Message.clone(fromMessage);
1695
1696 var to = toMessage.toArray();
1697 var from = copyOfFrom.toArray();
1698
1699 // Empty destination in case it has more values at the end of the array.
1700 to.length = 0;
1701 // and then copy everything from the new to the existing message.
1702 for (var i = 0; i < from.length; i++) {
1703 to[i] = from[i];
1704 }
1705
1706 // This is either null or empty for a fresh copy.
1707 toMessage.wrappers_ = copyOfFrom.wrappers_;
1708 // Just a reference into the shared array.
1709 toMessage.extensionObject_ = copyOfFrom.extensionObject_;
1710};
1711
1712
1713/**
1714 * Helper for cloning an internal JsPb object.
1715 * @param {!Object} obj A JsPb object, eg, a field, to be cloned.
1716 * @return {!Object} A clone of the input object.
1717 * @private
1718 */
1719jspb.Message.clone_ = function(obj) {
1720 var o;
1721 if (goog.isArray(obj)) {
1722 // Allocate array of correct size.
1723 var clonedArray = new Array(obj.length);
1724 // Use array iteration where possible because it is faster than for-in.
1725 for (var i = 0; i < obj.length; i++) {
Adam Cozzette0400cca2018-03-13 16:37:29 -07001726 o = obj[i];
1727 if (o != null) {
1728 // NOTE:redundant null check existing for NTI compatibility.
1729 // see b/70515949
1730 clonedArray[i] = (typeof o == 'object') ?
1731 jspb.Message.clone_(goog.asserts.assert(o)) :
1732 o;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001733 }
1734 }
1735 return clonedArray;
1736 }
Adam Cozzetted64a2d92016-06-29 15:23:27 -07001737 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array) {
1738 return new Uint8Array(obj);
1739 }
Feng Xiaoe841bac2015-12-11 17:09:20 -08001740 var clone = {};
1741 for (var key in obj) {
Adam Cozzette0400cca2018-03-13 16:37:29 -07001742 o = obj[key];
1743 if (o != null) {
1744 // NOTE:redundant null check existing for NTI compatibility.
1745 // see b/70515949
1746 clone[key] = (typeof o == 'object') ?
1747 jspb.Message.clone_(goog.asserts.assert(o)) :
1748 o;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001749 }
1750 }
1751 return clone;
1752};
1753
1754
1755/**
1756 * Registers a JsPb message type id with its constructor.
1757 * @param {string} id The id for this type of message.
1758 * @param {Function} constructor The message constructor.
1759 */
1760jspb.Message.registerMessageType = function(id, constructor) {
1761 jspb.Message.registry_[id] = constructor;
1762 // This is needed so we can later access messageId directly on the contructor,
1763 // otherwise it is not available due to 'property collapsing' by the compiler.
Adam Cozzette0400cca2018-03-13 16:37:29 -07001764 /**
1765 * @suppress {strictMissingProperties} messageId is not defined on Function
1766 */
Feng Xiaoe841bac2015-12-11 17:09:20 -08001767 constructor.messageId = id;
1768};
1769
1770
1771/**
1772 * The registry of message ids to message constructors.
1773 * @private
1774 */
1775jspb.Message.registry_ = {};
1776
1777
1778/**
1779 * The extensions registered on MessageSet. This is a map of extension
1780 * field number to field info object. This should be considered as a
1781 * private API.
1782 *
1783 * This is similar to [jspb class name].extensions object for
1784 * non-MessageSet. We special case MessageSet so that we do not need
1785 * to goog.require MessageSet from classes that extends MessageSet.
1786 *
Adam Cozzette92a7e772017-12-01 10:05:10 -08001787 * @type {!Object<number, jspb.ExtensionFieldInfo>}
Feng Xiaoe841bac2015-12-11 17:09:20 -08001788 */
1789jspb.Message.messageSetExtensions = {};
Adam Cozzette92a7e772017-12-01 10:05:10 -08001790
1791/**
1792 * @type {!Object<number, jspb.ExtensionFieldBinaryInfo>}
1793 */
Bo Yangcc8ca5b2016-09-19 13:45:07 -07001794jspb.Message.messageSetExtensionsBinary = {};