PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/src/pathfinder/npf/queue.cpp

https://github.com/xmirakulix/openttd-xmix
C++ | 489 lines | 297 code | 55 blank | 137 comment | 101 complexity | 225db8cef9b3ab0b00d3ddfbdf0680cd MD5 | raw file
  1. /* $Id$ */
  2. /*
  3. * This file is part of OpenTTD.
  4. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
  5. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  6. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
  7. */
  8. /** @file queue.cpp Implementation of the #BinaryHeap/#Hash. */
  9. #include "../../stdafx.h"
  10. #include "../../core/alloc_func.hpp"
  11. #include "queue.h"
  12. /*
  13. * Binary Heap
  14. * For information, see: http://www.policyalmanac.org/games/binaryHeaps.htm
  15. */
  16. const int BinaryHeap::BINARY_HEAP_BLOCKSIZE_BITS = 10; ///< The number of elements that will be malloc'd at a time.
  17. const int BinaryHeap::BINARY_HEAP_BLOCKSIZE = 1 << BinaryHeap::BINARY_HEAP_BLOCKSIZE_BITS;
  18. const int BinaryHeap::BINARY_HEAP_BLOCKSIZE_MASK = BinaryHeap::BINARY_HEAP_BLOCKSIZE - 1;
  19. /**
  20. * Clears the queue, by removing all values from it. Its state is
  21. * effectively reset. If free_items is true, each of the items cleared
  22. * in this way are free()'d.
  23. */
  24. void BinaryHeap::Clear(bool free_values)
  25. {
  26. /* Free all items if needed and free all but the first blocks of memory */
  27. uint i;
  28. uint j;
  29. for (i = 0; i < this->blocks; i++) {
  30. if (this->elements[i] == NULL) {
  31. /* No more allocated blocks */
  32. break;
  33. }
  34. /* For every allocated block */
  35. if (free_values) {
  36. for (j = 0; j < (1 << BINARY_HEAP_BLOCKSIZE_BITS); j++) {
  37. /* For every element in the block */
  38. if ((this->size >> BINARY_HEAP_BLOCKSIZE_BITS) == i &&
  39. (this->size & BINARY_HEAP_BLOCKSIZE_MASK) == j) {
  40. break; // We're past the last element
  41. }
  42. free(this->elements[i][j].item);
  43. }
  44. }
  45. if (i != 0) {
  46. /* Leave the first block of memory alone */
  47. free(this->elements[i]);
  48. this->elements[i] = NULL;
  49. }
  50. }
  51. this->size = 0;
  52. this->blocks = 1;
  53. }
  54. /**
  55. * Frees the queue, by reclaiming all memory allocated by it. After
  56. * this it is no longer usable. If free_items is true, any remaining
  57. * items are free()'d too.
  58. */
  59. void BinaryHeap::Free(bool free_values)
  60. {
  61. uint i;
  62. this->Clear(free_values);
  63. for (i = 0; i < this->blocks; i++) {
  64. if (this->elements[i] == NULL) break;
  65. free(this->elements[i]);
  66. }
  67. free(this->elements);
  68. }
  69. /**
  70. * Pushes an element into the queue, at the appropriate place for the queue.
  71. * Requires the queue pointer to be of an appropriate type, of course.
  72. */
  73. bool BinaryHeap::Push(void *item, int priority)
  74. {
  75. if (this->size == this->max_size) return false;
  76. assert(this->size < this->max_size);
  77. if (this->elements[this->size >> BINARY_HEAP_BLOCKSIZE_BITS] == NULL) {
  78. /* The currently allocated blocks are full, allocate a new one */
  79. assert((this->size & BINARY_HEAP_BLOCKSIZE_MASK) == 0);
  80. this->elements[this->size >> BINARY_HEAP_BLOCKSIZE_BITS] = MallocT<BinaryHeapNode>(BINARY_HEAP_BLOCKSIZE);
  81. this->blocks++;
  82. }
  83. /* Add the item at the end of the array */
  84. this->GetElement(this->size + 1).priority = priority;
  85. this->GetElement(this->size + 1).item = item;
  86. this->size++;
  87. /* Now we are going to check where it belongs. As long as the parent is
  88. * bigger, we switch with the parent */
  89. {
  90. BinaryHeapNode temp;
  91. int i;
  92. int j;
  93. i = this->size;
  94. while (i > 1) {
  95. /* Get the parent of this object (divide by 2) */
  96. j = i / 2;
  97. /* Is the parent bigger than the current, switch them */
  98. if (this->GetElement(i).priority <= this->GetElement(j).priority) {
  99. temp = this->GetElement(j);
  100. this->GetElement(j) = this->GetElement(i);
  101. this->GetElement(i) = temp;
  102. i = j;
  103. } else {
  104. /* It is not, we're done! */
  105. break;
  106. }
  107. }
  108. }
  109. return true;
  110. }
  111. /**
  112. * Deletes the item from the queue. priority should be specified if
  113. * known, which speeds up the deleting for some queue's. Should be -1
  114. * if not known.
  115. */
  116. bool BinaryHeap::Delete(void *item, int priority)
  117. {
  118. uint i = 0;
  119. /* First, we try to find the item.. */
  120. do {
  121. if (this->GetElement(i + 1).item == item) break;
  122. i++;
  123. } while (i < this->size);
  124. /* We did not find the item, so we return false */
  125. if (i == this->size) return false;
  126. /* Now we put the last item over the current item while decreasing the size of the elements */
  127. this->size--;
  128. this->GetElement(i + 1) = this->GetElement(this->size + 1);
  129. /* Now the only thing we have to do, is resort it..
  130. * On place i there is the item to be sorted.. let's start there */
  131. {
  132. uint j;
  133. BinaryHeapNode temp;
  134. /* Because of the fact that Binary Heap uses array from 1 to n, we need to
  135. * increase i by 1
  136. */
  137. i++;
  138. for (;;) {
  139. j = i;
  140. /* Check if we have 2 childs */
  141. if (2 * j + 1 <= this->size) {
  142. /* Is this child smaller than the parent? */
  143. if (this->GetElement(j).priority >= this->GetElement(2 * j).priority) i = 2 * j;
  144. /* Yes, we _need_ to use i here, not j, because we want to have the smallest child
  145. * This way we get that straight away! */
  146. if (this->GetElement(i).priority >= this->GetElement(2 * j + 1).priority) i = 2 * j + 1;
  147. /* Do we have one child? */
  148. } else if (2 * j <= this->size) {
  149. if (this->GetElement(j).priority >= this->GetElement(2 * j).priority) i = 2 * j;
  150. }
  151. /* One of our childs is smaller than we are, switch */
  152. if (i != j) {
  153. temp = this->GetElement(j);
  154. this->GetElement(j) = this->GetElement(i);
  155. this->GetElement(i) = temp;
  156. } else {
  157. /* None of our childs is smaller, so we stay here.. stop :) */
  158. break;
  159. }
  160. }
  161. }
  162. return true;
  163. }
  164. /**
  165. * Pops the first element from the queue. What exactly is the first element,
  166. * is defined by the exact type of queue.
  167. */
  168. void *BinaryHeap::Pop()
  169. {
  170. void *result;
  171. if (this->size == 0) return NULL;
  172. /* The best item is always on top, so give that as result */
  173. result = this->GetElement(1).item;
  174. /* And now we should get rid of this item... */
  175. this->Delete(this->GetElement(1).item, this->GetElement(1).priority);
  176. return result;
  177. }
  178. /**
  179. * Initializes a binary heap and allocates internal memory for maximum of
  180. * max_size elements
  181. */
  182. void BinaryHeap::Init(uint max_size)
  183. {
  184. this->max_size = max_size;
  185. this->size = 0;
  186. /* We malloc memory in block of BINARY_HEAP_BLOCKSIZE
  187. * It autosizes when it runs out of memory */
  188. this->elements = CallocT<BinaryHeapNode*>((max_size - 1) / BINARY_HEAP_BLOCKSIZE + 1);
  189. this->elements[0] = MallocT<BinaryHeapNode>(BINARY_HEAP_BLOCKSIZE);
  190. this->blocks = 1;
  191. }
  192. /* Because we don't want anyone else to bother with our defines */
  193. #undef BIN_HEAP_ARR
  194. /*
  195. * Hash
  196. */
  197. /**
  198. * Builds a new hash in an existing struct. Make sure that hash() always
  199. * returns a hash less than num_buckets! Call delete_hash after use
  200. */
  201. void Hash::Init(Hash_HashProc *hash, uint num_buckets)
  202. {
  203. /* Allocate space for the Hash, the buckets and the bucket flags */
  204. uint i;
  205. this->hash = hash;
  206. this->size = 0;
  207. this->num_buckets = num_buckets;
  208. this->buckets = (HashNode*)MallocT<byte>(num_buckets * (sizeof(*this->buckets) + sizeof(*this->buckets_in_use)));
  209. this->buckets_in_use = (bool*)(this->buckets + num_buckets);
  210. for (i = 0; i < num_buckets; i++) this->buckets_in_use[i] = false;
  211. }
  212. /**
  213. * Deletes the hash and cleans up. Only cleans up memory allocated by new_Hash
  214. * & friends. If free is true, it will call free() on all the values that
  215. * are left in the hash.
  216. */
  217. void Hash::Delete(bool free_values)
  218. {
  219. uint i;
  220. /* Iterate all buckets */
  221. for (i = 0; i < this->num_buckets; i++) {
  222. if (this->buckets_in_use[i]) {
  223. HashNode *node;
  224. /* Free the first value */
  225. if (free_values) free(this->buckets[i].value);
  226. node = this->buckets[i].next;
  227. while (node != NULL) {
  228. HashNode *prev = node;
  229. node = node->next;
  230. /* Free the value */
  231. if (free_values) free(prev->value);
  232. /* Free the node */
  233. free(prev);
  234. }
  235. }
  236. }
  237. free(this->buckets);
  238. /* No need to free buckets_in_use, it is always allocated in one
  239. * malloc with buckets */
  240. }
  241. #ifdef HASH_STATS
  242. void Hash::PrintStatistics() const
  243. {
  244. uint used_buckets = 0;
  245. uint max_collision = 0;
  246. uint max_usage = 0;
  247. uint usage[200];
  248. uint i;
  249. for (i = 0; i < lengthof(usage); i++) usage[i] = 0;
  250. for (i = 0; i < this->num_buckets; i++) {
  251. uint collision = 0;
  252. if (this->buckets_in_use[i]) {
  253. const HashNode *node;
  254. used_buckets++;
  255. for (node = &this->buckets[i]; node != NULL; node = node->next) collision++;
  256. if (collision > max_collision) max_collision = collision;
  257. }
  258. if (collision >= lengthof(usage)) collision = lengthof(usage) - 1;
  259. usage[collision]++;
  260. if (collision > 0 && usage[collision] >= max_usage) {
  261. max_usage = usage[collision];
  262. }
  263. }
  264. printf(
  265. "---\n"
  266. "Hash size: %d\n"
  267. "Nodes used: %d\n"
  268. "Non empty buckets: %d\n"
  269. "Max collision: %d\n",
  270. this->num_buckets, this->size, used_buckets, max_collision
  271. );
  272. printf("{ ");
  273. for (i = 0; i <= max_collision; i++) {
  274. if (usage[i] > 0) {
  275. printf("%d:%d ", i, usage[i]);
  276. #if 0
  277. if (i > 0) {
  278. uint j;
  279. for (j = 0; j < usage[i] * 160 / 800; j++) putchar('#');
  280. }
  281. printf("\n");
  282. #endif
  283. }
  284. }
  285. printf ("}\n");
  286. }
  287. #endif
  288. /**
  289. * Cleans the hash, but keeps the memory allocated
  290. */
  291. void Hash::Clear(bool free_values)
  292. {
  293. uint i;
  294. #ifdef HASH_STATS
  295. if (this->size > 2000) this->PrintStatistics();
  296. #endif
  297. /* Iterate all buckets */
  298. for (i = 0; i < this->num_buckets; i++) {
  299. if (this->buckets_in_use[i]) {
  300. HashNode *node;
  301. this->buckets_in_use[i] = false;
  302. /* Free the first value */
  303. if (free_values) free(this->buckets[i].value);
  304. node = this->buckets[i].next;
  305. while (node != NULL) {
  306. HashNode *prev = node;
  307. node = node->next;
  308. if (free_values) free(prev->value);
  309. free(prev);
  310. }
  311. }
  312. }
  313. this->size = 0;
  314. }
  315. /**
  316. * Finds the node that that saves this key pair. If it is not
  317. * found, returns NULL. If it is found, *prev is set to the
  318. * node before the one found, or if the node found was the first in the bucket
  319. * to NULL. If it is not found, *prev is set to the last HashNode in the
  320. * bucket, or NULL if it is empty. prev can also be NULL, in which case it is
  321. * not used for output.
  322. */
  323. HashNode *Hash::FindNode(uint key1, uint key2, HashNode** prev_out) const
  324. {
  325. uint hash = this->hash(key1, key2);
  326. HashNode *result = NULL;
  327. /* Check if the bucket is empty */
  328. if (!this->buckets_in_use[hash]) {
  329. if (prev_out != NULL) *prev_out = NULL;
  330. result = NULL;
  331. /* Check the first node specially */
  332. } else if (this->buckets[hash].key1 == key1 && this->buckets[hash].key2 == key2) {
  333. /* Save the value */
  334. result = this->buckets + hash;
  335. if (prev_out != NULL) *prev_out = NULL;
  336. /* Check all other nodes */
  337. } else {
  338. HashNode *prev = this->buckets + hash;
  339. HashNode *node;
  340. for (node = prev->next; node != NULL; node = node->next) {
  341. if (node->key1 == key1 && node->key2 == key2) {
  342. /* Found it */
  343. result = node;
  344. break;
  345. }
  346. prev = node;
  347. }
  348. if (prev_out != NULL) *prev_out = prev;
  349. }
  350. return result;
  351. }
  352. /**
  353. * Deletes the value with the specified key pair from the hash and returns
  354. * that value. Returns NULL when the value was not present. The value returned
  355. * is _not_ free()'d!
  356. */
  357. void *Hash::DeleteValue(uint key1, uint key2)
  358. {
  359. void *result;
  360. HashNode *prev; // Used as output var for below function call
  361. HashNode *node = this->FindNode(key1, key2, &prev);
  362. if (node == NULL) {
  363. /* not found */
  364. result = NULL;
  365. } else if (prev == NULL) {
  366. /* It is in the first node, we can't free that one, so we free
  367. * the next one instead (if there is any)*/
  368. /* Save the value */
  369. result = node->value;
  370. if (node->next != NULL) {
  371. HashNode *next = node->next;
  372. /* Copy the second to the first */
  373. *node = *next;
  374. /* Free the second */
  375. free(next);
  376. } else {
  377. /* This was the last in this bucket
  378. * Mark it as empty */
  379. uint hash = this->hash(key1, key2);
  380. this->buckets_in_use[hash] = false;
  381. }
  382. } else {
  383. /* It is in another node
  384. * Save the value */
  385. result = node->value;
  386. /* Link previous and next nodes */
  387. prev->next = node->next;
  388. /* Free the node */
  389. free(node);
  390. }
  391. if (result != NULL) this->size--;
  392. return result;
  393. }
  394. /**
  395. * Sets the value associated with the given key pair to the given value.
  396. * Returns the old value if the value was replaced, NULL when it was not yet present.
  397. */
  398. void *Hash::Set(uint key1, uint key2, void *value)
  399. {
  400. HashNode *prev;
  401. HashNode *node = this->FindNode(key1, key2, &prev);
  402. if (node != NULL) {
  403. /* Found it */
  404. void *result = node->value;
  405. node->value = value;
  406. return result;
  407. }
  408. /* It is not yet present, let's add it */
  409. if (prev == NULL) {
  410. /* The bucket is still empty */
  411. uint hash = this->hash(key1, key2);
  412. this->buckets_in_use[hash] = true;
  413. node = this->buckets + hash;
  414. } else {
  415. /* Add it after prev */
  416. node = MallocT<HashNode>(1);
  417. prev->next = node;
  418. }
  419. node->next = NULL;
  420. node->key1 = key1;
  421. node->key2 = key2;
  422. node->value = value;
  423. this->size++;
  424. return NULL;
  425. }
  426. /**
  427. * Gets the value associated with the given key pair, or NULL when it is not
  428. * present.
  429. */
  430. void *Hash::Get(uint key1, uint key2) const
  431. {
  432. HashNode *node = this->FindNode(key1, key2, NULL);
  433. return (node != NULL) ? node->value : NULL;
  434. }