message.js 60 KB

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