PageRenderTime 26ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/std/cs/_std/haxe/ds/IntMap.hx

https://github.com/MarcWeber/haxe-compiler-experiments
Haxe | 455 lines | 351 code | 59 blank | 45 comment | 79 complexity | f41b234797fa30d8319ca79ccc309a19 MD5 | raw file
  1. /*
  2. * Copyright (c) 2005, The haXe Project Contributors
  3. * All rights reserved.
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. *
  7. * - Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * - Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT CONTRIBUTORS "AS IS" AND ANY
  14. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  15. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  16. * DISCLAIMED. IN NO EVENT SHALL THE HAXE PROJECT CONTRIBUTORS BE LIABLE FOR
  17. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  19. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  20. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  23. * DAMAGE.
  24. */
  25. package haxe.ds;
  26. import cs.NativeArray;
  27. /*
  28. * This IntMap implementation is based on khash (https://github.com/attractivechaos/klib/blob/master/khash.h)
  29. * Copyright goes to Attractive Chaos <attractor@live.co.uk> and his contributors
  30. *
  31. * Thanks also to Jonas Malaco Filho for his Haxe-written IntMap code inspired by Python tables.
  32. * (https://jonasmalaco.com/fossil/test/jonas-haxe/artifact/887b53126e237d6c68951111d594033403889304)
  33. */
  34. @:coreApi class IntMap<T>
  35. {
  36. private static inline var HASH_UPPER = 0.7;
  37. private var flags:NativeArray<Int>;
  38. private var _keys:NativeArray<Int>;
  39. private var vals:NativeArray<T>;
  40. private var nBuckets:Int;
  41. private var size:Int;
  42. private var nOccupied:Int;
  43. private var upperBound:Int;
  44. private var cachedKey:Int;
  45. private var cachedIndex:Int;
  46. public function new() : Void
  47. {
  48. cachedIndex = -1;
  49. }
  50. public function set( key : Int, value : T ) : Void
  51. {
  52. var x:Int;
  53. if (nOccupied >= upperBound)
  54. {
  55. if (nBuckets > (size << 1))
  56. resize(nBuckets - 1); //clear "deleted" elements
  57. else
  58. resize(nBuckets + 1);
  59. }
  60. var flags = flags, _keys = _keys;
  61. {
  62. var mask = nBuckets - 1;
  63. var site = x = nBuckets;
  64. var k = hash(key);
  65. var i = k & mask;
  66. //for speed up
  67. if (flagIsEmpty(flags, i)) {
  68. x = i;
  69. } else {
  70. var inc = getInc(k, mask);
  71. var last = i;
  72. while (! (isEither(flags, i) || _keys[i] == key) )
  73. {
  74. i = (i + inc) & mask;
  75. #if DEBUG_HASHTBL
  76. if (i == last)
  77. {
  78. throw "assert";
  79. }
  80. #end
  81. }
  82. x = i;
  83. }
  84. }
  85. if (flagIsEmpty(flags, x))
  86. {
  87. _keys[x] = key;
  88. vals[x] = value;
  89. setIsBothFalse(flags, x);
  90. size++;
  91. nOccupied++;
  92. } else if (flagIsDel(flags, x)) {
  93. _keys[x] = key;
  94. vals[x] = value;
  95. setIsBothFalse(flags, x);
  96. size++;
  97. } else {
  98. assert(_keys[x] == key);
  99. vals[x] = value;
  100. }
  101. }
  102. @:final private function lookup( key : Int ) : Int
  103. {
  104. if (nBuckets != 0)
  105. {
  106. var flags = flags, _keys = _keys;
  107. var mask = nBuckets - 1, k = hash(key);
  108. var i = k & mask;
  109. var inc = getInc(k, mask); /* inc == 1 for linear probing */
  110. var last = i;
  111. while (!flagIsEmpty(flags, i) && (flagIsDel(flags, i) || _keys[i] != key))
  112. {
  113. i = (i + inc) & mask;
  114. if (i == last)
  115. return -1;
  116. }
  117. return isEither(flags, i) ? -1 : i;
  118. }
  119. return -1;
  120. }
  121. public function get( key : Int ) : Null<T>
  122. {
  123. var idx = -1;
  124. if (cachedKey == key && ( (idx = cachedIndex) != -1 ))
  125. {
  126. return vals[idx];
  127. }
  128. idx = lookup(key);
  129. if (idx != -1)
  130. {
  131. cachedKey = key;
  132. cachedIndex = idx;
  133. return vals[idx];
  134. }
  135. return null;
  136. }
  137. private function getDefault( key : Int, def : T ) : T
  138. {
  139. var idx = -1;
  140. if (cachedKey == key && ( (idx = cachedIndex) != -1 ))
  141. {
  142. return vals[idx];
  143. }
  144. idx = lookup(key);
  145. if (idx != -1)
  146. {
  147. cachedKey = key;
  148. cachedIndex = idx;
  149. return vals[idx];
  150. }
  151. return def;
  152. }
  153. public function exists( key : Int ) : Bool
  154. {
  155. var idx = -1;
  156. if (cachedKey == key && ( (idx = cachedIndex) != -1 ))
  157. {
  158. return true;
  159. }
  160. idx = lookup(key);
  161. if (idx != -1)
  162. {
  163. cachedKey = key;
  164. cachedIndex = idx;
  165. return true;
  166. }
  167. return false;
  168. }
  169. public function remove( key : Int ) : Bool
  170. {
  171. var idx = -1;
  172. if (! (cachedKey == key && ( (idx = cachedIndex) != -1 )))
  173. {
  174. idx = lookup(key);
  175. }
  176. if (idx == -1)
  177. {
  178. return false;
  179. } else {
  180. if (cachedKey == key)
  181. cachedIndex = -1;
  182. if (!isEither(flags, idx))
  183. {
  184. setIsDelTrue(flags, idx);
  185. --size;
  186. vals[idx] = null;
  187. _keys[idx] = 0;
  188. }
  189. return true;
  190. }
  191. }
  192. @:final private function resize(newNBuckets:Int) : Void
  193. {
  194. //This function uses 0.25*n_bucktes bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets.
  195. var newFlags = null;
  196. var j = 1;
  197. {
  198. newNBuckets = roundUp(newNBuckets);
  199. if (newNBuckets < 4) newNBuckets = 4;
  200. if (size >= (newNBuckets * HASH_UPPER + 0.5)) /* requested size is too small */
  201. {
  202. j = 0;
  203. } else { /* hash table size to be changed (shrink or expand); rehash */
  204. var nfSize = flagsSize(newNBuckets);
  205. newFlags = new NativeArray( nfSize );
  206. for (i in 0...nfSize)
  207. newFlags[i] = 0xaaaaaaaa;
  208. if (nBuckets < newNBuckets) //expand
  209. {
  210. var k = new NativeArray(newNBuckets);
  211. if (_keys != null)
  212. arrayCopy(_keys, 0, k, 0, nBuckets);
  213. _keys = k;
  214. var v = new NativeArray(newNBuckets);
  215. if (vals != null)
  216. arrayCopy(vals, 0, v, 0, nBuckets);
  217. vals = v;
  218. } //otherwise shrink
  219. }
  220. }
  221. if (j != 0)
  222. { //rehashing is required
  223. //resetting cache
  224. cachedKey = 0;
  225. cachedIndex = -1;
  226. j = -1;
  227. var nBuckets = nBuckets, _keys = _keys, vals = vals, flags = flags;
  228. var newMask = newNBuckets - 1;
  229. while (++j < nBuckets)
  230. {
  231. if (!isEither(flags, j))
  232. {
  233. var key = _keys[j];
  234. var val = vals[j];
  235. setIsDelTrue(flags, j);
  236. while (true) /* kick-out process; sort of like in Cuckoo hashing */
  237. {
  238. var k = hash(key);
  239. var inc = getInc(k, newMask);
  240. var i = k & newMask;
  241. while (!flagIsEmpty(newFlags, i))
  242. i = (i + inc) & newMask;
  243. setIsEmptyFalse(newFlags, i);
  244. if (i < nBuckets && !isEither(flags, i)) /* kick out the existing element */
  245. {
  246. {
  247. var tmp = _keys[i];
  248. _keys[i] = key;
  249. key = tmp;
  250. }
  251. {
  252. var tmp = vals[i];
  253. vals[i] = val;
  254. val = tmp;
  255. }
  256. setIsDelTrue(flags, i); /* mark it as deleted in the old hash table */
  257. } else { /* write the element and jump out of the loop */
  258. _keys[i] = key;
  259. vals[i] = val;
  260. break;
  261. }
  262. }
  263. }
  264. }
  265. if (nBuckets > newNBuckets) /* shrink the hash table */
  266. {
  267. {
  268. var k = new NativeArray(newNBuckets);
  269. arrayCopy(_keys, 0, k, 0, newNBuckets);
  270. this._keys = k;
  271. }
  272. {
  273. var v = new NativeArray(newNBuckets);
  274. arrayCopy(vals, 0, v, 0, newNBuckets);
  275. this.vals = v;
  276. }
  277. }
  278. this.flags = newFlags;
  279. this.nBuckets = newNBuckets;
  280. this.nOccupied = size;
  281. this.upperBound = Std.int(newNBuckets * HASH_UPPER + .5);
  282. }
  283. }
  284. /**
  285. Returns an iterator of all keys in the hashtable.
  286. Implementation detail: Do not set() any new value while iterating, as it may cause a resize, which will break iteration
  287. **/
  288. public function keys() : Iterator<Int>
  289. {
  290. var i = 0;
  291. var len = nBuckets;
  292. return {
  293. hasNext: function() {
  294. for (j in i...len)
  295. {
  296. if (!isEither(flags, j))
  297. {
  298. i = j;
  299. return true;
  300. }
  301. }
  302. return false;
  303. },
  304. next: function() {
  305. var ret = _keys[i];
  306. cachedIndex = i;
  307. cachedKey = ret;
  308. i = i + 1;
  309. return ret;
  310. }
  311. };
  312. }
  313. /**
  314. Returns an iterator of all values in the hashtable.
  315. Implementation detail: Do not set() any new value while iterating, as it may cause a resize, which will break iteration
  316. **/
  317. public function iterator() : Iterator<T>
  318. {
  319. var i = 0;
  320. var len = nBuckets;
  321. return {
  322. hasNext: function() {
  323. for (j in i...len)
  324. {
  325. if (!isEither(flags, j))
  326. {
  327. i = j;
  328. return true;
  329. }
  330. }
  331. return false;
  332. },
  333. next: function() {
  334. var ret = vals[i];
  335. i = i + 1;
  336. return ret;
  337. }
  338. };
  339. }
  340. /**
  341. Returns an displayable representation of the hashtable content.
  342. **/
  343. public function toString() : String {
  344. var s = new StringBuf();
  345. s.add("{");
  346. var it = keys();
  347. for( i in it ) {
  348. s.add(i);
  349. s.add(" => ");
  350. s.add(Std.string(get(i)));
  351. if( it.hasNext() )
  352. s.add(", ");
  353. }
  354. s.add("}");
  355. return s.toString();
  356. }
  357. private static inline function assert(x:Bool):Void
  358. {
  359. #if debug
  360. if (!x) throw "assert failed";
  361. #end
  362. }
  363. private static inline function defaultK():Int return 0
  364. private static inline function arrayCopy(sourceArray:cs.system.Array, sourceIndex:Int, destinationArray:cs.system.Array, destinationIndex:Int, length:Int):Void
  365. cs.system.Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)
  366. private static inline function getInc(k:Int, mask:Int):Int
  367. return (((k) >> 3 ^ (k) << 3) | 1) & (mask)
  368. private static inline function hash(i:Int):Int
  369. return i
  370. private static inline function flagIsEmpty(flag:NativeArray<Int>, i:Int):Bool
  371. return ( (flag[i >> 4] >>> ((i & 0xf) << 1)) & 2 ) != 0
  372. private static inline function flagIsDel(flag:NativeArray<Int>, i:Int):Bool
  373. return ((flag[i >> 4] >>> ((i & 0xf) << 1)) & 1) != 0
  374. private static inline function isEither(flag:NativeArray<Int>, i:Int):Bool
  375. return ((flag[i >> 4] >>> ((i & 0xf) << 1)) & 3) != 0
  376. private static inline function setIsDelFalse(flag:NativeArray<Int>, i:Int):Void
  377. flag[i >> 4] &= ~(1 << ((i & 0xf) << 1))
  378. private static inline function setIsEmptyFalse(flag:NativeArray<Int>, i:Int):Void
  379. flag[i >> 4] &= ~(2 << ((i & 0xf) << 1))
  380. private static inline function setIsBothFalse(flag:NativeArray<Int>, i:Int):Void
  381. flag[i >> 4] &= ~(3 << ((i & 0xf) << 1))
  382. private static inline function setIsDelTrue(flag:NativeArray<Int>, i:Int):Void
  383. flag[i >> 4] |= 1 << ((i & 0xf) << 1)
  384. private static inline function roundUp(x:Int):Int
  385. {
  386. --x;
  387. x |= (x) >>> 1;
  388. x |= (x) >>> 2;
  389. x |= (x) >>> 4;
  390. x |= (x) >>> 8;
  391. x |= (x) >>> 16;
  392. return ++x;
  393. }
  394. private static inline function flagsSize(m:Int):Int
  395. return ((m) < 16? 1 : (m) >> 4)
  396. }