Advertisement
Cool_Dalek

Scala3 example of switch low-level optimisation

Apr 6th, 2022
1,102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.19 KB | None | 0 0
  1. import ProcessState.*
  2.  
  3. type ProcessState = Stop | Running | Idle
  4. object ProcessState {
  5.   type Stop = 1
  6.   val Stop: Stop = 1
  7.   type Running = 2
  8.   val Running: Running = 2
  9.   type Idle = 3
  10.   val Idle: Idle = 3
  11. }
  12.  
  13. import java.util.concurrent.atomic.AtomicInteger
  14.  
  15. opaque type AtomicProcessState = AtomicInteger
  16. object AtomicProcessState {
  17.  
  18.   inline def apply(initial: ProcessState): AtomicProcessState = AtomicInteger(initial)
  19.  
  20.   extension (self: AtomicProcessState) {
  21.  
  22.     inline def compareAndSet(expected: ProcessState, newValue: ProcessState): Boolean =
  23.       self.compareAndSet(expected, newValue)
  24.  
  25.     inline def set(value: ProcessState): Unit =
  26.       self.set(value)
  27.  
  28.     inline def get(): ProcessState =
  29.       self.get().asInstanceOf[ProcessState]
  30.  
  31.   }
  32.  
  33. }
  34.  
  35.  
  36.   protected val state: AtomicProcessState = AtomicProcessState(ProcessState.Idle)
  37.   private def tell(queue: ConcurrentLinkedQueue[T], message: T): Unit = {
  38.     import ProcessState.*
  39.     (state.get(): @switch) match {
  40.       case Stop =>
  41.         runtime.reportFailure(Undelivered(message))
  42.       case Running =>
  43.         queue.add(message)
  44.       case Idle =>
  45.         queue.add(message)
  46.         continue()
  47.     }
  48.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement