message.js 62 KB

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