message.js 53 KB

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