map.js 15 KB

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