message.js 51 KB

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