message.js 53 KB

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