message.js 47 KB

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