message.js 51 KB

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