message.js 59 KB

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