message.js 38 KB

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