message.js 60 KB

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