Skip to content

Commit

Permalink
TRef#getAndSet
Browse files Browse the repository at this point in the history
  • Loading branch information
durban committed Jan 6, 2025
1 parent d8481c5 commit 2d9fdca
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ lazy val stm = crossProject(JVMPlatform, JSPlatform)
// there is no backward compat for `choam-stm`:
ProblemFilters.exclude[ReversedMissingMethodProblem]("dev.tauri.choam.stm.TRef.update"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("dev.tauri.choam.stm.TRef.modify"),
ProblemFilters.exclude[ReversedMissingMethodProblem]("dev.tauri.choam.stm.TRef.getAndSet"),
),
)

Expand Down
3 changes: 3 additions & 0 deletions stm/js/src/main/scala/dev/tauri/choam/stm/TRefImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ private final class TRefImpl[F[_], A](
final override def modify[B](f: A => (A, B)): Txn[F, B] =
core.Rxn.loc.upd[A, Any, B](this) { (ov, _) => f(ov) }.castF[F]

final override def getAndSet(a: A): Txn[F, A] =
this.modify { ov => (a, ov) }

final override def hashCode: Int = {
// `RefIdGen` generates IDs with
// Fibonacci hashing, so no need
Expand Down
3 changes: 3 additions & 0 deletions stm/jvm/src/main/scala/dev/tauri/choam/stm/TRefImpl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ private final class TRefImpl[F[_], A](
final override def modify[B](f: A => (A, B)): Txn[F, B] =
core.Rxn.loc.upd[A, Any, B](this) { (ov, _) => f(ov) }.castF[F]

final override def getAndSet(a: A): Txn[F, A] =
this.modify { ov => (a, ov) }

final override def hashCode: Int = {
// `RefIdGen` generates IDs with
// Fibonacci hashing, so no need
Expand Down
1 change: 1 addition & 0 deletions stm/shared/src/main/scala/dev/tauri/choam/stm/TRef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ sealed trait TRef[F[_], A] {
def set(a: A): Txn[F, Unit]
def update(f: A => A): Txn[F, Unit]
def modify[B](f: A => (A, B)): Txn[F, B]
def getAndSet(a: A): Txn[F, A]
}

object TRef {
Expand Down
8 changes: 8 additions & 0 deletions stm/shared/src/test/scala/dev/tauri/choam/stm/TxnSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,14 @@ trait TxnSpec[F[_]] extends TxnBaseSpec[F] { this: McasImplSpec =>
_ <- assertResultF(r.get.commit, 1)
} yield ()
}

test("TRef#getAndSet") {
for {
r <- TRef[F, Int](0).commit
_ <- assertResultF(r.getAndSet(42).commit, 0)
_ <- assertResultF(r.get.commit, 42)
} yield ()
}
}

trait TxnSpecTicked[F[_]] extends TxnBaseSpec[F] with TestContextSpec[F] { this: McasImplSpec =>
Expand Down

0 comments on commit 2d9fdca

Please sign in to comment.