message.js 62 KB

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