map.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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
  32. * @suppress {missingRequire} TODO(b/152540451): this shouldn't be needed
  33. */
  34. goog.provide('jspb.Map');
  35. goog.require('goog.asserts');
  36. goog.requireType('jspb.BinaryReader');
  37. goog.requireType('jspb.BinaryWriter');
  38. /**
  39. * Constructs a new Map. A Map is a container that is used to implement map
  40. * fields on message objects. It closely follows the ES6 Map API; however,
  41. * it is distinct because we do not want to depend on external polyfills or
  42. * on ES6 itself.
  43. *
  44. * This constructor should only be called from generated message code. It is not
  45. * intended for general use by library consumers.
  46. *
  47. * @template K, V
  48. *
  49. * @param {!Array<!Array<?>>} arr
  50. *
  51. * @param {?function(new:V, ?=)=} opt_valueCtor
  52. * The constructor for type V, if type V is a message type.
  53. *
  54. * @constructor
  55. * @struct
  56. */
  57. jspb.Map = function(arr, opt_valueCtor) {
  58. /** @const @private */
  59. this.arr_ = arr;
  60. /** @const @private */
  61. this.valueCtor_ = opt_valueCtor;
  62. /** @type {!Object<string, !jspb.Map.Entry_<K,V>>} @private */
  63. this.map_ = {};
  64. /**
  65. * Is `this.arr_ updated with respect to `this.map_`?
  66. * @type {boolean}
  67. */
  68. this.arrClean = true;
  69. if (this.arr_.length > 0) {
  70. this.loadFromArray_();
  71. }
  72. };
  73. /**
  74. * Load initial content from underlying array.
  75. * @private
  76. */
  77. jspb.Map.prototype.loadFromArray_ = function() {
  78. for (var i = 0; i < this.arr_.length; i++) {
  79. var record = this.arr_[i];
  80. var key = record[0];
  81. var value = record[1];
  82. this.map_[key.toString()] = new jspb.Map.Entry_(key, value);
  83. }
  84. this.arrClean = true;
  85. };
  86. /**
  87. * Synchronize content to underlying array, if needed, and return it.
  88. * @return {!Array<!Array<!Object>>}
  89. */
  90. jspb.Map.prototype.toArray = function() {
  91. if (this.arrClean) {
  92. if (this.valueCtor_) {
  93. // We need to recursively sync maps in submessages to their arrays.
  94. var m = this.map_;
  95. for (var p in m) {
  96. if (Object.prototype.hasOwnProperty.call(m, p)) {
  97. var valueWrapper = /** @type {?jspb.Message} */ (m[p].valueWrapper);
  98. if (valueWrapper) {
  99. valueWrapper.toArray();
  100. }
  101. }
  102. }
  103. }
  104. } else {
  105. // Delete all elements.
  106. this.arr_.length = 0;
  107. var strKeys = this.stringKeys_();
  108. // Output keys in deterministic (sorted) order.
  109. strKeys.sort();
  110. for (var i = 0; i < strKeys.length; i++) {
  111. var entry = this.map_[strKeys[i]];
  112. var valueWrapper = /** @type {?jspb.Message} */ (entry.valueWrapper);
  113. if (valueWrapper) {
  114. valueWrapper.toArray();
  115. }
  116. this.arr_.push([entry.key, entry.value]);
  117. }
  118. this.arrClean = true;
  119. }
  120. return this.arr_;
  121. };
  122. /**
  123. * Returns the map formatted as an array of key-value pairs, suitable for the
  124. * toObject() form of a message.
  125. *
  126. * @param {boolean=} includeInstance Whether to include the JSPB instance for
  127. * transitional soy proto support: http://goto/soy-param-migration
  128. * @param {function((boolean|undefined),V):!Object=} valueToObject
  129. * The static toObject() method, if V is a message type.
  130. * @return {!Array<!Array<!Object>>}
  131. */
  132. jspb.Map.prototype.toObject = function(includeInstance, valueToObject) {
  133. var rawArray = this.toArray();
  134. var entries = [];
  135. for (var i = 0; i < rawArray.length; i++) {
  136. var entry = this.map_[rawArray[i][0].toString()];
  137. this.wrapEntry_(entry);
  138. var valueWrapper = /** @type {V|undefined} */ (entry.valueWrapper);
  139. if (valueWrapper) {
  140. goog.asserts.assert(valueToObject);
  141. entries.push([entry.key, valueToObject(includeInstance, valueWrapper)]);
  142. } else {
  143. entries.push([entry.key, entry.value]);
  144. }
  145. }
  146. return entries;
  147. };
  148. /**
  149. * Returns a Map from the given array of key-value pairs when the values are of
  150. * message type. The values in the array must match the format returned by their
  151. * message type's toObject() method.
  152. *
  153. * @template K, V
  154. * @param {!Array<!Array<!Object>>} entries
  155. * @param {function(new:V,?=)} valueCtor
  156. * The constructor for type V.
  157. * @param {function(!Object):V} valueFromObject
  158. * The fromObject function for type V.
  159. * @return {!jspb.Map<K, V>}
  160. */
  161. jspb.Map.fromObject = function(entries, valueCtor, valueFromObject) {
  162. var result = new jspb.Map([], valueCtor);
  163. for (var i = 0; i < entries.length; i++) {
  164. var key = entries[i][0];
  165. var value = valueFromObject(entries[i][1]);
  166. result.set(key, value);
  167. }
  168. return result;
  169. };
  170. /**
  171. * Helper: an IteratorIterable over an array.
  172. * @template T
  173. * @param {!Array<T>} arr the array
  174. * @implements {IteratorIterable<T>}
  175. * @constructor @struct
  176. * @private
  177. */
  178. jspb.Map.ArrayIteratorIterable_ = function(arr) {
  179. /** @type {number} @private */
  180. this.idx_ = 0;
  181. /** @const @private */
  182. this.arr_ = arr;
  183. };
  184. /** @override @final */
  185. jspb.Map.ArrayIteratorIterable_.prototype.next = function() {
  186. if (this.idx_ < this.arr_.length) {
  187. return {done: false, value: this.arr_[this.idx_++]};
  188. } else {
  189. return {done: true, value: undefined};
  190. }
  191. };
  192. if (typeof(Symbol) != 'undefined') {
  193. /** @override */
  194. jspb.Map.ArrayIteratorIterable_.prototype[Symbol.iterator] = function() {
  195. return this;
  196. };
  197. }
  198. /**
  199. * Returns the map's length (number of key/value pairs).
  200. * @return {number}
  201. */
  202. jspb.Map.prototype.getLength = function() {
  203. return this.stringKeys_().length;
  204. };
  205. /**
  206. * Clears the map.
  207. */
  208. jspb.Map.prototype.clear = function() {
  209. this.map_ = {};
  210. this.arrClean = false;
  211. };
  212. /**
  213. * Deletes a particular key from the map.
  214. * N.B.: differs in name from ES6 Map's `delete` because IE8 does not support
  215. * reserved words as property names.
  216. * @this {jspb.Map}
  217. * @param {K} key
  218. * @return {boolean} Whether any entry with this key was deleted.
  219. */
  220. jspb.Map.prototype.del = function(key) {
  221. var keyValue = key.toString();
  222. var hadKey = this.map_.hasOwnProperty(keyValue);
  223. delete this.map_[keyValue];
  224. this.arrClean = false;
  225. return hadKey;
  226. };
  227. /**
  228. * Returns an array of [key, value] pairs in the map.
  229. *
  230. * This is redundant compared to the plain entries() method, but we provide this
  231. * to help out Angular 1.x users. Still evaluating whether this is the best
  232. * option.
  233. *
  234. * @return {!Array<!Array<K|V>>}
  235. */
  236. jspb.Map.prototype.getEntryList = function() {
  237. var entries = [];
  238. var strKeys = this.stringKeys_();
  239. strKeys.sort();
  240. for (var i = 0; i < strKeys.length; i++) {
  241. var entry = this.map_[strKeys[i]];
  242. entries.push([entry.key, entry.value]);
  243. }
  244. return entries;
  245. };
  246. /**
  247. * Returns an iterator-iterable over [key, value] pairs in the map.
  248. * Closure compiler sadly doesn't support tuples, ie. Iterator<[K,V]>.
  249. * @return {!IteratorIterable<!Array<K|V>>} The iterator-iterable.
  250. */
  251. jspb.Map.prototype.entries = function() {
  252. var entries = [];
  253. var strKeys = this.stringKeys_();
  254. strKeys.sort();
  255. for (var i = 0; i < strKeys.length; i++) {
  256. var entry = this.map_[strKeys[i]];
  257. entries.push([entry.key, this.wrapEntry_(entry)]);
  258. }
  259. return new jspb.Map.ArrayIteratorIterable_(entries);
  260. };
  261. /**
  262. * Returns an iterator-iterable over keys in the map.
  263. * @return {!IteratorIterable<K>} The iterator-iterable.
  264. */
  265. jspb.Map.prototype.keys = function() {
  266. var keys = [];
  267. var strKeys = this.stringKeys_();
  268. strKeys.sort();
  269. for (var i = 0; i < strKeys.length; i++) {
  270. var entry = this.map_[strKeys[i]];
  271. keys.push(entry.key);
  272. }
  273. return new jspb.Map.ArrayIteratorIterable_(keys);
  274. };
  275. /**
  276. * Returns an iterator-iterable over values in the map.
  277. * @return {!IteratorIterable<V>} The iterator-iterable.
  278. */
  279. jspb.Map.prototype.values = function() {
  280. var values = [];
  281. var strKeys = this.stringKeys_();
  282. strKeys.sort();
  283. for (var i = 0; i < strKeys.length; i++) {
  284. var entry = this.map_[strKeys[i]];
  285. values.push(this.wrapEntry_(entry));
  286. }
  287. return new jspb.Map.ArrayIteratorIterable_(values);
  288. };
  289. /**
  290. * Iterates over entries in the map, calling a function on each.
  291. * @template T
  292. * @param {function(this:T, V, K, ?jspb.Map<K, V>)} cb
  293. * @param {T=} opt_thisArg
  294. */
  295. jspb.Map.prototype.forEach = function(cb, opt_thisArg) {
  296. var strKeys = this.stringKeys_();
  297. strKeys.sort();
  298. for (var i = 0; i < strKeys.length; i++) {
  299. var entry = this.map_[strKeys[i]];
  300. cb.call(opt_thisArg, this.wrapEntry_(entry), entry.key, this);
  301. }
  302. };
  303. /**
  304. * Sets a key in the map to the given value.
  305. * @param {K} key The key
  306. * @param {V} value The value
  307. * @return {!jspb.Map<K,V>}
  308. */
  309. jspb.Map.prototype.set = function(key, value) {
  310. var entry = new jspb.Map.Entry_(key);
  311. if (this.valueCtor_) {
  312. entry.valueWrapper = value;
  313. // .toArray() on a message returns a reference to the underlying array
  314. // rather than a copy.
  315. entry.value = value.toArray();
  316. } else {
  317. entry.value = value;
  318. }
  319. this.map_[key.toString()] = entry;
  320. this.arrClean = false;
  321. return this;
  322. };
  323. /**
  324. * Helper: lazily construct a wrapper around an entry, if needed, and return the
  325. * user-visible type.
  326. * @param {!jspb.Map.Entry_<K,V>} entry
  327. * @return {V}
  328. * @private
  329. */
  330. jspb.Map.prototype.wrapEntry_ = function(entry) {
  331. if (this.valueCtor_) {
  332. if (!entry.valueWrapper) {
  333. entry.valueWrapper = new this.valueCtor_(entry.value);
  334. }
  335. return /** @type {V} */ (entry.valueWrapper);
  336. } else {
  337. return entry.value;
  338. }
  339. };
  340. /**
  341. * Gets the value corresponding to a key in the map.
  342. * @param {K} key
  343. * @return {V|undefined} The value, or `undefined` if key not present
  344. */
  345. jspb.Map.prototype.get = function(key) {
  346. var keyValue = key.toString();
  347. var entry = this.map_[keyValue];
  348. if (entry) {
  349. return this.wrapEntry_(entry);
  350. } else {
  351. return undefined;
  352. }
  353. };
  354. /**
  355. * Determines whether the given key is present in the map.
  356. * @param {K} key
  357. * @return {boolean} `true` if the key is present
  358. */
  359. jspb.Map.prototype.has = function(key) {
  360. var keyValue = key.toString();
  361. return (keyValue in this.map_);
  362. };
  363. /**
  364. * Write this Map field in wire format to a BinaryWriter, using the given field
  365. * number.
  366. * @param {number} fieldNumber
  367. * @param {!jspb.BinaryWriter} writer
  368. * @param {function(this:jspb.BinaryWriter,number,K)} keyWriterFn
  369. * The method on BinaryWriter that writes type K to the stream.
  370. * @param {function(this:jspb.BinaryWriter,number,V,?=)|
  371. * function(this:jspb.BinaryWriter,number,V,?)} valueWriterFn
  372. * The method on BinaryWriter that writes type V to the stream. May be
  373. * writeMessage, in which case the second callback arg form is used.
  374. * @param {function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
  375. * The BinaryWriter serialization callback for type V, if V is a message
  376. * type.
  377. */
  378. jspb.Map.prototype.serializeBinary = function(
  379. fieldNumber, writer, keyWriterFn, valueWriterFn, opt_valueWriterCallback) {
  380. var strKeys = this.stringKeys_();
  381. strKeys.sort();
  382. for (var i = 0; i < strKeys.length; i++) {
  383. var entry = this.map_[strKeys[i]];
  384. writer.beginSubMessage(fieldNumber);
  385. keyWriterFn.call(writer, 1, entry.key);
  386. if (this.valueCtor_) {
  387. valueWriterFn.call(writer, 2, this.wrapEntry_(entry),
  388. opt_valueWriterCallback);
  389. } else {
  390. /** @type {function(this:jspb.BinaryWriter,number,?)} */ (valueWriterFn)
  391. .call(writer, 2, entry.value);
  392. }
  393. writer.endSubMessage();
  394. }
  395. };
  396. /**
  397. * Read one key/value message from the given BinaryReader. Compatible as the
  398. * `reader` callback parameter to jspb.BinaryReader.readMessage, to be called
  399. * when a key/value pair submessage is encountered. If the Key is undefined,
  400. * we should default it to 0.
  401. * @template K, V
  402. * @param {!jspb.Map} map
  403. * @param {!jspb.BinaryReader} reader
  404. * @param {function(this:jspb.BinaryReader):K} keyReaderFn
  405. * The method on BinaryReader that reads type K from the stream.
  406. *
  407. * @param {function(this:jspb.BinaryReader):V|
  408. * function(this:jspb.BinaryReader,V,
  409. * function(V,!jspb.BinaryReader))} valueReaderFn
  410. * The method on BinaryReader that reads type V from the stream. May be
  411. * readMessage, in which case the second callback arg form is used.
  412. *
  413. * @param {?function(V,!jspb.BinaryReader)=} opt_valueReaderCallback
  414. * The BinaryReader parsing callback for type V, if V is a message type
  415. *
  416. * @param {K=} opt_defaultKey
  417. * The default value for the type of map keys. Accepting map entries with
  418. * unset keys is required for maps to be backwards compatible with the
  419. * repeated message representation described here: goo.gl/zuoLAC
  420. *
  421. * @param {V=} opt_defaultValue
  422. * The default value for the type of map values. Accepting map entries with
  423. * unset values is required for maps to be backwards compatible with the
  424. * repeated message representation described here: goo.gl/zuoLAC
  425. *
  426. */
  427. jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
  428. opt_valueReaderCallback, opt_defaultKey,
  429. opt_defaultValue) {
  430. var key = opt_defaultKey;
  431. var value = opt_defaultValue;
  432. while (reader.nextField()) {
  433. if (reader.isEndGroup()) {
  434. break;
  435. }
  436. var field = reader.getFieldNumber();
  437. if (field == 1) {
  438. // Key.
  439. key = keyReaderFn.call(reader);
  440. } else if (field == 2) {
  441. // Value.
  442. if (map.valueCtor_) {
  443. goog.asserts.assert(opt_valueReaderCallback);
  444. if (!value) {
  445. // Old generator still doesn't provide default value message.
  446. // Need this for backward compatibility.
  447. value = new map.valueCtor_();
  448. }
  449. valueReaderFn.call(reader, value, opt_valueReaderCallback);
  450. } else {
  451. value =
  452. (/** @type {function(this:jspb.BinaryReader):?} */ (valueReaderFn))
  453. .call(reader);
  454. }
  455. }
  456. }
  457. goog.asserts.assert(key != undefined);
  458. goog.asserts.assert(value != undefined);
  459. map.set(key, value);
  460. };
  461. /**
  462. * Helper: compute the list of all stringified keys in the underlying Object
  463. * map.
  464. * @return {!Array<string>}
  465. * @private
  466. */
  467. jspb.Map.prototype.stringKeys_ = function() {
  468. var m = this.map_;
  469. var ret = [];
  470. for (var p in m) {
  471. if (Object.prototype.hasOwnProperty.call(m, p)) {
  472. ret.push(p);
  473. }
  474. }
  475. return ret;
  476. };
  477. /**
  478. * @param {K} key The entry's key.
  479. * @param {V=} opt_value The entry's value wrapper.
  480. * @constructor
  481. * @struct
  482. * @template K, V
  483. * @private
  484. */
  485. jspb.Map.Entry_ = function(key, opt_value) {
  486. /** @const {K} */
  487. this.key = key;
  488. // The JSPB-serializable value. For primitive types this will be of type V.
  489. // For message types it will be an array.
  490. /** @type {V} */
  491. this.value = opt_value;
  492. // Only used for submessage values.
  493. /** @type {V} */
  494. this.valueWrapper = undefined;
  495. };