message.js 61 KB

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