message.js 57 KB

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