FastPriorityQueue.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. declare(strict_types=1);
  3. namespace Laminas\Stdlib;
  4. use Countable;
  5. use Iterator;
  6. use ReturnTypeWillChange;
  7. use Serializable;
  8. use SplPriorityQueue as PhpSplPriorityQueue;
  9. use UnexpectedValueException;
  10. use function current;
  11. use function in_array;
  12. use function is_array;
  13. use function is_int;
  14. use function key;
  15. use function max;
  16. use function next;
  17. use function reset;
  18. use function serialize;
  19. use function sprintf;
  20. use function unserialize;
  21. /**
  22. * This is an efficient implementation of an integer priority queue in PHP
  23. *
  24. * This class acts like a queue with insert() and extract(), removing the
  25. * elements from the queue and it also acts like an Iterator without removing
  26. * the elements. This behaviour can be used in mixed scenarios with high
  27. * performance boost.
  28. *
  29. * @template TValue of mixed
  30. * @template-implements Iterator<int, TValue>
  31. */
  32. class FastPriorityQueue implements Iterator, Countable, Serializable
  33. {
  34. public const EXTR_DATA = PhpSplPriorityQueue::EXTR_DATA;
  35. public const EXTR_PRIORITY = PhpSplPriorityQueue::EXTR_PRIORITY;
  36. public const EXTR_BOTH = PhpSplPriorityQueue::EXTR_BOTH;
  37. /** @var self::EXTR_* */
  38. protected $extractFlag = self::EXTR_DATA;
  39. /**
  40. * Elements of the queue, divided by priorities
  41. *
  42. * @var array<int, list<TValue>>
  43. */
  44. protected $values = [];
  45. /**
  46. * Array of priorities
  47. *
  48. * @var array<int, int>
  49. */
  50. protected $priorities = [];
  51. /**
  52. * Array of priorities used for the iteration
  53. *
  54. * @var array
  55. */
  56. protected $subPriorities = [];
  57. /**
  58. * Max priority
  59. *
  60. * @var int|null
  61. */
  62. protected $maxPriority;
  63. /**
  64. * Total number of elements in the queue
  65. *
  66. * @var int
  67. */
  68. protected $count = 0;
  69. /**
  70. * Index of the current element in the queue
  71. *
  72. * @var int
  73. */
  74. protected $index = 0;
  75. /**
  76. * Sub index of the current element in the same priority level
  77. *
  78. * @var int
  79. */
  80. protected $subIndex = 0;
  81. public function __serialize(): array
  82. {
  83. $clone = clone $this;
  84. $clone->setExtractFlags(self::EXTR_BOTH);
  85. $data = [];
  86. foreach ($clone as $item) {
  87. $data[] = $item;
  88. }
  89. return $data;
  90. }
  91. public function __unserialize(array $data): void
  92. {
  93. foreach ($data as $item) {
  94. $this->insert($item['data'], $item['priority']);
  95. }
  96. }
  97. /**
  98. * Insert an element in the queue with a specified priority
  99. *
  100. * @param TValue $value
  101. * @param int $priority
  102. * @return void
  103. */
  104. public function insert(mixed $value, $priority)
  105. {
  106. if (! is_int($priority)) {
  107. throw new Exception\InvalidArgumentException('The priority must be an integer');
  108. }
  109. $this->values[$priority][] = $value;
  110. if (! isset($this->priorities[$priority])) {
  111. $this->priorities[$priority] = $priority;
  112. $this->maxPriority = $this->maxPriority === null ? $priority : max($priority, $this->maxPriority);
  113. }
  114. ++$this->count;
  115. }
  116. /**
  117. * Extract an element in the queue according to the priority and the
  118. * order of insertion
  119. *
  120. * @return TValue|int|array{data: TValue, priority: int}|false
  121. */
  122. public function extract()
  123. {
  124. if (! $this->valid()) {
  125. return false;
  126. }
  127. $value = $this->current();
  128. $this->nextAndRemove();
  129. return $value;
  130. }
  131. /**
  132. * Remove an item from the queue
  133. *
  134. * This is different than {@link extract()}; its purpose is to dequeue an
  135. * item.
  136. *
  137. * Note: this removes the first item matching the provided item found. If
  138. * the same item has been added multiple times, it will not remove other
  139. * instances.
  140. *
  141. * @return bool False if the item was not found, true otherwise.
  142. */
  143. public function remove(mixed $datum)
  144. {
  145. $currentIndex = $this->index;
  146. $currentSubIndex = $this->subIndex;
  147. $currentPriority = $this->maxPriority;
  148. $this->rewind();
  149. while ($this->valid()) {
  150. if (current($this->values[$this->maxPriority]) === $datum) {
  151. $index = key($this->values[$this->maxPriority]);
  152. unset($this->values[$this->maxPriority][$index]);
  153. // The `next()` method advances the internal array pointer, so we need to use the `reset()` function,
  154. // otherwise we would lose all elements before the place the pointer points.
  155. reset($this->values[$this->maxPriority]);
  156. $this->index = $currentIndex;
  157. $this->subIndex = $currentSubIndex;
  158. // If the array is empty we need to destroy the unnecessary priority,
  159. // otherwise we would end up with an incorrect value of `$this->count`
  160. // {@see \Laminas\Stdlib\FastPriorityQueue::nextAndRemove()}.
  161. if (empty($this->values[$this->maxPriority])) {
  162. unset($this->values[$this->maxPriority]);
  163. unset($this->priorities[$this->maxPriority]);
  164. if ($this->maxPriority === $currentPriority) {
  165. $this->subIndex = 0;
  166. }
  167. }
  168. $this->maxPriority = empty($this->priorities) ? null : max($this->priorities);
  169. --$this->count;
  170. return true;
  171. }
  172. $this->next();
  173. }
  174. return false;
  175. }
  176. /**
  177. * Get the total number of elements in the queue
  178. *
  179. * @return int
  180. */
  181. #[ReturnTypeWillChange]
  182. public function count()
  183. {
  184. return $this->count;
  185. }
  186. /**
  187. * Get the current element in the queue
  188. *
  189. * @return TValue|int|array{data: TValue|false, priority: int|null}|false
  190. */
  191. #[ReturnTypeWillChange]
  192. public function current()
  193. {
  194. switch ($this->extractFlag) {
  195. case self::EXTR_DATA:
  196. return current($this->values[$this->maxPriority]);
  197. case self::EXTR_PRIORITY:
  198. return $this->maxPriority;
  199. case self::EXTR_BOTH:
  200. return [
  201. 'data' => current($this->values[$this->maxPriority]),
  202. 'priority' => $this->maxPriority,
  203. ];
  204. }
  205. }
  206. /**
  207. * Get the index of the current element in the queue
  208. *
  209. * @return int
  210. */
  211. #[ReturnTypeWillChange]
  212. public function key()
  213. {
  214. return $this->index;
  215. }
  216. /**
  217. * Set the iterator pointer to the next element in the queue
  218. * removing the previous element
  219. *
  220. * @return void
  221. */
  222. protected function nextAndRemove()
  223. {
  224. $key = key($this->values[$this->maxPriority]);
  225. if (false === next($this->values[$this->maxPriority])) {
  226. unset($this->priorities[$this->maxPriority]);
  227. unset($this->values[$this->maxPriority]);
  228. $this->maxPriority = empty($this->priorities) ? null : max($this->priorities);
  229. $this->subIndex = -1;
  230. } else {
  231. unset($this->values[$this->maxPriority][$key]);
  232. }
  233. ++$this->index;
  234. ++$this->subIndex;
  235. --$this->count;
  236. }
  237. /**
  238. * Set the iterator pointer to the next element in the queue
  239. * without removing the previous element
  240. */
  241. #[ReturnTypeWillChange]
  242. public function next()
  243. {
  244. if (false === next($this->values[$this->maxPriority])) {
  245. unset($this->subPriorities[$this->maxPriority]);
  246. reset($this->values[$this->maxPriority]);
  247. $this->maxPriority = empty($this->subPriorities) ? null : max($this->subPriorities);
  248. $this->subIndex = -1;
  249. }
  250. ++$this->index;
  251. ++$this->subIndex;
  252. }
  253. /**
  254. * Check if the current iterator is valid
  255. *
  256. * @return bool
  257. */
  258. #[ReturnTypeWillChange]
  259. public function valid()
  260. {
  261. return isset($this->values[$this->maxPriority]);
  262. }
  263. /**
  264. * Rewind the current iterator
  265. */
  266. #[ReturnTypeWillChange]
  267. public function rewind()
  268. {
  269. $this->subPriorities = $this->priorities;
  270. $this->maxPriority = empty($this->priorities) ? 0 : max($this->priorities);
  271. $this->index = 0;
  272. $this->subIndex = 0;
  273. }
  274. /**
  275. * Serialize to an array
  276. *
  277. * Array will be priority => data pairs
  278. *
  279. * @return list<TValue|int|array{data: TValue, priority: int}>
  280. */
  281. public function toArray()
  282. {
  283. $array = [];
  284. foreach (clone $this as $item) {
  285. $array[] = $item;
  286. }
  287. return $array;
  288. }
  289. /**
  290. * Serialize
  291. *
  292. * @return string
  293. */
  294. public function serialize()
  295. {
  296. return serialize($this->__serialize());
  297. }
  298. /**
  299. * Deserialize
  300. *
  301. * @param string $data
  302. * @return void
  303. */
  304. public function unserialize($data)
  305. {
  306. $toUnserialize = unserialize($data);
  307. if (! is_array($toUnserialize)) {
  308. throw new UnexpectedValueException(sprintf(
  309. 'Cannot deserialize %s instance; corrupt serialization data',
  310. self::class
  311. ));
  312. }
  313. $this->__unserialize($toUnserialize);
  314. }
  315. /**
  316. * Set the extract flag
  317. *
  318. * @param self::EXTR_* $flag
  319. * @return void
  320. */
  321. public function setExtractFlags($flag)
  322. {
  323. $this->extractFlag = match ($flag) {
  324. self::EXTR_DATA, self::EXTR_PRIORITY, self::EXTR_BOTH => $flag,
  325. default => throw new Exception\InvalidArgumentException("The extract flag specified is not valid"),
  326. };
  327. }
  328. /**
  329. * Check if the queue is empty
  330. *
  331. * @return bool
  332. */
  333. public function isEmpty()
  334. {
  335. return empty($this->values);
  336. }
  337. /**
  338. * Does the queue contain the given datum?
  339. *
  340. * @return bool
  341. */
  342. public function contains(mixed $datum)
  343. {
  344. foreach ($this->values as $values) {
  345. if (in_array($datum, $values)) {
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. /**
  352. * Does the queue have an item with the given priority?
  353. *
  354. * @param int $priority
  355. * @return bool
  356. */
  357. public function hasPriority($priority)
  358. {
  359. return isset($this->values[$priority]);
  360. }
  361. }