map.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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<!Object>>} arr
  46. *
  47. * @param {?function(new:V)|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 {!Object} */ (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)|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: return an iterator over an array.
  168. * @template T
  169. * @param {!Array<T>} arr the array
  170. * @return {!Iterator<T>} an iterator
  171. * @private
  172. */
  173. jspb.Map.arrayIterator_ = function(arr) {
  174. var idx = 0;
  175. return /** @type {!Iterator} */ ({
  176. next: function() {
  177. if (idx < arr.length) {
  178. return { done: false, value: arr[idx++] };
  179. } else {
  180. return { done: true };
  181. }
  182. }
  183. });
  184. };
  185. /**
  186. * Returns the map's length (number of key/value pairs).
  187. * @return {number}
  188. */
  189. jspb.Map.prototype.getLength = function() {
  190. return this.stringKeys_().length;
  191. };
  192. /**
  193. * Clears the map.
  194. */
  195. jspb.Map.prototype.clear = function() {
  196. this.map_ = {};
  197. this.arrClean = false;
  198. };
  199. /**
  200. * Deletes a particular key from the map.
  201. * N.B.: differs in name from ES6 Map's `delete` because IE8 does not support
  202. * reserved words as property names.
  203. * @this {jspb.Map}
  204. * @param {K} key
  205. * @return {boolean} Whether any entry with this key was deleted.
  206. */
  207. jspb.Map.prototype.del = function(key) {
  208. var keyValue = key.toString();
  209. var hadKey = this.map_.hasOwnProperty(keyValue);
  210. delete this.map_[keyValue];
  211. this.arrClean = false;
  212. return hadKey;
  213. };
  214. /**
  215. * Returns an array of [key, value] pairs in the map.
  216. *
  217. * This is redundant compared to the plain entries() method, but we provide this
  218. * to help out Angular 1.x users. Still evaluating whether this is the best
  219. * option.
  220. *
  221. * @return {!Array<!Array<K|V>>}
  222. */
  223. jspb.Map.prototype.getEntryList = function() {
  224. var entries = [];
  225. var strKeys = this.stringKeys_();
  226. strKeys.sort();
  227. for (var i = 0; i < strKeys.length; i++) {
  228. var entry = this.map_[strKeys[i]];
  229. entries.push([entry.key, entry.value]);
  230. }
  231. return entries;
  232. };
  233. /**
  234. * Returns an iterator over [key, value] pairs in the map.
  235. * Closure compiler sadly doesn't support tuples, ie. Iterator<[K,V]>.
  236. * @return {!Iterator<!Array<K|V>>}
  237. * The iterator
  238. */
  239. jspb.Map.prototype.entries = function() {
  240. var entries = [];
  241. var strKeys = this.stringKeys_();
  242. strKeys.sort();
  243. for (var i = 0; i < strKeys.length; i++) {
  244. var entry = this.map_[strKeys[i]];
  245. entries.push([entry.key, this.wrapEntry_(entry)]);
  246. }
  247. return jspb.Map.arrayIterator_(entries);
  248. };
  249. /**
  250. * Returns an iterator over keys in the map.
  251. * @return {!Iterator<K>} The iterator
  252. */
  253. jspb.Map.prototype.keys = function() {
  254. var keys = [];
  255. var strKeys = this.stringKeys_();
  256. strKeys.sort();
  257. for (var i = 0; i < strKeys.length; i++) {
  258. var entry = this.map_[strKeys[i]];
  259. keys.push(entry.key);
  260. }
  261. return jspb.Map.arrayIterator_(keys);
  262. };
  263. /**
  264. * Returns an iterator over values in the map.
  265. * @return {!Iterator<V>} The iterator
  266. */
  267. jspb.Map.prototype.values = function() {
  268. var values = [];
  269. var strKeys = this.stringKeys_();
  270. strKeys.sort();
  271. for (var i = 0; i < strKeys.length; i++) {
  272. var entry = this.map_[strKeys[i]];
  273. values.push(this.wrapEntry_(entry));
  274. }
  275. return jspb.Map.arrayIterator_(values);
  276. };
  277. /**
  278. * Iterates over entries in the map, calling a function on each.
  279. * @template T
  280. * @param {function(this:T, V, K, ?jspb.Map<K, V>)} cb
  281. * @param {T=} opt_thisArg
  282. */
  283. jspb.Map.prototype.forEach = function(cb, opt_thisArg) {
  284. var strKeys = this.stringKeys_();
  285. strKeys.sort();
  286. for (var i = 0; i < strKeys.length; i++) {
  287. var entry = this.map_[strKeys[i]];
  288. cb.call(opt_thisArg, this.wrapEntry_(entry), entry.key, this);
  289. }
  290. };
  291. /**
  292. * Sets a key in the map to the given value.
  293. * @param {K} key The key
  294. * @param {V} value The value
  295. * @return {!jspb.Map<K,V>}
  296. */
  297. jspb.Map.prototype.set = function(key, value) {
  298. var entry = new jspb.Map.Entry_(key);
  299. if (this.valueCtor_) {
  300. entry.valueWrapper = value;
  301. // .toArray() on a message returns a reference to the underlying array
  302. // rather than a copy.
  303. entry.value = value.toArray();
  304. } else {
  305. entry.value = value;
  306. }
  307. this.map_[key.toString()] = entry;
  308. this.arrClean = false;
  309. return this;
  310. };
  311. /**
  312. * Helper: lazily construct a wrapper around an entry, if needed, and return the
  313. * user-visible type.
  314. * @param {!jspb.Map.Entry_<K,V>} entry
  315. * @return {V}
  316. * @private
  317. */
  318. jspb.Map.prototype.wrapEntry_ = function(entry) {
  319. if (this.valueCtor_) {
  320. if (!entry.valueWrapper) {
  321. entry.valueWrapper = new this.valueCtor_(entry.value);
  322. }
  323. return /** @type {V} */ (entry.valueWrapper);
  324. } else {
  325. return entry.value;
  326. }
  327. };
  328. /**
  329. * Gets the value corresponding to a key in the map.
  330. * @param {K} key
  331. * @return {V|undefined} The value, or `undefined` if key not present
  332. */
  333. jspb.Map.prototype.get = function(key) {
  334. var keyValue = key.toString();
  335. var entry = this.map_[keyValue];
  336. if (entry) {
  337. return this.wrapEntry_(entry);
  338. } else {
  339. return undefined;
  340. }
  341. };
  342. /**
  343. * Determines whether the given key is present in the map.
  344. * @param {K} key
  345. * @return {boolean} `true` if the key is present
  346. */
  347. jspb.Map.prototype.has = function(key) {
  348. var keyValue = key.toString();
  349. return (keyValue in this.map_);
  350. };
  351. /**
  352. * Write this Map field in wire format to a BinaryWriter, using the given field
  353. * number.
  354. * @param {number} fieldNumber
  355. * @param {!jspb.BinaryWriter} writer
  356. * @param {!function(this:jspb.BinaryWriter,number,K)} keyWriterFn
  357. * The method on BinaryWriter that writes type K to the stream.
  358. * @param {!function(this:jspb.BinaryWriter,number,V)|
  359. * function(this:jspb.BinaryReader,V,?)} valueWriterFn
  360. * The method on BinaryWriter that writes type V to the stream. May be
  361. * writeMessage, in which case the second callback arg form is used.
  362. * @param {function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
  363. * The BinaryWriter serialization callback for type V, if V is a message
  364. * type.
  365. */
  366. jspb.Map.prototype.serializeBinary = function(
  367. fieldNumber, writer, keyWriterFn, valueWriterFn, opt_valueWriterCallback) {
  368. var strKeys = this.stringKeys_();
  369. strKeys.sort();
  370. for (var i = 0; i < strKeys.length; i++) {
  371. var entry = this.map_[strKeys[i]];
  372. writer.beginSubMessage(fieldNumber);
  373. keyWriterFn.call(writer, 1, entry.key);
  374. if (this.valueCtor_) {
  375. valueWriterFn.call(writer, 2, this.wrapEntry_(entry),
  376. opt_valueWriterCallback);
  377. } else {
  378. valueWriterFn.call(writer, 2, entry.value);
  379. }
  380. writer.endSubMessage();
  381. }
  382. };
  383. /**
  384. * Read one key/value message from the given BinaryReader. Compatible as the
  385. * `reader` callback parameter to jspb.BinaryReader.readMessage, to be called
  386. * when a key/value pair submessage is encountered.
  387. * @template K, V
  388. * @param {!jspb.Map} map
  389. * @param {!jspb.BinaryReader} reader
  390. * @param {!function(this:jspb.BinaryReader):K} keyReaderFn
  391. * The method on BinaryReader that reads type K from the stream.
  392. *
  393. * @param {!function(this:jspb.BinaryReader):V|
  394. * function(this:jspb.BinaryReader,V,
  395. * function(V,!jspb.BinaryReader))} valueReaderFn
  396. * The method on BinaryReader that reads type V from the stream. May be
  397. * readMessage, in which case the second callback arg form is used.
  398. *
  399. * @param {?function(V,!jspb.BinaryReader)=} opt_valueReaderCallback
  400. * The BinaryReader parsing callback for type V, if V is a message type.
  401. *
  402. */
  403. jspb.Map.deserializeBinary = function(map, reader, keyReaderFn, valueReaderFn,
  404. opt_valueReaderCallback) {
  405. var key = undefined;
  406. var value = undefined;
  407. while (reader.nextField()) {
  408. if (reader.isEndGroup()) {
  409. break;
  410. }
  411. var field = reader.getFieldNumber();
  412. if (field == 1) {
  413. // Key.
  414. key = keyReaderFn.call(reader);
  415. } else if (field == 2) {
  416. // Value.
  417. if (map.valueCtor_) {
  418. value = new map.valueCtor_();
  419. valueReaderFn.call(reader, value, opt_valueReaderCallback);
  420. } else {
  421. value = valueReaderFn.call(reader);
  422. }
  423. }
  424. }
  425. goog.asserts.assert(key != undefined);
  426. goog.asserts.assert(value != undefined);
  427. map.set(key, value);
  428. };
  429. /**
  430. * Helper: compute the list of all stringified keys in the underlying Object
  431. * map.
  432. * @return {!Array<string>}
  433. * @private
  434. */
  435. jspb.Map.prototype.stringKeys_ = function() {
  436. var m = this.map_;
  437. var ret = [];
  438. for (var p in m) {
  439. if (Object.prototype.hasOwnProperty.call(m, p)) {
  440. ret.push(p);
  441. }
  442. }
  443. return ret;
  444. };
  445. /**
  446. * @param {!K} key The entry's key.
  447. * @param {V=} opt_value The entry's value wrapper.
  448. * @constructor
  449. * @struct
  450. * @template K, V
  451. * @private
  452. */
  453. jspb.Map.Entry_ = function(key, opt_value) {
  454. /** @const {K} */
  455. this.key = key;
  456. // The JSPB-serializable value. For primitive types this will be of type V.
  457. // For message types it will be an array.
  458. /** @type {V} */
  459. this.value = opt_value;
  460. // Only used for submessage values.
  461. /** @type {V} */
  462. this.valueWrapper = undefined;
  463. };