message.js 60 KB

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