message.js 47 KB

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