message.js 52 KB

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