Skip to content

Instantly share code, notes, and snippets.

@ChristopherDavenport
Created September 1, 2021 18:18
Show Gist options
  • Save ChristopherDavenport/f9875d7dc58687da8cd3343677cf7d84 to your computer and use it in GitHub Desktop.
Save ChristopherDavenport/f9875d7dc58687da8cd3343677cf7d84 to your computer and use it in GitHub Desktop.
Fiber Local Basic Implementation
trait FiberLocal[F[_], A]{
def get: F[A]
def set(value: A): F[Unit]
def reset: F[Unit]
def update(f: A => A): F[Unit]
def modify[B](f: A => (A, B)): F[B]
def getAndSet(value: A): F[A]
def getAndReset: F[A]
}
object FiberLocal {
def fromIOLocal[F[_]: LiftIO, A](local: IOLocal[A]): FiberLocal[F, A] = new FiberLocal[F, A] {
def get: F[A] = LiftIO[F].liftIO(local.get)
def set(value: A): F[Unit] = LiftIO[F].liftIO(local.set(value))
def reset: F[Unit] = LiftIO[F].liftIO(local.reset)
def update(f: A => A): F[Unit] = LiftIO[F].liftIO(local.update(f))
def modify[B](f: A => (A, B)): F[B] = LiftIO[F].liftIO(local.modify(f))
def getAndSet(value: A): F[A] = LiftIO[F].liftIO(local.getAndSet(value))
def getAndReset: F[A] = LiftIO[F].liftIO(local.getAndReset)
}
}
trait GenFiberLocal[F[_]]{
def local[A](default: A): F[FiberLocal[F, A]]
}
object GenFiberLocal {
def fromLiftIO[F[_]: LiftIO: Functor]: GenFiberLocal[F] = new GenFiberLocal[F] {
def local[A](default: A): F[FiberLocal[F,A]] = LiftIO[F].liftIO(IOLocal(default)).map( local =>
FiberLocal.fromIOLocal(local)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment