blob: 813e6b8cd1d2f02a083c89892211fe4b15d95b0a [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
37goog.provide('jspb.ExtensionFieldInfo');
38goog.provide('jspb.Message');
39
40goog.require('goog.array');
41goog.require('goog.asserts');
Jisi Liu3b3c8ab2016-03-30 11:39:59 -070042goog.require('goog.crypt.base64');
Feng Xiaoe841bac2015-12-11 17:09:20 -080043goog.require('goog.json');
Feng Xiaoe841bac2015-12-11 17:09:20 -080044
45// Not needed in compilation units that have no protos with xids.
46goog.forwardDeclare('xid.String');
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 * @param {?function(number,?)=} opt_binaryReaderFn
87 * @param {?function(number,?)|function(number,?,?,?,?,?)=} opt_binaryWriterFn
88 * @param {?function(?,?)=} opt_binaryMessageSerializeFn
89 * @param {?function(?,?)=} opt_binaryMessageDeserializeFn
90 * @param {?boolean=} opt_isPacked
91 * @constructor
92 * @struct
93 * @template T
94 */
95jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
96 isRepeated, opt_binaryReaderFn, opt_binaryWriterFn,
97 opt_binaryMessageSerializeFn, opt_binaryMessageDeserializeFn,
98 opt_isPacked) {
99 /** @const */
100 this.fieldIndex = fieldNumber;
101 /** @const */
102 this.fieldName = fieldName;
103 /** @const */
104 this.ctor = ctor;
105 /** @const */
106 this.toObjectFn = toObjectFn;
107 /** @const */
108 this.binaryReaderFn = opt_binaryReaderFn;
109 /** @const */
110 this.binaryWriterFn = opt_binaryWriterFn;
111 /** @const */
112 this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
113 /** @const */
114 this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
115 /** @const */
116 this.isRepeated = isRepeated;
117 /** @const */
118 this.isPacked = opt_isPacked;
119};
120
121
122/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700123 * @return {boolean} Does this field represent a sub Message?
124 */
125jspb.ExtensionFieldInfo.prototype.isMessageType = function() {
126 return !!this.ctor;
127};
128
129
130/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800131 * Base class for all JsPb messages.
132 * @constructor
133 * @struct
134 */
135jspb.Message = function() {
136};
137
138
139/**
140 * @define {boolean} Whether to generate toObject methods for objects. Turn
141 * this off, if you do not want toObject to be ever used in your project.
142 * When turning off this flag, consider adding a conformance test that bans
143 * calling toObject. Enabling this will disable the JSCompiler's ability to
144 * dead code eliminate fields used in protocol buffers that are never used
145 * in an application.
146 */
147goog.define('jspb.Message.GENERATE_TO_OBJECT', true);
148
149
150/**
151 * @define {boolean} Whether to generate fromObject methods for objects. Turn
152 * this off, if you do not want fromObject to be ever used in your project.
153 * When turning off this flag, consider adding a conformance test that bans
154 * calling fromObject. Enabling this might disable the JSCompiler's ability
155 * to dead code eliminate fields used in protocol buffers that are never
156 * used in an application.
157 * NOTE: By default no protos actually have a fromObject method. You need to
158 * add the jspb.generate_from_object options to the proto definition to
159 * activate the feature.
160 * By default this is enabled for test code only.
161 */
162goog.define('jspb.Message.GENERATE_FROM_OBJECT', !goog.DISALLOW_TEST_ONLY_CODE);
163
164
165/**
166 * @define {boolean} Turning on this flag does NOT change the behavior of JSPB
167 * and only affects private internal state. It may, however, break some
168 * tests that use naive deeply-equals algorithms, because using a proto
169 * mutates its internal state.
170 * Projects are advised to turn this flag always on.
171 */
172goog.define('jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS', COMPILED);
173// TODO(b/19419436) Turn this on by default.
174
175
176/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700177 * Does this browser support Uint8Aray typed arrays?
178 * @type {boolean}
179 * @private
180 */
181jspb.Message.SUPPORTS_UINT8ARRAY_ = (typeof Uint8Array == 'function');
182
183
184/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800185 * The internal data array.
186 * @type {!Array}
187 * @protected
188 */
189jspb.Message.prototype.array;
190
191
192/**
193 * Wrappers are the constructed instances of message-type fields. They are built
194 * on demand from the raw array data. Includes message fields, repeated message
195 * fields and extension message fields. Indexed by field number.
196 * @type {Object}
197 * @private
198 */
199jspb.Message.prototype.wrappers_;
200
201
202/**
203 * The object that contains extension fields, if any. This is an object that
204 * maps from a proto field number to the field's value.
205 * @type {Object}
206 * @private
207 */
208jspb.Message.prototype.extensionObject_;
209
210
211/**
212 * Non-extension fields with a field number at or above the pivot are
213 * stored in the extension object (in addition to all extension fields).
214 * @type {number}
215 * @private
216 */
217jspb.Message.prototype.pivot_;
218
219
220/**
221 * The JsPb message_id of this proto.
222 * @type {string|undefined} the message id or undefined if this message
223 * has no id.
224 * @private
225 */
226jspb.Message.prototype.messageId_;
227
228
229/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700230 * Repeated float or double fields which have been converted to include only
231 * numbers and not strings holding "NaN", "Infinity" and "-Infinity".
232 * @private {!Object<number,boolean>|undefined}
233 */
234jspb.Message.prototype.convertedFloatingPointFields_;
235
236
237/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800238 * The xid of this proto type (The same for all instances of a proto). Provides
239 * a way to identify a proto by stable obfuscated name.
240 * @see {xid}.
241 * Available if {@link jspb.generate_xid} is added as a Message option to
242 * a protocol buffer.
243 * @const {!xid.String|undefined} The xid or undefined if message is
244 * annotated to generate the xid.
245 */
246jspb.Message.prototype.messageXid;
247
248
249
250/**
251 * Returns the JsPb message_id of this proto.
252 * @return {string|undefined} the message id or undefined if this message
253 * has no id.
254 */
255jspb.Message.prototype.getJsPbMessageId = function() {
256 return this.messageId_;
257};
258
259
260/**
261 * An offset applied to lookups into this.array to account for the presence or
262 * absence of a messageId at position 0. For response messages, this will be 0.
263 * Otherwise, it will be -1 so that the first array position is not wasted.
264 * @type {number}
265 * @private
266 */
267jspb.Message.prototype.arrayIndexOffset_;
268
269
270/**
271 * Returns the index into msg.array at which the proto field with tag number
272 * fieldNumber will be located.
273 * @param {!jspb.Message} msg Message for which we're calculating an index.
274 * @param {number} fieldNumber The field number.
275 * @return {number} The index.
276 * @private
277 */
278jspb.Message.getIndex_ = function(msg, fieldNumber) {
279 return fieldNumber + msg.arrayIndexOffset_;
280};
281
282
283/**
284 * Initializes a JsPb Message.
285 * @param {!jspb.Message} msg The JsPb proto to modify.
286 * @param {Array|undefined} data An initial data array.
287 * @param {string|number} messageId For response messages, the message id or ''
288 * if no message id is specified. For non-response messages, 0.
289 * @param {number} suggestedPivot The field number at which to start putting
290 * fields into the extension object. This is only used if data does not
291 * contain an extension object already. -1 if no extension object is
292 * required for this message type.
293 * @param {Array<number>} repeatedFields The message's repeated fields.
294 * @param {Array<!Array<number>>=} opt_oneofFields The fields belonging to
295 * each of the message's oneof unions.
296 * @protected
297 */
298jspb.Message.initialize = function(
299 msg, data, messageId, suggestedPivot, repeatedFields, opt_oneofFields) {
300 msg.wrappers_ = jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ? null : {};
301 if (!data) {
302 data = messageId ? [messageId] : [];
303 }
304 msg.messageId_ = messageId ? String(messageId) : undefined;
305 // If the messageId is 0, this message is not a response message, so we shift
306 // array indices down by 1 so as not to waste the first position in the array,
307 // which would otherwise go unused.
308 msg.arrayIndexOffset_ = messageId === 0 ? -1 : 0;
309 msg.array = data;
310 jspb.Message.materializeExtensionObject_(msg, suggestedPivot);
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700311 msg.convertedFloatingPointFields_ = {};
312
Feng Xiaoe841bac2015-12-11 17:09:20 -0800313 if (repeatedFields) {
314 for (var i = 0; i < repeatedFields.length; i++) {
315 var fieldNumber = repeatedFields[i];
316 if (fieldNumber < msg.pivot_) {
317 var index = jspb.Message.getIndex_(msg, fieldNumber);
318 msg.array[index] = msg.array[index] ||
319 (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ?
320 jspb.Message.EMPTY_LIST_SENTINEL_ :
321 []);
322 } else {
323 msg.extensionObject_[fieldNumber] =
324 msg.extensionObject_[fieldNumber] ||
325 (jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS ?
326 jspb.Message.EMPTY_LIST_SENTINEL_ :
327 []);
328 }
329 }
330 }
331
332 if (opt_oneofFields && opt_oneofFields.length) {
333 // Compute the oneof case for each union. This ensures only one value is
334 // set in the union.
335 goog.array.forEach(
336 opt_oneofFields, goog.partial(jspb.Message.computeOneofCase, msg));
337 }
338};
339
340
341/**
342 * Used to mark empty repeated fields. Serializes to null when serialized
343 * to JSON.
344 * When reading a repeated field readers must check the return value against
345 * this value and return and replace it with a new empty array if it is
346 * present.
347 * @private @const {!Object}
348 */
349jspb.Message.EMPTY_LIST_SENTINEL_ = goog.DEBUG && Object.freeze ?
350 Object.freeze([]) :
351 [];
352
353
354/**
355 * Ensures that the array contains an extension object if necessary.
356 * If the array contains an extension object in its last position, then the
357 * object is kept in place and its position is used as the pivot. If not, then
358 * create an extension object using suggestedPivot. If suggestedPivot is -1,
359 * we don't have an extension object at all, in which case all fields are stored
360 * in the array.
361 * @param {!jspb.Message} msg The JsPb proto to modify.
362 * @param {number} suggestedPivot See description for initialize().
363 * @private
364 */
365jspb.Message.materializeExtensionObject_ = function(msg, suggestedPivot) {
366 if (msg.array.length) {
367 var foundIndex = msg.array.length - 1;
368 var obj = msg.array[foundIndex];
369 // Normal fields are never objects, so we can be sure that if we find an
370 // object here, then it's the extension object. However, we must ensure that
371 // the object is not an array, since arrays are valid field values.
372 // NOTE(lukestebbing): We avoid looking at .length to avoid a JIT bug
373 // in Safari on iOS 8. See the description of CL/86511464 for details.
374 if (obj && typeof obj == 'object' && !goog.isArray(obj)) {
375 msg.pivot_ = foundIndex - msg.arrayIndexOffset_;
376 msg.extensionObject_ = obj;
377 return;
378 }
379 }
380 // This complexity exists because we keep all extension fields in the
381 // extensionObject_ regardless of proto field number. Changing this would
382 // simplify the code here, but it would require changing the serialization
383 // format from the server, which is not backwards compatible.
384 // TODO(jshneier): Should we just treat extension fields the same as
385 // non-extension fields, and select whether they appear in the object or in
386 // the array purely based on tag number? This would allow simplifying all the
387 // get/setExtension logic, but it would require the breaking change described
388 // above.
389 if (suggestedPivot > -1) {
390 msg.pivot_ = suggestedPivot;
391 var pivotIndex = jspb.Message.getIndex_(msg, suggestedPivot);
392 if (!jspb.Message.MINIMIZE_MEMORY_ALLOCATIONS) {
393 msg.extensionObject_ = msg.array[pivotIndex] = {};
394 } else {
395 // Initialize to null to avoid changing the shape of the proto when it
396 // gets eventually set.
397 msg.extensionObject_ = null;
398 }
399 } else {
400 msg.pivot_ = Number.MAX_VALUE;
401 }
402};
403
404
405/**
406 * Creates an empty extensionObject_ if non exists.
407 * @param {!jspb.Message} msg The JsPb proto to modify.
408 * @private
409 */
410jspb.Message.maybeInitEmptyExtensionObject_ = function(msg) {
411 var pivotIndex = jspb.Message.getIndex_(msg, msg.pivot_);
412 if (!msg.array[pivotIndex]) {
413 msg.extensionObject_ = msg.array[pivotIndex] = {};
414 }
415};
416
417
418/**
419 * Converts a JsPb repeated message field into an object list.
420 * @param {!Array<T>} field The repeated message field to be
421 * converted.
422 * @param {?function(boolean=): Object|
423 * function((boolean|undefined),T): Object} toObjectFn The toObject
424 * function for this field. We need to pass this for effective dead code
425 * removal.
426 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
427 * for transitional soy proto support: http://goto/soy-param-migration
428 * @return {!Array<Object>} An array of converted message objects.
429 * @template T
430 */
431jspb.Message.toObjectList = function(field, toObjectFn, opt_includeInstance) {
432 // Not using goog.array.map in the generated code to keep it small.
433 // And not using it here to avoid a function call.
434 var result = [];
435 for (var i = 0; i < field.length; i++) {
436 result[i] = toObjectFn.call(field[i], opt_includeInstance,
437 /** @type {!jspb.Message} */ (field[i]));
438 }
439 return result;
440};
441
442
443/**
444 * Adds a proto's extension data to a Soy rendering object.
445 * @param {!jspb.Message} proto The proto whose extensions to convert.
446 * @param {!Object} obj The Soy object to add converted extension data to.
447 * @param {!Object} extensions The proto class' registered extensions.
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700448 * @param {function(this:?, jspb.ExtensionFieldInfo) : *} getExtensionFn
449 * The proto class' getExtension function. Passed for effective dead code
450 * removal.
Feng Xiaoe841bac2015-12-11 17:09:20 -0800451 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
452 * for transitional soy proto support: http://goto/soy-param-migration
453 */
454jspb.Message.toObjectExtension = function(proto, obj, extensions,
455 getExtensionFn, opt_includeInstance) {
456 for (var fieldNumber in extensions) {
457 var fieldInfo = extensions[fieldNumber];
458 var value = getExtensionFn.call(proto, fieldInfo);
459 if (value) {
460 for (var name in fieldInfo.fieldName) {
461 if (fieldInfo.fieldName.hasOwnProperty(name)) {
462 break; // the compiled field name
463 }
464 }
465 if (!fieldInfo.toObjectFn) {
466 obj[name] = value;
467 } else {
468 if (fieldInfo.isRepeated) {
469 obj[name] = jspb.Message.toObjectList(
470 /** @type {!Array<jspb.Message>} */ (value),
471 fieldInfo.toObjectFn, opt_includeInstance);
472 } else {
473 obj[name] = fieldInfo.toObjectFn(opt_includeInstance, value);
474 }
475 }
476 }
477 }
478};
479
480
481/**
482 * Writes a proto's extension data to a binary-format output stream.
483 * @param {!jspb.Message} proto The proto whose extensions to convert.
484 * @param {*} writer The binary-format writer to write to.
485 * @param {!Object} extensions The proto class' registered extensions.
486 * @param {function(jspb.ExtensionFieldInfo) : *} getExtensionFn The proto
487 * class' getExtension function. Passed for effective dead code removal.
488 */
489jspb.Message.serializeBinaryExtensions = function(proto, writer, extensions,
490 getExtensionFn) {
491 for (var fieldNumber in extensions) {
492 var fieldInfo = extensions[fieldNumber];
493 // The old codegen doesn't add the extra fields to ExtensionFieldInfo, so we
494 // need to gracefully error-out here rather than produce a null dereference
495 // below.
496 if (!fieldInfo.binaryWriterFn) {
497 throw new Error('Message extension present that was generated ' +
498 'without binary serialization support');
499 }
500 var value = getExtensionFn.call(proto, fieldInfo);
501 if (value) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700502 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800503 // If the message type of the extension was generated without binary
504 // support, there may not be a binary message serializer function, and
505 // we can't know when we codegen the extending message that the extended
506 // message may require binary support, so we can *only* catch this error
507 // here, at runtime (and this decoupled codegen is the whole point of
508 // extensions!).
509 if (fieldInfo.binaryMessageSerializeFn) {
510 fieldInfo.binaryWriterFn.call(writer, fieldInfo.fieldIndex,
511 value, fieldInfo.binaryMessageSerializeFn);
512 } else {
513 throw new Error('Message extension present holding submessage ' +
514 'without binary support enabled, and message is ' +
515 'being serialized to binary format');
516 }
517 } else {
518 fieldInfo.binaryWriterFn.call(writer, fieldInfo.fieldIndex, value);
519 }
520 }
521 }
522};
523
524
525/**
526 * Reads an extension field from the given reader and, if a valid extension,
527 * sets the extension value.
528 * @param {!jspb.Message} msg A jspb proto.
529 * @param {{skipField:function(),getFieldNumber:function():number}} reader
530 * @param {!Object} extensions The extensions object.
531 * @param {function(jspb.ExtensionFieldInfo)} getExtensionFn
532 * @param {function(jspb.ExtensionFieldInfo, ?)} setExtensionFn
533 */
534jspb.Message.readBinaryExtension = function(msg, reader, extensions,
535 getExtensionFn, setExtensionFn) {
536 var fieldInfo = extensions[reader.getFieldNumber()];
537 if (!fieldInfo) {
538 reader.skipField();
539 return;
540 }
541 if (!fieldInfo.binaryReaderFn) {
542 throw new Error('Deserializing extension whose generated code does not ' +
543 'support binary format');
544 }
545
546 var value;
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700547 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800548 value = new fieldInfo.ctor();
549 fieldInfo.binaryReaderFn.call(
550 reader, value, fieldInfo.binaryMessageDeserializeFn);
551 } else {
552 // All other types.
553 value = fieldInfo.binaryReaderFn.call(reader);
554 }
555
556 if (fieldInfo.isRepeated && !fieldInfo.isPacked) {
557 var currentList = getExtensionFn.call(msg, fieldInfo);
558 if (!currentList) {
559 setExtensionFn.call(msg, fieldInfo, [value]);
560 } else {
561 currentList.push(value);
562 }
563 } else {
564 setExtensionFn.call(msg, fieldInfo, value);
565 }
566};
567
568
569/**
570 * Gets the value of a non-extension field.
571 * @param {!jspb.Message} msg A jspb proto.
572 * @param {number} fieldNumber The field number.
573 * @return {string|number|boolean|Uint8Array|Array|null|undefined}
574 * The field's value.
575 * @protected
576 */
577jspb.Message.getField = function(msg, fieldNumber) {
578 if (fieldNumber < msg.pivot_) {
579 var index = jspb.Message.getIndex_(msg, fieldNumber);
580 var val = msg.array[index];
581 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
582 return msg.array[index] = [];
583 }
584 return val;
585 } else {
586 var val = msg.extensionObject_[fieldNumber];
587 if (val === jspb.Message.EMPTY_LIST_SENTINEL_) {
588 return msg.extensionObject_[fieldNumber] = [];
589 }
590 return val;
591 }
592};
593
594
595/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700596 * Gets the value of an optional float or double field.
597 * @param {!jspb.Message} msg A jspb proto.
598 * @param {number} fieldNumber The field number.
599 * @return {?number|undefined} The field's value.
600 * @protected
601 */
602jspb.Message.getOptionalFloatingPointField = function(msg, fieldNumber) {
603 var value = jspb.Message.getField(msg, fieldNumber);
604 // Converts "NaN", "Infinity" and "-Infinity" to their corresponding numbers.
605 return value == null ? value : +value;
606};
607
608
609/**
610 * Gets the value of a repeated float or double field.
611 * @param {!jspb.Message} msg A jspb proto.
612 * @param {number} fieldNumber The field number.
613 * @return {!Array<number>} The field's value.
614 * @protected
615 */
616jspb.Message.getRepeatedFloatingPointField = function(msg, fieldNumber) {
617 var values = jspb.Message.getField(msg, fieldNumber);
618 if (!msg.convertedFloatingPointFields_) {
619 msg.convertedFloatingPointFields_ = {};
620 }
621 if (!msg.convertedFloatingPointFields_[fieldNumber]) {
622 for (var i = 0; i < values.length; i++) {
623 // Converts "NaN", "Infinity" and "-Infinity" to their corresponding
624 // numbers.
625 values[i] = +values[i];
626 }
627 msg.convertedFloatingPointFields_[fieldNumber] = true;
628 }
629 return /** @type {!Array<number>} */ (values);
630};
631
632
633/**
634 * Coerce a 'bytes' field to a base 64 string.
635 * @param {string|Uint8Array|null} value
636 * @return {?string} The field's coerced value.
637 */
638jspb.Message.bytesAsB64 = function(value) {
639 if (value == null || goog.isString(value)) {
640 return value;
641 }
642 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && value instanceof Uint8Array) {
643 return goog.crypt.base64.encodeByteArray(value);
644 }
645 goog.asserts.fail('Cannot coerce to b64 string: ' + goog.typeOf(value));
646 return null;
647};
648
649
650/**
651 * Coerce a 'bytes' field to a Uint8Array byte buffer.
652 * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
653 * Mini. @see http://caniuse.com/Uint8Array
654 * @param {string|Uint8Array|null} value
655 * @return {?Uint8Array} The field's coerced value.
656 */
657jspb.Message.bytesAsU8 = function(value) {
658 if (value == null || value instanceof Uint8Array) {
659 return value;
660 }
661 if (goog.isString(value)) {
662 return goog.crypt.base64.decodeStringToUint8Array(value);
663 }
664 goog.asserts.fail('Cannot coerce to Uint8Array: ' + goog.typeOf(value));
665 return null;
666};
667
668
669/**
670 * Coerce a repeated 'bytes' field to an array of base 64 strings.
671 * Note: the returned array should be treated as immutable.
672 * @param {!Array<string>|!Array<!Uint8Array>} value
673 * @return {!Array<string?>} The field's coerced value.
674 */
675jspb.Message.bytesListAsB64 = function(value) {
676 jspb.Message.assertConsistentTypes_(value);
677 if (!value.length || goog.isString(value[0])) {
678 return /** @type {!Array<string>} */ (value);
679 }
680 return goog.array.map(value, jspb.Message.bytesAsB64);
681};
682
683
684/**
685 * Coerce a repeated 'bytes' field to an array of Uint8Array byte buffers.
686 * Note: the returned array should be treated as immutable.
687 * Note that Uint8Array is not supported on IE versions before 10 nor on Opera
688 * Mini. @see http://caniuse.com/Uint8Array
689 * @param {!Array<string>|!Array<!Uint8Array>} value
690 * @return {!Array<Uint8Array?>} The field's coerced value.
691 */
692jspb.Message.bytesListAsU8 = function(value) {
693 jspb.Message.assertConsistentTypes_(value);
694 if (!value.length || value[0] instanceof Uint8Array) {
695 return /** @type {!Array<!Uint8Array>} */ (value);
696 }
697 return goog.array.map(value, jspb.Message.bytesAsU8);
698};
699
700
701/**
702 * Asserts that all elements of an array are of the same type.
703 * @param {Array?} array The array to test.
704 * @private
705 */
706jspb.Message.assertConsistentTypes_ = function(array) {
707 if (goog.DEBUG && array && array.length > 1) {
708 var expected = goog.typeOf(array[0]);
709 goog.array.forEach(array, function(e) {
710 if (goog.typeOf(e) != expected) {
711 goog.asserts.fail('Inconsistent type in JSPB repeated field array. ' +
712 'Got ' + goog.typeOf(e) + ' expected ' + expected);
713 }
714 });
715 }
716};
717
718
719/**
Feng Xiaoe841bac2015-12-11 17:09:20 -0800720 * Gets the value of a non-extension primitive field, with proto3 (non-nullable
721 * primitives) semantics. Returns `defaultValue` if the field is not otherwise
722 * set.
723 * @template T
724 * @param {!jspb.Message} msg A jspb proto.
725 * @param {number} fieldNumber The field number.
726 * @param {T} defaultValue The default value.
727 * @return {T} The field's value.
728 * @protected
729 */
730jspb.Message.getFieldProto3 = function(msg, fieldNumber, defaultValue) {
731 var value = jspb.Message.getField(msg, fieldNumber);
732 if (value == null) {
733 return defaultValue;
734 } else {
735 return value;
736 }
737};
738
739
740/**
741 * Sets the value of a non-extension field.
742 * @param {!jspb.Message} msg A jspb proto.
743 * @param {number} fieldNumber The field number.
744 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
745 * @protected
746 */
747jspb.Message.setField = function(msg, fieldNumber, value) {
748 if (fieldNumber < msg.pivot_) {
749 msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
750 } else {
751 msg.extensionObject_[fieldNumber] = value;
752 }
753};
754
755
756/**
757 * Sets the value of a field in a oneof union and clears all other fields in
758 * the union.
759 * @param {!jspb.Message} msg A jspb proto.
760 * @param {number} fieldNumber The field number.
761 * @param {!Array<number>} oneof The fields belonging to the union.
762 * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
763 * @protected
764 */
765jspb.Message.setOneofField = function(msg, fieldNumber, oneof, value) {
766 var currentCase = jspb.Message.computeOneofCase(msg, oneof);
767 if (currentCase && currentCase !== fieldNumber && value !== undefined) {
768 if (msg.wrappers_ && currentCase in msg.wrappers_) {
769 msg.wrappers_[currentCase] = undefined;
770 }
771 jspb.Message.setField(msg, currentCase, undefined);
772 }
773 jspb.Message.setField(msg, fieldNumber, value);
774};
775
776
777/**
778 * Computes the selection in a oneof group for the given message, ensuring
779 * only one field is set in the process.
780 *
781 * According to the protobuf language guide (
782 * https://developers.google.com/protocol-buffers/docs/proto#oneof), "if the
783 * parser encounters multiple members of the same oneof on the wire, only the
784 * last member seen is used in the parsed message." Since JSPB serializes
785 * messages to a JSON array, the "last member seen" will always be the field
786 * with the greatest field number (directly corresponding to the greatest
787 * array index).
788 *
789 * @param {!jspb.Message} msg A jspb proto.
790 * @param {!Array<number>} oneof The field numbers belonging to the union.
791 * @return {number} The field number currently set in the union, or 0 if none.
792 * @protected
793 */
794jspb.Message.computeOneofCase = function(msg, oneof) {
795 var oneofField;
796 var oneofValue;
797
798 goog.array.forEach(oneof, function(fieldNumber) {
799 var value = jspb.Message.getField(msg, fieldNumber);
800 if (goog.isDefAndNotNull(value)) {
801 oneofField = fieldNumber;
802 oneofValue = value;
803 jspb.Message.setField(msg, fieldNumber, undefined);
804 }
805 });
806
807 if (oneofField) {
808 // NB: We know the value is unique, so we can call jspb.Message.setField
809 // directly instead of jpsb.Message.setOneofField. Also, setOneofField
810 // calls this function.
811 jspb.Message.setField(msg, oneofField, oneofValue);
812 return oneofField;
813 }
814
815 return 0;
816};
817
818
819/**
820 * Gets and wraps a proto field on access.
821 * @param {!jspb.Message} msg A jspb proto.
822 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
823 * @param {number} fieldNumber The field number.
824 * @param {number=} opt_required True (1) if this is a required field.
825 * @return {jspb.Message} The field as a jspb proto.
826 * @protected
827 */
828jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
829 // TODO(mwr): Consider copying data and/or arrays.
830 if (!msg.wrappers_) {
831 msg.wrappers_ = {};
832 }
833 if (!msg.wrappers_[fieldNumber]) {
834 var data = /** @type {Array} */ (jspb.Message.getField(msg, fieldNumber));
835 if (opt_required || data) {
836 // TODO(mwr): Remove existence test for always valid default protos.
837 msg.wrappers_[fieldNumber] = new ctor(data);
838 }
839 }
840 return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
841};
842
843
844/**
845 * Gets and wraps a repeated proto field on access.
846 * @param {!jspb.Message} msg A jspb proto.
847 * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
848 * @param {number} fieldNumber The field number.
849 * @return {Array<!jspb.Message>} The repeated field as an array of protos.
850 * @protected
851 */
852jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
853 if (!msg.wrappers_) {
854 msg.wrappers_ = {};
855 }
856 if (!msg.wrappers_[fieldNumber]) {
857 var data = jspb.Message.getField(msg, fieldNumber);
858 for (var wrappers = [], i = 0; i < data.length; i++) {
859 wrappers[i] = new ctor(data[i]);
860 }
861 msg.wrappers_[fieldNumber] = wrappers;
862 }
863 var val = msg.wrappers_[fieldNumber];
864 if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
865 val = msg.wrappers_[fieldNumber] = [];
866 }
867 return /** @type {Array<!jspb.Message>} */ (val);
868};
869
870
871/**
872 * Sets a proto field and syncs it to the backing array.
873 * @param {!jspb.Message} msg A jspb proto.
874 * @param {number} fieldNumber The field number.
875 * @param {jspb.Message|undefined} value A new value for this proto field.
876 * @protected
877 */
878jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
879 if (!msg.wrappers_) {
880 msg.wrappers_ = {};
881 }
882 var data = value ? value.toArray() : value;
883 msg.wrappers_[fieldNumber] = value;
884 jspb.Message.setField(msg, fieldNumber, data);
885};
886
887
888/**
889 * Sets a proto field in a oneof union and syncs it to the backing array.
890 * @param {!jspb.Message} msg A jspb proto.
891 * @param {number} fieldNumber The field number.
892 * @param {!Array<number>} oneof The fields belonging to the union.
893 * @param {jspb.Message|undefined} value A new value for this proto field.
894 * @protected
895 */
896jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
897 if (!msg.wrappers_) {
898 msg.wrappers_ = {};
899 }
900 var data = value ? value.toArray() : value;
901 msg.wrappers_[fieldNumber] = value;
902 jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
903};
904
905
906/**
907 * Sets a repeated proto field and syncs it to the backing array.
908 * @param {!jspb.Message} msg A jspb proto.
909 * @param {number} fieldNumber The field number.
910 * @param {Array<!jspb.Message>|undefined} value An array of protos.
911 * @protected
912 */
913jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
914 if (!msg.wrappers_) {
915 msg.wrappers_ = {};
916 }
917 value = value || [];
918 for (var data = [], i = 0; i < value.length; i++) {
919 data[i] = value[i].toArray();
920 }
921 msg.wrappers_[fieldNumber] = value;
922 jspb.Message.setField(msg, fieldNumber, data);
923};
924
925
926/**
927 * Converts a JsPb repeated message field into a map. The map will contain
928 * protos unless an optional toObject function is given, in which case it will
929 * contain objects suitable for Soy rendering.
930 * @param {!Array<T>} field The repeated message field to be
931 * converted.
932 * @param {function() : string?} mapKeyGetterFn The function to get the key of
933 * the map.
934 * @param {?function(boolean=): Object|
935 * function((boolean|undefined),T): Object} opt_toObjectFn The
936 * toObject function for this field. We need to pass this for effective
937 * dead code removal.
938 * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
939 * for transitional soy proto support: http://goto/soy-param-migration
940 * @return {!Object.<string, Object>} A map of proto or Soy objects.
941 * @template T
942 */
943jspb.Message.toMap = function(
944 field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
945 var result = {};
946 for (var i = 0; i < field.length; i++) {
947 result[mapKeyGetterFn.call(field[i])] = opt_toObjectFn ?
948 opt_toObjectFn.call(field[i], opt_includeInstance,
949 /** @type {!jspb.Message} */ (field[i])) : field[i];
950 }
951 return result;
952};
953
954
955/**
956 * Returns the internal array of this proto.
957 * <p>Note: If you use this array to construct a second proto, the content
958 * would then be partially shared between the two protos.
959 * @return {!Array} The proto represented as an array.
960 */
961jspb.Message.prototype.toArray = function() {
962 return this.array;
963};
964
965
966
967
968/**
969 * Creates a string representation of the internal data array of this proto.
970 * <p>NOTE: This string is *not* suitable for use in server requests.
971 * @return {string} A string representation of this proto.
972 * @override
973 */
974jspb.Message.prototype.toString = function() {
975 return this.array.toString();
976};
977
978
979/**
980 * Gets the value of the extension field from the extended object.
981 * @param {jspb.ExtensionFieldInfo.<T>} fieldInfo Specifies the field to get.
982 * @return {T} The value of the field.
983 * @template T
984 */
985jspb.Message.prototype.getExtension = function(fieldInfo) {
986 if (!this.extensionObject_) {
987 return undefined;
988 }
989 if (!this.wrappers_) {
990 this.wrappers_ = {};
991 }
992 var fieldNumber = fieldInfo.fieldIndex;
993 if (fieldInfo.isRepeated) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -0700994 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -0800995 if (!this.wrappers_[fieldNumber]) {
996 this.wrappers_[fieldNumber] =
997 goog.array.map(this.extensionObject_[fieldNumber] || [],
998 function(arr) {
999 return new fieldInfo.ctor(arr);
1000 });
1001 }
1002 return this.wrappers_[fieldNumber];
1003 } else {
1004 return this.extensionObject_[fieldNumber];
1005 }
1006 } else {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001007 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001008 if (!this.wrappers_[fieldNumber] && this.extensionObject_[fieldNumber]) {
1009 this.wrappers_[fieldNumber] = new fieldInfo.ctor(
1010 /** @type {Array|undefined} */ (
1011 this.extensionObject_[fieldNumber]));
1012 }
1013 return this.wrappers_[fieldNumber];
1014 } else {
1015 return this.extensionObject_[fieldNumber];
1016 }
1017 }
1018};
1019
1020
1021/**
1022 * Sets the value of the extension field in the extended object.
1023 * @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001024 * @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
1025 * to set.
Feng Xiaoe841bac2015-12-11 17:09:20 -08001026 */
1027jspb.Message.prototype.setExtension = function(fieldInfo, value) {
1028 if (!this.wrappers_) {
1029 this.wrappers_ = {};
1030 }
1031 jspb.Message.maybeInitEmptyExtensionObject_(this);
1032 var fieldNumber = fieldInfo.fieldIndex;
1033 if (fieldInfo.isRepeated) {
1034 value = value || [];
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001035 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001036 this.wrappers_[fieldNumber] = value;
1037 this.extensionObject_[fieldNumber] = goog.array.map(
1038 /** @type {Array<jspb.Message>} */ (value), function(msg) {
1039 return msg.toArray();
1040 });
1041 } else {
1042 this.extensionObject_[fieldNumber] = value;
1043 }
1044 } else {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001045 if (fieldInfo.isMessageType()) {
Feng Xiaoe841bac2015-12-11 17:09:20 -08001046 this.wrappers_[fieldNumber] = value;
1047 this.extensionObject_[fieldNumber] = value ? value.toArray() : value;
1048 } else {
1049 this.extensionObject_[fieldNumber] = value;
1050 }
1051 }
1052};
1053
1054
1055/**
1056 * Creates a difference object between two messages.
1057 *
1058 * The result will contain the top-level fields of m2 that differ from those of
1059 * m1 at any level of nesting. No data is cloned, the result object will
1060 * share its top-level elements with m2 (but not with m1).
1061 *
1062 * Note that repeated fields should not have null/undefined elements, but if
1063 * they do, this operation will treat repeated fields of different length as
1064 * the same if the only difference between them is due to trailing
1065 * null/undefined values.
1066 *
1067 * @param {!jspb.Message} m1 The first message object.
1068 * @param {!jspb.Message} m2 The second message object.
1069 * @return {!jspb.Message} The difference returned as a proto message.
1070 * Note that the returned message may be missing required fields. This is
1071 * currently tolerated in Js, but would cause an error if you tried to
1072 * send such a proto to the server. You can access the raw difference
1073 * array with result.toArray().
1074 * @throws {Error} If the messages are responses with different types.
1075 */
1076jspb.Message.difference = function(m1, m2) {
1077 if (!(m1 instanceof m2.constructor)) {
1078 throw new Error('Messages have different types.');
1079 }
1080 var arr1 = m1.toArray();
1081 var arr2 = m2.toArray();
1082 var res = [];
1083 var start = 0;
1084 var length = arr1.length > arr2.length ? arr1.length : arr2.length;
1085 if (m1.getJsPbMessageId()) {
1086 res[0] = m1.getJsPbMessageId();
1087 start = 1;
1088 }
1089 for (var i = start; i < length; i++) {
1090 if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
1091 res[i] = arr2[i];
1092 }
1093 }
1094 return new m1.constructor(res);
1095};
1096
1097
1098/**
1099 * Tests whether two messages are equal.
1100 * @param {jspb.Message|undefined} m1 The first message object.
1101 * @param {jspb.Message|undefined} m2 The second message object.
1102 * @return {boolean} true if both messages are null/undefined, or if both are
1103 * of the same type and have the same field values.
1104 */
1105jspb.Message.equals = function(m1, m2) {
1106 return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
1107 jspb.Message.compareFields(m1.toArray(), m2.toArray()));
1108};
1109
1110
1111/**
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001112 * Compares two message extension fields recursively.
1113 * @param {!Object} extension1 The first field.
1114 * @param {!Object} extension2 The second field.
1115 * @return {boolean} true if the extensions are null/undefined, or otherwise
1116 * equal.
1117 */
1118jspb.Message.compareExtensions = function(extension1, extension2) {
1119 extension1 = extension1 || {};
1120 extension2 = extension2 || {};
1121
1122 var keys = {};
1123 for (var name in extension1) {
1124 keys[name] = 0;
1125 }
1126 for (var name in extension2) {
1127 keys[name] = 0;
1128 }
1129 for (name in keys) {
1130 if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
1131 return false;
1132 }
1133 }
1134 return true;
1135};
1136
1137
1138/**
Feng Xiaoe841bac2015-12-11 17:09:20 -08001139 * Compares two message fields recursively.
1140 * @param {*} field1 The first field.
1141 * @param {*} field2 The second field.
1142 * @return {boolean} true if the fields are null/undefined, or otherwise equal.
1143 */
1144jspb.Message.compareFields = function(field1, field2) {
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001145 // If the fields are trivially equal, they're equal.
1146 if (field1 == field2) return true;
1147
1148 // If the fields aren't trivially equal and one of them isn't an object,
1149 // they can't possibly be equal.
1150 if (!goog.isObject(field1) || !goog.isObject(field2)) {
1151 return false;
1152 }
1153
1154 // We have two objects. If they're different types, they're not equal.
1155 field1 = /** @type {!Object} */(field1);
1156 field2 = /** @type {!Object} */(field2);
1157 if (field1.constructor != field2.constructor) return false;
1158
1159 // If both are Uint8Arrays, compare them element-by-element.
1160 if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
1161 var bytes1 = /** @type {!Uint8Array} */(field1);
1162 var bytes2 = /** @type {!Uint8Array} */(field2);
1163 if (bytes1.length != bytes2.length) return false;
1164 for (var i = 0; i < bytes1.length; i++) {
1165 if (bytes1[i] != bytes2[i]) return false;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001166 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001167 return true;
1168 }
1169
1170 // If they're both Arrays, compare them element by element except for the
1171 // optional extension objects at the end, which we compare separately.
1172 if (field1.constructor === Array) {
1173 var extension1 = undefined;
1174 var extension2 = undefined;
1175
1176 var length = Math.max(field1.length, field2.length);
1177 for (var i = 0; i < length; i++) {
1178 var val1 = field1[i];
1179 var val2 = field2[i];
1180
1181 if (val1 && (val1.constructor == Object)) {
1182 goog.asserts.assert(extension1 === undefined);
1183 goog.asserts.assert(i === field1.length - 1);
1184 extension1 = val1;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001185 val1 = undefined;
1186 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001187
1188 if (val2 && (val2.constructor == Object)) {
1189 goog.asserts.assert(extension2 === undefined);
1190 goog.asserts.assert(i === field2.length - 1);
1191 extension2 = val2;
Feng Xiaoe841bac2015-12-11 17:09:20 -08001192 val2 = undefined;
1193 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001194
Feng Xiaoe841bac2015-12-11 17:09:20 -08001195 if (!jspb.Message.compareFields(val1, val2)) {
1196 return false;
1197 }
1198 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001199
1200 if (extension1 || extension2) {
1201 extension1 = extension1 || {};
1202 extension2 = extension2 || {};
1203 return jspb.Message.compareExtensions(extension1, extension2);
Feng Xiaoe841bac2015-12-11 17:09:20 -08001204 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001205
Feng Xiaoe841bac2015-12-11 17:09:20 -08001206 return true;
1207 }
Jisi Liu3b3c8ab2016-03-30 11:39:59 -07001208
1209 // If they're both plain Objects (i.e. extensions), compare them as
1210 // extensions.
1211 if (field1.constructor === Object) {
1212 return jspb.Message.compareExtensions(field1, field2);
1213 }
1214
1215 throw new Error('Invalid type in JSPB array');
Feng Xiaoe841bac2015-12-11 17:09:20 -08001216};
1217
1218
1219/**
1220 * Static clone function. NOTE: A type-safe method called "cloneMessage" exists
1221 * on each generated JsPb class. Do not call this function directly.
1222 * @param {!jspb.Message} msg A message to clone.
1223 * @return {!jspb.Message} A deep clone of the given message.
1224 */
1225jspb.Message.clone = function(msg) {
1226 // Although we could include the wrappers, we leave them out here.
1227 return jspb.Message.cloneMessage(msg);
1228};
1229
1230
1231/**
1232 * @param {!jspb.Message} msg A message to clone.
1233 * @return {!jspb.Message} A deep clone of the given message.
1234 * @protected
1235 */
1236jspb.Message.cloneMessage = function(msg) {
1237 // Although we could include the wrappers, we leave them out here.
1238 return new msg.constructor(jspb.Message.clone_(msg.toArray()));
1239};
1240
1241
1242/**
1243 * Takes 2 messages of the same type and copies the contents of the first
1244 * message into the second. After this the 2 messages will equals in terms of
1245 * value semantics but share no state. All data in the destination message will
1246 * be overridden.
1247 *
1248 * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
1249 * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
1250 * as its contents.
1251 * @template MESSAGE
1252 */
1253jspb.Message.copyInto = function(fromMessage, toMessage) {
1254 goog.asserts.assertInstanceof(fromMessage, jspb.Message);
1255 goog.asserts.assertInstanceof(toMessage, jspb.Message);
1256 goog.asserts.assert(fromMessage.constructor == toMessage.constructor,
1257 'Copy source and target message should have the same type.');
1258 var copyOfFrom = jspb.Message.clone(fromMessage);
1259
1260 var to = toMessage.toArray();
1261 var from = copyOfFrom.toArray();
1262
1263 // Empty destination in case it has more values at the end of the array.
1264 to.length = 0;
1265 // and then copy everything from the new to the existing message.
1266 for (var i = 0; i < from.length; i++) {
1267 to[i] = from[i];
1268 }
1269
1270 // This is either null or empty for a fresh copy.
1271 toMessage.wrappers_ = copyOfFrom.wrappers_;
1272 // Just a reference into the shared array.
1273 toMessage.extensionObject_ = copyOfFrom.extensionObject_;
1274};
1275
1276
1277/**
1278 * Helper for cloning an internal JsPb object.
1279 * @param {!Object} obj A JsPb object, eg, a field, to be cloned.
1280 * @return {!Object} A clone of the input object.
1281 * @private
1282 */
1283jspb.Message.clone_ = function(obj) {
1284 var o;
1285 if (goog.isArray(obj)) {
1286 // Allocate array of correct size.
1287 var clonedArray = new Array(obj.length);
1288 // Use array iteration where possible because it is faster than for-in.
1289 for (var i = 0; i < obj.length; i++) {
1290 if ((o = obj[i]) != null) {
1291 clonedArray[i] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
1292 }
1293 }
1294 return clonedArray;
1295 }
1296 var clone = {};
1297 for (var key in obj) {
1298 if ((o = obj[key]) != null) {
1299 clone[key] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
1300 }
1301 }
1302 return clone;
1303};
1304
1305
1306/**
1307 * Registers a JsPb message type id with its constructor.
1308 * @param {string} id The id for this type of message.
1309 * @param {Function} constructor The message constructor.
1310 */
1311jspb.Message.registerMessageType = function(id, constructor) {
1312 jspb.Message.registry_[id] = constructor;
1313 // This is needed so we can later access messageId directly on the contructor,
1314 // otherwise it is not available due to 'property collapsing' by the compiler.
1315 constructor.messageId = id;
1316};
1317
1318
1319/**
1320 * The registry of message ids to message constructors.
1321 * @private
1322 */
1323jspb.Message.registry_ = {};
1324
1325
1326/**
1327 * The extensions registered on MessageSet. This is a map of extension
1328 * field number to field info object. This should be considered as a
1329 * private API.
1330 *
1331 * This is similar to [jspb class name].extensions object for
1332 * non-MessageSet. We special case MessageSet so that we do not need
1333 * to goog.require MessageSet from classes that extends MessageSet.
1334 *
1335 * @type {!Object.<number, jspb.ExtensionFieldInfo>}
1336 */
1337jspb.Message.messageSetExtensions = {};