message.js 56 KB

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