message.js 57 KB

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