-
Notifications
You must be signed in to change notification settings - Fork 509
/
PQueue.scala
369 lines (320 loc) · 11.6 KB
/
PQueue.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
* Copyright 2020-2022 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cats
package effect
package std
import cats.effect.kernel.{Concurrent, Deferred, Ref}
import cats.effect.kernel.syntax.all._
import cats.effect.std.internal.BinomialHeap
import cats.implicits._
import scala.collection.immutable.{Queue => ScalaQueue}
/**
* A purely functional Priority Queue implementation based on a binomial heap (Okasaki)
*
* Assumes an `Order` instance is in scope for `A`
*/
abstract class PQueue[F[_], A] extends PQueueSource[F, A] with PQueueSink[F, A] { self =>
/**
* Modifies the context in which this PQueue is executed using the natural transformation `f`.
*
* O(1)
*
* @return
* a PQueue in the new context obtained by mapping the current one using `f`
*/
def mapK[G[_]](f: F ~> G): PQueue[G, A] =
new PQueue[G, A] {
def offer(a: A): G[Unit] = f(self.offer(a))
def tryOffer(a: A): G[Boolean] = f(self.tryOffer(a))
def size: G[Int] = f(self.size)
val take: G[A] = f(self.take)
val tryTake: G[Option[A]] = f(self.tryTake)
}
}
object PQueue {
def bounded[F[_], A](
capacity: Int)(implicit F: Concurrent[F], O: Order[A]): F[PQueue[F, A]] = {
assertNonNegative(capacity)
F.ref(State.empty[F, A]).map { ref =>
new PQueueImpl[F, A](ref, capacity) {
implicit val Ord = O
}
}
}
def unbounded[F[_], A](implicit F: Concurrent[F], O: Order[A]): F[PQueue[F, A]] =
bounded(Int.MaxValue)
private[std] abstract class PQueueImpl[F[_], A](ref: Ref[F, State[F, A]], capacity: Int)(
implicit F: Concurrent[F])
extends PQueue[F, A] {
implicit val Ord: Order[A]
def offer(a: A): F[Unit] =
F.uncancelable { poll =>
F.deferred[Unit].flatMap { offerer =>
ref.modify {
case State(heap, size, takers, offerers) if takers.nonEmpty =>
val (taker, rest) = takers.dequeue
State(heap.insert(a), size + 1, rest, offerers) -> taker.complete(()).void
case State(heap, size, takers, offerers) if size < capacity =>
State(heap.insert(a), size + 1, takers, offerers) -> F.unit
case s => {
val State(heap, size, takers, offerers) = s
val cleanup = ref modify { s =>
val offerers2 = s.offerers.filter(_ ne offerer)
if (offerers2.isEmpty) {
s.copy(offerers = offerers2) -> F.unit
} else {
val (release, rest) = offerers2.dequeue
s.copy(offerers = rest) -> release.complete(()).void
}
}
State(heap, size, takers, offerers.enqueue(offerer)) ->
(poll(offerer.get) *> poll(offer(a))).onCancel(cleanup.flatten)
}
}.flatten
}
}
def tryOffer(a: A): F[Boolean] =
ref
.modify {
case State(heap, size, takers, offerers) if takers.nonEmpty =>
val (taker, rest) = takers.dequeue
State(heap.insert(a), size + 1, rest, offerers) -> taker.complete(()).as(true)
case State(heap, size, takers, offerers) if size < capacity =>
State(heap.insert(a), size + 1, takers, offerers) -> F.pure(true)
case s => s -> F.pure(false)
}
.flatten
.uncancelable
val take: F[A] =
F.uncancelable { poll =>
F.deferred[Unit] flatMap { taker =>
ref.modify {
case State(heap, size, takers, offerers) if heap.nonEmpty && offerers.isEmpty =>
val (rest, a) = heap.take
State(rest, size - 1, takers, offerers) -> F.pure(a)
case State(heap, size, takers, offerers) if heap.nonEmpty =>
val (rest, a) = heap.take
val (release, tail) = offerers.dequeue
State(rest, size - 1, takers, tail) -> release.complete(()).as(a)
case State(heap, size, takers, offerers) =>
val cleanup = ref modify { s =>
val takers2 = s.takers.filter(_ ne taker)
if (takers2.isEmpty) {
s.copy(takers = takers2) -> F.unit
} else {
val (release, rest) = takers2.dequeue
s.copy(takers = rest) -> release.complete(()).void
}
}
val await = (poll(taker.get) *> poll(take)).onCancel(cleanup.flatten)
val (fulfill, offerers2) = if (offerers.isEmpty) {
(await, offerers)
} else {
val (release, rest) = offerers.dequeue
(release.complete(()) *> await, rest)
}
State(heap, size, takers.enqueue(taker), offerers2) -> fulfill
}.flatten
}
}
val tryTake: F[Option[A]] =
ref
.modify {
case State(heap, size, takers, offerers) if heap.nonEmpty && offerers.isEmpty =>
val (rest, a) = heap.take
State(rest, size - 1, takers, offerers) -> F.pure(a.some)
case State(heap, size, takers, offerers) if heap.nonEmpty =>
val (rest, a) = heap.take
val (release, tail) = offerers.dequeue
State(rest, size - 1, takers, tail) -> release.complete(()).as(a.some)
case s =>
s -> F.pure(none[A])
}
.flatten
.uncancelable
def size: F[Int] =
ref.get.map(_.size)
}
private[std] final case class State[F[_], A](
heap: BinomialHeap[A],
size: Int,
takers: ScalaQueue[Deferred[F, Unit]],
offerers: ScalaQueue[Deferred[F, Unit]])
private[std] object State {
def empty[F[_], A: Order]: State[F, A] =
State(
BinomialHeap.empty[A],
0,
ScalaQueue.empty,
ScalaQueue.empty
)
}
implicit def catsInvariantForPQueue[F[_]: Functor]: Invariant[PQueue[F, *]] =
new Invariant[PQueue[F, *]] {
override def imap[A, B](fa: PQueue[F, A])(f: A => B)(g: B => A): PQueue[F, B] =
new PQueue[F, B] {
override def offer(b: B): F[Unit] =
fa.offer(g(b))
override def tryOffer(b: B): F[Boolean] =
fa.tryOffer(g(b))
override def take: F[B] =
fa.take.map(f)
override def tryTake: F[Option[B]] =
fa.tryTake.map(_.map(f))
override def size: F[Int] =
fa.size
}
}
private def assertNonNegative(capacity: Int): Unit =
if (capacity < 0)
throw new IllegalArgumentException(
s"Bounded queue capacity must be non-negative, was: $capacity")
else ()
}
trait PQueueSource[F[_], A] {
/**
* Dequeues the least element from the PQueue, possibly fiber blocking until an element
* becomes available.
*
* O(log(n))
*
* Note: If there are multiple elements with least priority, the order in which they are
* dequeued is undefined. If you want to break ties with FIFO order you will need an
* additional `Ref[F, Long]` to track insertion, and embed that information into your instance
* for `Order[A]`.
*/
def take: F[A]
/**
* Attempts to dequeue the least element from the PQueue, if one is available without fiber
* blocking.
*
* O(log(n))
*
* @return
* an effect that describes whether the dequeueing of an element from the PQueue succeeded
* without blocking, with `None` denoting that no element was available
*
* Note: If there are multiple elements with least priority, the order in which they are
* dequeued is undefined. If you want to break ties with FIFO order you will need an
* additional `Ref[F, Long]` to track insertion, and embed that information into your instance
* for `Order[A]`.
*/
def tryTake: F[Option[A]]
/**
* Attempts to dequeue elements from the PQueue, if they are available without semantically
* blocking. This is a convenience method that recursively runs `tryTake`. It does not provide
* any additional performance benefits.
*
* @param maxN
* The max elements to dequeue. Passing `None` will try to dequeue the whole queue.
*
* @return
* an effect that contains the dequeued elements from the PQueue
*
* Note: If there are multiple elements with least priority, the order in which they are
* dequeued is undefined.
*/
def tryTakeN(maxN: Option[Int])(implicit F: Monad[F]): F[List[A]] = {
PQueueSource.assertMaxNPositive(maxN)
def loop(i: Int, limit: Int, acc: List[A]): F[List[A]] =
if (i >= limit)
F.pure(acc.reverse)
else
tryTake flatMap {
case Some(a) => loop(i + 1, limit, a :: acc)
case None => F.pure(acc.reverse)
}
maxN match {
case Some(limit) => loop(0, limit, Nil)
case None => loop(0, Int.MaxValue, Nil)
}
}
def size: F[Int]
}
object PQueueSource {
private def assertMaxNPositive(maxN: Option[Int]): Unit = maxN match {
case Some(n) if n <= 0 =>
throw new IllegalArgumentException(s"Provided maxN parameter must be positive, was $n")
case _ => ()
}
implicit def catsFunctorForPQueueSource[F[_]: Functor]: Functor[PQueueSource[F, *]] =
new Functor[PQueueSource[F, *]] {
override def map[A, B](fa: PQueueSource[F, A])(f: A => B): PQueueSource[F, B] =
new PQueueSource[F, B] {
override def take: F[B] =
fa.take.map(f)
override def tryTake: F[Option[B]] =
fa.tryTake.map(_.map(f))
override def size: F[Int] =
fa.size
}
}
}
trait PQueueSink[F[_], A] {
/**
* Enqueues the given element, possibly fiber blocking until sufficient capacity becomes
* available.
*
* O(log(n))
*
* @param a
* the element to be put in the PQueue
*/
def offer(a: A): F[Unit]
/**
* Attempts to enqueue the given element without fiber blocking.
*
* O(log(n))
*
* @param a
* the element to be put in the PQueue
* @return
* an effect that describes whether the enqueuing of the given element succeeded without
* blocking
*/
def tryOffer(a: A): F[Boolean]
/**
* Attempts to enqueue the given elements without semantically blocking. If an item in the
* list cannot be enqueued, the remaining elements will be returned. This is a convenience
* method that recursively runs `tryOffer` and does not offer any additional performance
* benefits.
*
* @param list
* the elements to be put in the PQueue
* @return
* an effect that contains the remaining valus that could not be offered.
*/
def tryOfferN(list: List[A])(implicit F: Monad[F]): F[List[A]] = list match {
case Nil => F.pure(list)
case h :: t =>
tryOffer(h).ifM(
tryOfferN(t),
F.pure(list)
)
}
}
object PQueueSink {
implicit def catsContravariantForPQueueSink[F[_]]: Contravariant[PQueueSink[F, *]] =
new Contravariant[PQueueSink[F, *]] {
override def contramap[A, B](fa: PQueueSink[F, A])(f: B => A): PQueueSink[F, B] =
new PQueueSink[F, B] {
override def offer(b: B): F[Unit] =
fa.offer(f(b))
override def tryOffer(b: B): F[Boolean] =
fa.tryOffer(f(b))
}
}
}