-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ref.scala
322 lines (249 loc) · 9.53 KB
/
Ref.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
/*
* SPDX-License-Identifier: Apache-2.0
* Copyright 2016-2024 Daniel Urban and contributors listed in NOTICE.txt
*
* 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 dev.tauri.choam
package refs
import java.util.concurrent.ThreadLocalRandom
import scala.math.Ordering
import cats.kernel.{ Hash, Order }
import cats.effect.kernel.{ Ref => CatsRef }
import internal.mcas.MemoryLocation
import CompatPlatform.AtomicReferenceArray
/**
* A mutable memory location with a pure API and
* composable lock-free operations.
*
* `Ref` is similar to [[java.util.concurrent.atomic.AtomicReference]]
* or [[cats.effect.kernel.Ref]], but its operations are [[Rxn]]s.
* Thus, operations on a `Ref` are composable with other [[Rxn]]s.
*/
sealed trait Ref[A] extends RefLike[A] { this: MemoryLocation[A] =>
final override def get: Axn[A] =
Rxn.ref.get(this)
// TODO: needs better name (it's like `modify`)
final override def upd[B, C](f: (A, B) => (A, C)): Rxn[B, C] =
Rxn.ref.upd(this)(f)
// TODO: needs better name (it's like `modifyWith`)
final override def updWith[B, C](f: (A, B) => Axn[(A, C)]): Rxn[B, C] =
Rxn.ref.updWith(this)(f)
final def unsafeDirectRead: Axn[A] =
Rxn.unsafe.directRead(this)
final def unsafeTicketRead: Axn[Rxn.unsafe.Ticket[A]] =
Rxn.unsafe.ticketRead(this)
final def unsafeCas(ov: A, nv: A): Axn[Unit] =
Rxn.unsafe.cas(this, ov, nv)
final override def toCats[F[_]](implicit F: core.Reactive[F]): CatsRef[F, A] =
new Ref.CatsRefFromRef[F, A](this) {}
private[choam] final def loc: MemoryLocation[A] =
this
private[choam] def dummy(v: Long): Long
}
private[refs] trait UnsealedRef[A] extends Ref[A] { this: MemoryLocation[A] =>
}
object Ref extends RefInstances0 {
sealed trait Array[A] {
def size: Int
def unsafeGet(idx: Int): Ref[A]
def apply(idx: Int): Option[Ref[A]]
final def length: Int =
this.size
}
private[refs] trait UnsealedArray[A] extends Array[A] { this: RefIdOnly =>
protected[refs] final override def refToString(): String = {
val h = (id0 ^ id1 ^ id2 ^ id3) & (~0xffffL)
s"Ref.Array[${size}]@${java.lang.Long.toHexString(h >> 16)}"
}
protected final def checkIndex(idx: Int): Unit = {
if ((idx < 0) || (idx >= size)) {
throw new IndexOutOfBoundsException(s"Index ${idx} out of bounds for length ${size}")
}
}
}
private final class EmptyRefArray[A] extends Ref.Array[A] {
final override val size: Int =
0
final override def apply(idx: Int): Option[Ref[A]] =
None
final override def unsafeGet(idx: Int): Ref[A] =
throw new IndexOutOfBoundsException(s"Index ${idx} out of bounds for length 0")
final override def toString: String =
s"Ref.Array[0]@${java.lang.Long.toHexString(0L)}"
}
private[choam] final def apply[A](initial: A): Axn[Ref[A]] =
padded(initial)
// TODO: Figure out which array variants we actually need,
// TODO: and clean up the creation API. Currently there are
// TODO: 4 options: (sparse or not) × (flat or not).
// TODO: Another possible option would be to have padding.
// TODO: How to avoid allocating RefArrayRef objects?
// TODO: Create getAndUpdate(idx: Int, f: A => A) methods.
// TODO: But: what to do with out-of-bounds indices?
// TODO: (Refined? But can we avoid boxing?)
// TODO: Would implementing Traverse help? Probably not.
final def array[A](size: Int, initial: A): Axn[Ref.Array[A]] =
Axn.unsafe.delay(unsafeStrictArray(size, initial))
final def lazyArray[A](size: Int, initial: A): Axn[Ref.Array[A]] =
Axn.unsafe.delay(unsafeLazyArray(size, initial))
final def arrayOfRefs[A](_size: Int, _initial: A): Axn[Ref.Array[A]] = {
Axn.unsafe.delay {
if (_size == 0) new EmptyRefArray
else new Ref.Array[A] {
final override val size: Int =
_size
private[this] val arr: scala.Array[Ref[A]] = {
val a = new scala.Array[Ref[A]](size)
var idx = 0
while (idx < size) {
a(idx) = Ref.unsafeUnpadded(_initial)
idx += 1
}
a
}
final override def unsafeGet(idx: Int): Ref[A] = {
CompatPlatform.checkArrayIndexIfScalaJs(idx, size)
this.arr(idx)
}
final override def apply(idx: Int): Option[Ref[A]] = {
if ((idx >= 0) && (idx < size)) {
Some(this.unsafeGet(idx))
} else {
None
}
}
}
}
}
final def lazyArrayOfRefs[A](_size: Int, _initial: A): Axn[Ref.Array[A]] = {
Axn.unsafe.delay {
if (_size == 0) new EmptyRefArray
else new Ref.Array[A] {
final override val size: Int =
_size
private[this] val initial: A =
_initial
private[this] val arr: AtomicReferenceArray[Ref[A]] =
new AtomicReferenceArray[Ref[A]](size)
final override def unsafeGet(idx: Int): Ref[A] = {
val arr = this.arr
arr.getOpaque(idx) match { // FIXME: reading a `Ref` with a race!
case null =>
val nv = Ref.unsafe(initial)
val wit = arr.compareAndExchange(idx, null, nv)
if (wit eq null) {
nv // we're the first
} else {
wit // found other
}
case ref =>
ref
}
}
final override def apply(idx: Int): Option[Ref[A]] = {
if ((idx >= 0) && (idx < size)) {
Some(this.unsafeGet(idx))
} else {
None
}
}
}
}
}
private[choam] final def catsRefFromRef[F[_] : Reactive, A](ref: Ref[A]): CatsRef[F, A] =
new CatsRefFromRef[F, A](ref) {}
private[refs] abstract class CatsRefFromRef[F[_], A](self: Ref[A])(implicit F: Reactive[F])
extends RefLike.CatsRefFromRefLike[F, A](self)(F) {
override def get: F[A] =
self.unsafeDirectRead.run[F]
}
private[choam] final def unsafeStrictArray[A](size: Int, initial: A): Ref.Array[A] = {
if (size > 0) {
val tlr = ThreadLocalRandom.current()
unsafeNewStrictRefArray[A](size = size, initial = initial)(tlr.nextLong(), tlr.nextLong(), tlr.nextLong(), tlr.nextInt())
} else {
new EmptyRefArray
}
}
private[choam] final def unsafeLazyArray[A](size: Int, initial: A): Ref.Array[A] = {
if (size > 0) {
val tlr = ThreadLocalRandom.current()
unsafeNewLazyRefArray[A](size = size, initial = initial)(tlr.nextLong(), tlr.nextLong(), tlr.nextLong(), tlr.nextInt())
} else {
new EmptyRefArray
}
}
final def padded[A](initial: A): Axn[Ref[A]] =
Axn.unsafe.delay[Ref[A]](Ref.unsafe(initial))
final def unpadded[A](initial: A): Axn[Ref[A]] =
Axn.unsafe.delay[Ref[A]](Ref.unsafeUnpadded(initial))
private[choam] final def unsafe[A](initial: A): Ref[A] =
unsafePadded(initial)
private[choam] final def unsafePadded[A](initial: A): Ref[A] = {
val tlr = ThreadLocalRandom.current()
unsafeWithId(initial)(tlr.nextLong(), tlr.nextLong(), tlr.nextLong(), tlr.nextLong())
}
private[choam] final def unsafeUnpadded[A](initial: A): Ref[A] = {
val tlr = ThreadLocalRandom.current()
unsafeNewRefU1(initial)(tlr.nextLong(), tlr.nextLong(), tlr.nextLong(), tlr.nextLong())
}
/** Only for testing/benchmarks */
private[choam] def unsafeWithId[A](initial: A)(i0: Long, i1: Long, i2: Long, i3: Long): Ref[A] =
unsafeNewRefP1(initial)(i0, i1, i2, i3)
// Ref2:
def refP1P1[A, B](a: A, b: B): Axn[Ref2[A, B]] =
Ref2.p1p1(a, b)
def refP2[A, B](a: A, b: B): Axn[Ref2[A, B]] =
Ref2.p2(a, b)
// Utilities:
final def consistentRead[A, B](ra: Ref[A], rb: Ref[B]): Axn[(A, B)] = {
ra.get * rb.get
}
final def consistentReadMany[A](refs: List[Ref[A]]): Axn[List[A]] = {
refs.foldRight(Rxn.pure(List.empty[A])) { (ref, acc) =>
(ref.get * acc).map {
case (h, t) => h :: t
}
}
}
final def swap[A](r1: Ref[A], r2: Ref[A]): Axn[Unit] = {
r1.updateWith { o1 =>
r2.modify[A] { o2 =>
(o1, o2)
}
}
}
}
private[refs] sealed abstract class RefInstances0 extends RefInstances1 { this: Ref.type =>
private[this] val _orderingInstance: Ordering[Ref[Any]] = new Ordering[Ref[Any]] {
final override def compare(x: Ref[Any], y: Ref[Any]): Int =
MemoryLocation.globalCompare(x.loc, y.loc)
}
implicit final def orderingInstance[A]: Ordering[Ref[A]] =
_orderingInstance.asInstanceOf[Ordering[Ref[A]]]
}
private sealed abstract class RefInstances1 extends RefInstances2 { this: Ref.type =>
private[this] val _orderInstance: Order[Ref[Any]] = new Order[Ref[Any]] {
final override def compare(x: Ref[Any], y: Ref[Any]): Int =
MemoryLocation.globalCompare(x.loc, y.loc)
}
implicit final def orderInstance[A]: Order[Ref[A]] =
_orderInstance.asInstanceOf[Order[Ref[A]]]
}
private sealed abstract class RefInstances2 { this: Ref.type =>
private[this] val _hashInstance: Hash[Ref[Any]] =
Hash.fromUniversalHashCode[Ref[Any]]
implicit final def hashInstance[A]: Hash[Ref[A]] =
_hashInstance.asInstanceOf[Hash[Ref[A]]]
}