message.js 44 KB

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