message.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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. * The below callbacks are used to allow the map to serialize and parse its
  671. * binary wire format data. Their purposes are described in more detail in
  672. * `jspb.Map`'s constructor documentation.
  673. *
  674. * @template K, V
  675. * @param {!jspb.Message} msg
  676. * @param {number} fieldNumber
  677. * @param {boolean|undefined} noLazyCreate
  678. * @param {?=} opt_valueCtor
  679. * @param {function(number,K)=} opt_keyWriterFn
  680. * @param {function():K=} opt_keyReaderFn
  681. * @param {function(number,V)|function(number,V,?)|
  682. * function(number,V,?,?,?,?)=} opt_valueWriterFn
  683. * @param {function():V|
  684. * function(V,function(?,?))=} opt_valueReaderFn
  685. * @param {function(?,?)|function(?,?,?,?,?)=} opt_valueWriterCallback
  686. * @param {function(?,?)=} opt_valueReaderCallback
  687. * @return {!jspb.Map<K, V>|undefined}
  688. * @protected
  689. */
  690. jspb.Message.getMapField = function(msg, fieldNumber, noLazyCreate,
  691. opt_valueCtor, opt_keyWriterFn, opt_keyReaderFn, opt_valueWriterFn,
  692. opt_valueReaderFn, opt_valueWriterCallback, opt_valueReaderCallback) {
  693. if (!msg.wrappers_) {
  694. msg.wrappers_ = {};
  695. }
  696. // If we already have a map in the map wrappers, return that.
  697. if (fieldNumber in msg.wrappers_) {
  698. return msg.wrappers_[fieldNumber];
  699. } else if (noLazyCreate) {
  700. return undefined;
  701. } else {
  702. // Wrap the underlying elements array with a Map.
  703. var arr = jspb.Message.getField(msg, fieldNumber);
  704. if (!arr) {
  705. arr = [];
  706. jspb.Message.setField(msg, fieldNumber, arr);
  707. }
  708. return msg.wrappers_[fieldNumber] =
  709. new jspb.Map(
  710. /** @type {!Array<!Array<!Object>>} */ (arr),
  711. opt_keyWriterFn, opt_keyReaderFn, opt_valueWriterFn,
  712. opt_valueReaderFn, opt_valueCtor, opt_valueWriterCallback,
  713. opt_valueReaderCallback);
  714. }
  715. };
  716. /**
  717. * Sets the value of a non-extension field.
  718. * @param {!jspb.Message} msg A jspb proto.
  719. * @param {number} fieldNumber The field number.
  720. * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
  721. * @protected
  722. */
  723. jspb.Message.setField = function(msg, fieldNumber, value) {
  724. if (fieldNumber < msg.pivot_) {
  725. msg.array[jspb.Message.getIndex_(msg, fieldNumber)] = value;
  726. } else {
  727. msg.extensionObject_[fieldNumber] = value;
  728. }
  729. };
  730. /**
  731. * Sets the value of a field in a oneof union and clears all other fields in
  732. * the union.
  733. * @param {!jspb.Message} msg A jspb proto.
  734. * @param {number} fieldNumber The field number.
  735. * @param {!Array<number>} oneof The fields belonging to the union.
  736. * @param {string|number|boolean|Uint8Array|Array|undefined} value New value
  737. * @protected
  738. */
  739. jspb.Message.setOneofField = function(msg, fieldNumber, oneof, value) {
  740. var currentCase = jspb.Message.computeOneofCase(msg, oneof);
  741. if (currentCase && currentCase !== fieldNumber && value !== undefined) {
  742. if (msg.wrappers_ && currentCase in msg.wrappers_) {
  743. msg.wrappers_[currentCase] = undefined;
  744. }
  745. jspb.Message.setField(msg, currentCase, undefined);
  746. }
  747. jspb.Message.setField(msg, fieldNumber, value);
  748. };
  749. /**
  750. * Computes the selection in a oneof group for the given message, ensuring
  751. * only one field is set in the process.
  752. *
  753. * According to the protobuf language guide (
  754. * https://developers.google.com/protocol-buffers/docs/proto#oneof), "if the
  755. * parser encounters multiple members of the same oneof on the wire, only the
  756. * last member seen is used in the parsed message." Since JSPB serializes
  757. * messages to a JSON array, the "last member seen" will always be the field
  758. * with the greatest field number (directly corresponding to the greatest
  759. * array index).
  760. *
  761. * @param {!jspb.Message} msg A jspb proto.
  762. * @param {!Array<number>} oneof The field numbers belonging to the union.
  763. * @return {number} The field number currently set in the union, or 0 if none.
  764. * @protected
  765. */
  766. jspb.Message.computeOneofCase = function(msg, oneof) {
  767. var oneofField;
  768. var oneofValue;
  769. goog.array.forEach(oneof, function(fieldNumber) {
  770. var value = jspb.Message.getField(msg, fieldNumber);
  771. if (goog.isDefAndNotNull(value)) {
  772. oneofField = fieldNumber;
  773. oneofValue = value;
  774. jspb.Message.setField(msg, fieldNumber, undefined);
  775. }
  776. });
  777. if (oneofField) {
  778. // NB: We know the value is unique, so we can call jspb.Message.setField
  779. // directly instead of jpsb.Message.setOneofField. Also, setOneofField
  780. // calls this function.
  781. jspb.Message.setField(msg, oneofField, oneofValue);
  782. return oneofField;
  783. }
  784. return 0;
  785. };
  786. /**
  787. * Gets and wraps a proto field on access.
  788. * @param {!jspb.Message} msg A jspb proto.
  789. * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
  790. * @param {number} fieldNumber The field number.
  791. * @param {number=} opt_required True (1) if this is a required field.
  792. * @return {jspb.Message} The field as a jspb proto.
  793. * @protected
  794. */
  795. jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
  796. // TODO(mwr): Consider copying data and/or arrays.
  797. if (!msg.wrappers_) {
  798. msg.wrappers_ = {};
  799. }
  800. if (!msg.wrappers_[fieldNumber]) {
  801. var data = /** @type {Array} */ (jspb.Message.getField(msg, fieldNumber));
  802. if (opt_required || data) {
  803. // TODO(mwr): Remove existence test for always valid default protos.
  804. msg.wrappers_[fieldNumber] = new ctor(data);
  805. }
  806. }
  807. return /** @type {jspb.Message} */ (msg.wrappers_[fieldNumber]);
  808. };
  809. /**
  810. * Gets and wraps a repeated proto field on access.
  811. * @param {!jspb.Message} msg A jspb proto.
  812. * @param {function(new:jspb.Message, Array)} ctor Constructor for the field.
  813. * @param {number} fieldNumber The field number.
  814. * @return {Array<!jspb.Message>} The repeated field as an array of protos.
  815. * @protected
  816. */
  817. jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
  818. if (!msg.wrappers_) {
  819. msg.wrappers_ = {};
  820. }
  821. if (!msg.wrappers_[fieldNumber]) {
  822. var data = jspb.Message.getField(msg, fieldNumber);
  823. for (var wrappers = [], i = 0; i < data.length; i++) {
  824. wrappers[i] = new ctor(data[i]);
  825. }
  826. msg.wrappers_[fieldNumber] = wrappers;
  827. }
  828. var val = msg.wrappers_[fieldNumber];
  829. if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
  830. val = msg.wrappers_[fieldNumber] = [];
  831. }
  832. return /** @type {Array<!jspb.Message>} */ (val);
  833. };
  834. /**
  835. * Sets a proto field and syncs it to the backing array.
  836. * @param {!jspb.Message} msg A jspb proto.
  837. * @param {number} fieldNumber The field number.
  838. * @param {jspb.Message|undefined} value A new value for this proto field.
  839. * @protected
  840. */
  841. jspb.Message.setWrapperField = function(msg, fieldNumber, value) {
  842. if (!msg.wrappers_) {
  843. msg.wrappers_ = {};
  844. }
  845. var data = value ? value.toArray() : value;
  846. msg.wrappers_[fieldNumber] = value;
  847. jspb.Message.setField(msg, fieldNumber, data);
  848. };
  849. /**
  850. * Sets a proto field in a oneof union 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<number>} oneof The fields belonging to the union.
  854. * @param {jspb.Message|undefined} value A new value for this proto field.
  855. * @protected
  856. */
  857. jspb.Message.setOneofWrapperField = function(msg, fieldNumber, oneof, value) {
  858. if (!msg.wrappers_) {
  859. msg.wrappers_ = {};
  860. }
  861. var data = value ? value.toArray() : value;
  862. msg.wrappers_[fieldNumber] = value;
  863. jspb.Message.setOneofField(msg, fieldNumber, oneof, data);
  864. };
  865. /**
  866. * Sets a repeated proto field and syncs it to the backing array.
  867. * @param {!jspb.Message} msg A jspb proto.
  868. * @param {number} fieldNumber The field number.
  869. * @param {Array<!jspb.Message>|undefined} value An array of protos.
  870. * @protected
  871. */
  872. jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
  873. if (!msg.wrappers_) {
  874. msg.wrappers_ = {};
  875. }
  876. value = value || [];
  877. for (var data = [], i = 0; i < value.length; i++) {
  878. data[i] = value[i].toArray();
  879. }
  880. msg.wrappers_[fieldNumber] = value;
  881. jspb.Message.setField(msg, fieldNumber, data);
  882. };
  883. /**
  884. * Converts a JsPb repeated message field into a map. The map will contain
  885. * protos unless an optional toObject function is given, in which case it will
  886. * contain objects suitable for Soy rendering.
  887. * @param {!Array<T>} field The repeated message field to be
  888. * converted.
  889. * @param {function() : string?} mapKeyGetterFn The function to get the key of
  890. * the map.
  891. * @param {?function(boolean=): Object|
  892. * function((boolean|undefined),T): Object} opt_toObjectFn The
  893. * toObject function for this field. We need to pass this for effective
  894. * dead code removal.
  895. * @param {boolean=} opt_includeInstance Whether to include the JSPB instance
  896. * for transitional soy proto support: http://goto/soy-param-migration
  897. * @return {!Object.<string, Object>} A map of proto or Soy objects.
  898. * @template T
  899. */
  900. jspb.Message.toMap = function(
  901. field, mapKeyGetterFn, opt_toObjectFn, opt_includeInstance) {
  902. var result = {};
  903. for (var i = 0; i < field.length; i++) {
  904. result[mapKeyGetterFn.call(field[i])] = opt_toObjectFn ?
  905. opt_toObjectFn.call(field[i], opt_includeInstance,
  906. /** @type {!jspb.Message} */ (field[i])) : field[i];
  907. }
  908. return result;
  909. };
  910. /**
  911. * Syncs all map fields' contents back to their underlying arrays.
  912. * @private
  913. */
  914. jspb.Message.prototype.syncMapFields_ = function() {
  915. // This iterates over submessage, map, and repeated fields, which is intended.
  916. // Submessages can contain maps which also need to be synced.
  917. //
  918. // There is a lot of opportunity for optimization here. For example we could
  919. // statically determine that some messages have no submessages with maps and
  920. // optimize this method away for those just by generating one extra static
  921. // boolean per message type.
  922. if (this.wrappers_) {
  923. for (var fieldNumber in this.wrappers_) {
  924. var val = this.wrappers_[fieldNumber];
  925. if (goog.isArray(val)) {
  926. for (var i = 0; i < val.length; i++) {
  927. if (val[i]) {
  928. val[i].toArray();
  929. }
  930. }
  931. } else {
  932. // Works for submessages and maps.
  933. if (val) {
  934. val.toArray();
  935. }
  936. }
  937. }
  938. }
  939. };
  940. /**
  941. * Returns the internal array of this proto.
  942. * <p>Note: If you use this array to construct a second proto, the content
  943. * would then be partially shared between the two protos.
  944. * @return {!Array} The proto represented as an array.
  945. */
  946. jspb.Message.prototype.toArray = function() {
  947. this.syncMapFields_();
  948. return this.array;
  949. };
  950. /**
  951. * Creates a string representation of the internal data array of this proto.
  952. * <p>NOTE: This string is *not* suitable for use in server requests.
  953. * @return {string} A string representation of this proto.
  954. * @override
  955. */
  956. jspb.Message.prototype.toString = function() {
  957. this.syncMapFields_();
  958. return this.array.toString();
  959. };
  960. /**
  961. * Gets the value of the extension field from the extended object.
  962. * @param {jspb.ExtensionFieldInfo.<T>} fieldInfo Specifies the field to get.
  963. * @return {T} The value of the field.
  964. * @template T
  965. */
  966. jspb.Message.prototype.getExtension = function(fieldInfo) {
  967. if (!this.extensionObject_) {
  968. return undefined;
  969. }
  970. if (!this.wrappers_) {
  971. this.wrappers_ = {};
  972. }
  973. var fieldNumber = fieldInfo.fieldIndex;
  974. if (fieldInfo.isRepeated) {
  975. if (fieldInfo.isMessageType()) {
  976. if (!this.wrappers_[fieldNumber]) {
  977. this.wrappers_[fieldNumber] =
  978. goog.array.map(this.extensionObject_[fieldNumber] || [],
  979. function(arr) {
  980. return new fieldInfo.ctor(arr);
  981. });
  982. }
  983. return this.wrappers_[fieldNumber];
  984. } else {
  985. return this.extensionObject_[fieldNumber];
  986. }
  987. } else {
  988. if (fieldInfo.isMessageType()) {
  989. if (!this.wrappers_[fieldNumber] && this.extensionObject_[fieldNumber]) {
  990. this.wrappers_[fieldNumber] = new fieldInfo.ctor(
  991. /** @type {Array|undefined} */ (
  992. this.extensionObject_[fieldNumber]));
  993. }
  994. return this.wrappers_[fieldNumber];
  995. } else {
  996. return this.extensionObject_[fieldNumber];
  997. }
  998. }
  999. };
  1000. /**
  1001. * Sets the value of the extension field in the extended object.
  1002. * @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
  1003. * @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
  1004. * to set.
  1005. */
  1006. jspb.Message.prototype.setExtension = function(fieldInfo, value) {
  1007. if (!this.wrappers_) {
  1008. this.wrappers_ = {};
  1009. }
  1010. jspb.Message.maybeInitEmptyExtensionObject_(this);
  1011. var fieldNumber = fieldInfo.fieldIndex;
  1012. if (fieldInfo.isRepeated) {
  1013. value = value || [];
  1014. if (fieldInfo.isMessageType()) {
  1015. this.wrappers_[fieldNumber] = value;
  1016. this.extensionObject_[fieldNumber] = goog.array.map(
  1017. /** @type {Array<jspb.Message>} */ (value), function(msg) {
  1018. return msg.toArray();
  1019. });
  1020. } else {
  1021. this.extensionObject_[fieldNumber] = value;
  1022. }
  1023. } else {
  1024. if (fieldInfo.isMessageType()) {
  1025. this.wrappers_[fieldNumber] = value;
  1026. this.extensionObject_[fieldNumber] = value ? value.toArray() : value;
  1027. } else {
  1028. this.extensionObject_[fieldNumber] = value;
  1029. }
  1030. }
  1031. };
  1032. /**
  1033. * Creates a difference object between two messages.
  1034. *
  1035. * The result will contain the top-level fields of m2 that differ from those of
  1036. * m1 at any level of nesting. No data is cloned, the result object will
  1037. * share its top-level elements with m2 (but not with m1).
  1038. *
  1039. * Note that repeated fields should not have null/undefined elements, but if
  1040. * they do, this operation will treat repeated fields of different length as
  1041. * the same if the only difference between them is due to trailing
  1042. * null/undefined values.
  1043. *
  1044. * @param {!jspb.Message} m1 The first message object.
  1045. * @param {!jspb.Message} m2 The second message object.
  1046. * @return {!jspb.Message} The difference returned as a proto message.
  1047. * Note that the returned message may be missing required fields. This is
  1048. * currently tolerated in Js, but would cause an error if you tried to
  1049. * send such a proto to the server. You can access the raw difference
  1050. * array with result.toArray().
  1051. * @throws {Error} If the messages are responses with different types.
  1052. */
  1053. jspb.Message.difference = function(m1, m2) {
  1054. if (!(m1 instanceof m2.constructor)) {
  1055. throw new Error('Messages have different types.');
  1056. }
  1057. var arr1 = m1.toArray();
  1058. var arr2 = m2.toArray();
  1059. var res = [];
  1060. var start = 0;
  1061. var length = arr1.length > arr2.length ? arr1.length : arr2.length;
  1062. if (m1.getJsPbMessageId()) {
  1063. res[0] = m1.getJsPbMessageId();
  1064. start = 1;
  1065. }
  1066. for (var i = start; i < length; i++) {
  1067. if (!jspb.Message.compareFields(arr1[i], arr2[i])) {
  1068. res[i] = arr2[i];
  1069. }
  1070. }
  1071. return new m1.constructor(res);
  1072. };
  1073. /**
  1074. * Tests whether two messages are equal.
  1075. * @param {jspb.Message|undefined} m1 The first message object.
  1076. * @param {jspb.Message|undefined} m2 The second message object.
  1077. * @return {boolean} true if both messages are null/undefined, or if both are
  1078. * of the same type and have the same field values.
  1079. */
  1080. jspb.Message.equals = function(m1, m2) {
  1081. return m1 == m2 || (!!(m1 && m2) && (m1 instanceof m2.constructor) &&
  1082. jspb.Message.compareFields(m1.toArray(), m2.toArray()));
  1083. };
  1084. /**
  1085. * Compares two message extension fields recursively.
  1086. * @param {!Object} extension1 The first field.
  1087. * @param {!Object} extension2 The second field.
  1088. * @return {boolean} true if the extensions are null/undefined, or otherwise
  1089. * equal.
  1090. */
  1091. jspb.Message.compareExtensions = function(extension1, extension2) {
  1092. extension1 = extension1 || {};
  1093. extension2 = extension2 || {};
  1094. var keys = {};
  1095. for (var name in extension1) {
  1096. keys[name] = 0;
  1097. }
  1098. for (var name in extension2) {
  1099. keys[name] = 0;
  1100. }
  1101. for (name in keys) {
  1102. if (!jspb.Message.compareFields(extension1[name], extension2[name])) {
  1103. return false;
  1104. }
  1105. }
  1106. return true;
  1107. };
  1108. /**
  1109. * Compares two message fields recursively.
  1110. * @param {*} field1 The first field.
  1111. * @param {*} field2 The second field.
  1112. * @return {boolean} true if the fields are null/undefined, or otherwise equal.
  1113. */
  1114. jspb.Message.compareFields = function(field1, field2) {
  1115. // If the fields are trivially equal, they're equal.
  1116. if (field1 == field2) return true;
  1117. // If the fields aren't trivially equal and one of them isn't an object,
  1118. // they can't possibly be equal.
  1119. if (!goog.isObject(field1) || !goog.isObject(field2)) {
  1120. return false;
  1121. }
  1122. // We have two objects. If they're different types, they're not equal.
  1123. field1 = /** @type {!Object} */(field1);
  1124. field2 = /** @type {!Object} */(field2);
  1125. if (field1.constructor != field2.constructor) return false;
  1126. // If both are Uint8Arrays, compare them element-by-element.
  1127. if (jspb.Message.SUPPORTS_UINT8ARRAY_ && field1.constructor === Uint8Array) {
  1128. var bytes1 = /** @type {!Uint8Array} */(field1);
  1129. var bytes2 = /** @type {!Uint8Array} */(field2);
  1130. if (bytes1.length != bytes2.length) return false;
  1131. for (var i = 0; i < bytes1.length; i++) {
  1132. if (bytes1[i] != bytes2[i]) return false;
  1133. }
  1134. return true;
  1135. }
  1136. // If they're both Arrays, compare them element by element except for the
  1137. // optional extension objects at the end, which we compare separately.
  1138. if (field1.constructor === Array) {
  1139. var extension1 = undefined;
  1140. var extension2 = undefined;
  1141. var length = Math.max(field1.length, field2.length);
  1142. for (var i = 0; i < length; i++) {
  1143. var val1 = field1[i];
  1144. var val2 = field2[i];
  1145. if (val1 && (val1.constructor == Object)) {
  1146. goog.asserts.assert(extension1 === undefined);
  1147. goog.asserts.assert(i === field1.length - 1);
  1148. extension1 = val1;
  1149. val1 = undefined;
  1150. }
  1151. if (val2 && (val2.constructor == Object)) {
  1152. goog.asserts.assert(extension2 === undefined);
  1153. goog.asserts.assert(i === field2.length - 1);
  1154. extension2 = val2;
  1155. val2 = undefined;
  1156. }
  1157. if (!jspb.Message.compareFields(val1, val2)) {
  1158. return false;
  1159. }
  1160. }
  1161. if (extension1 || extension2) {
  1162. extension1 = extension1 || {};
  1163. extension2 = extension2 || {};
  1164. return jspb.Message.compareExtensions(extension1, extension2);
  1165. }
  1166. return true;
  1167. }
  1168. // If they're both plain Objects (i.e. extensions), compare them as
  1169. // extensions.
  1170. if (field1.constructor === Object) {
  1171. return jspb.Message.compareExtensions(field1, field2);
  1172. }
  1173. throw new Error('Invalid type in JSPB array');
  1174. };
  1175. /**
  1176. * Static clone function. NOTE: A type-safe method called "cloneMessage" exists
  1177. * on each generated JsPb class. Do not call this function directly.
  1178. * @param {!jspb.Message} msg A message to clone.
  1179. * @return {!jspb.Message} A deep clone of the given message.
  1180. */
  1181. jspb.Message.clone = function(msg) {
  1182. // Although we could include the wrappers, we leave them out here.
  1183. return jspb.Message.cloneMessage(msg);
  1184. };
  1185. /**
  1186. * @param {!jspb.Message} msg A message to clone.
  1187. * @return {!jspb.Message} A deep clone of the given message.
  1188. * @protected
  1189. */
  1190. jspb.Message.cloneMessage = function(msg) {
  1191. // Although we could include the wrappers, we leave them out here.
  1192. return new msg.constructor(jspb.Message.clone_(msg.toArray()));
  1193. };
  1194. /**
  1195. * Takes 2 messages of the same type and copies the contents of the first
  1196. * message into the second. After this the 2 messages will equals in terms of
  1197. * value semantics but share no state. All data in the destination message will
  1198. * be overridden.
  1199. *
  1200. * @param {MESSAGE} fromMessage Message that will be copied into toMessage.
  1201. * @param {MESSAGE} toMessage Message which will receive a copy of fromMessage
  1202. * as its contents.
  1203. * @template MESSAGE
  1204. */
  1205. jspb.Message.copyInto = function(fromMessage, toMessage) {
  1206. goog.asserts.assertInstanceof(fromMessage, jspb.Message);
  1207. goog.asserts.assertInstanceof(toMessage, jspb.Message);
  1208. goog.asserts.assert(fromMessage.constructor == toMessage.constructor,
  1209. 'Copy source and target message should have the same type.');
  1210. var copyOfFrom = jspb.Message.clone(fromMessage);
  1211. var to = toMessage.toArray();
  1212. var from = copyOfFrom.toArray();
  1213. // Empty destination in case it has more values at the end of the array.
  1214. to.length = 0;
  1215. // and then copy everything from the new to the existing message.
  1216. for (var i = 0; i < from.length; i++) {
  1217. to[i] = from[i];
  1218. }
  1219. // This is either null or empty for a fresh copy.
  1220. toMessage.wrappers_ = copyOfFrom.wrappers_;
  1221. // Just a reference into the shared array.
  1222. toMessage.extensionObject_ = copyOfFrom.extensionObject_;
  1223. };
  1224. /**
  1225. * Helper for cloning an internal JsPb object.
  1226. * @param {!Object} obj A JsPb object, eg, a field, to be cloned.
  1227. * @return {!Object} A clone of the input object.
  1228. * @private
  1229. */
  1230. jspb.Message.clone_ = function(obj) {
  1231. var o;
  1232. if (goog.isArray(obj)) {
  1233. // Allocate array of correct size.
  1234. var clonedArray = new Array(obj.length);
  1235. // Use array iteration where possible because it is faster than for-in.
  1236. for (var i = 0; i < obj.length; i++) {
  1237. if ((o = obj[i]) != null) {
  1238. clonedArray[i] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
  1239. }
  1240. }
  1241. return clonedArray;
  1242. }
  1243. if (jspb.Message.SUPPORTS_UINT8ARRAY_ && obj instanceof Uint8Array) {
  1244. return new Uint8Array(obj);
  1245. }
  1246. var clone = {};
  1247. for (var key in obj) {
  1248. if ((o = obj[key]) != null) {
  1249. clone[key] = typeof o == 'object' ? jspb.Message.clone_(o) : o;
  1250. }
  1251. }
  1252. return clone;
  1253. };
  1254. /**
  1255. * Registers a JsPb message type id with its constructor.
  1256. * @param {string} id The id for this type of message.
  1257. * @param {Function} constructor The message constructor.
  1258. */
  1259. jspb.Message.registerMessageType = function(id, constructor) {
  1260. jspb.Message.registry_[id] = constructor;
  1261. // This is needed so we can later access messageId directly on the contructor,
  1262. // otherwise it is not available due to 'property collapsing' by the compiler.
  1263. constructor.messageId = id;
  1264. };
  1265. /**
  1266. * The registry of message ids to message constructors.
  1267. * @private
  1268. */
  1269. jspb.Message.registry_ = {};
  1270. /**
  1271. * The extensions registered on MessageSet. This is a map of extension
  1272. * field number to field info object. This should be considered as a
  1273. * private API.
  1274. *
  1275. * This is similar to [jspb class name].extensions object for
  1276. * non-MessageSet. We special case MessageSet so that we do not need
  1277. * to goog.require MessageSet from classes that extends MessageSet.
  1278. *
  1279. * @type {!Object.<number, jspb.ExtensionFieldInfo>}
  1280. */
  1281. jspb.Message.messageSetExtensions = {};