packages feed

pykinos-core-0.1.1.0: src/Pykinos/Queue/WordRing.hs

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-unused-matches -Wno-deprecations #-}
-- | Module: Pykinos.Queue.WordRing
-- Description: Unboxed power-of-two circular FIFO/LIFO deque with geometric resizing
--
-- Implements an unboxed double-ended queue over a single 'MutablePrimArray' of
-- 32-bit machine words (@Word32@). Supports amortized O(1) pushBack, popFront,
-- and popBack with zero per-element GC allocation overhead.
module Pykinos.Queue.WordRing
  ( WordRing
  , newWordRing
  , pushBack
  , popFront
  , popBack
  , ringLength
  , ringCapacity
  , clearRing
  ) where

import Control.Monad (when)
import Control.Monad.ST (ST)
import Data.Bits ((.&.))
import Data.Primitive.PrimArray
  ( MutablePrimArray
  , copyMutablePrimArray
  , newPrimArray
  , readPrimArray
  , sizeofMutablePrimArray
  , writePrimArray
  )
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)
import Data.Word (Word32)

-- | Circular power-of-two ring buffer in @ST s@.
data WordRing s = WordRing
  { wrArrRef :: !(STRef s (MutablePrimArray s Word32))
  , wrHead   :: !(STRef s Int)
  , wrTail   :: !(STRef s Int)
  , wrCount  :: !(STRef s Int)
  }

-- | Allocates an empty 'WordRing' with initial capacity rounded up to power of two (min 16).
newWordRing :: Int -> ST s (WordRing s)
newWordRing !minCap = do
  let !cap = nextPowerOfTwo (max 16 minCap)
  arr <- newPrimArray cap
  arrRef <- newSTRef arr
  hRef <- newSTRef 0
  tRef <- newSTRef 0
  cRef <- newSTRef 0
  pure (WordRing arrRef hRef tRef cRef)

-- | Returns the next power of two >= n.
nextPowerOfTwo :: Int -> Int
nextPowerOfTwo 0 = 1
nextPowerOfTwo !n = 1 `go` (n - 1)
  where
    go !acc 0 = acc
    go !acc k = go (acc * 2) (k `div` 2)

-- | Current number of elements stored in the ring.
ringLength :: WordRing s -> ST s Int
ringLength (WordRing _ _ _ cRef) = readSTRef cRef

-- | Total allocated slot capacity in the current underlying array.
ringCapacity :: WordRing s -> ST s Int
ringCapacity (WordRing arrRef _ _ _) = do
  arr <- readSTRef arrRef
  pure (sizeofMutablePrimArray arr)

-- | Resets the ring to empty without reallocating the underlying array.
clearRing :: WordRing s -> ST s ()
clearRing (WordRing _ hRef tRef cRef) = do
  writeSTRef hRef 0
  writeSTRef tRef 0
  writeSTRef cRef 0

-- | Enqueues a word at the back of the deque, doubling capacity if full.
pushBack :: WordRing s -> Word32 -> ST s ()
pushBack ring@(WordRing arrRef hRef tRef cRef) !val = do
  !cnt <- readSTRef cRef
  arr <- readSTRef arrRef
  let !cap = sizeofMutablePrimArray arr
  when (cnt == cap) $ do
    growRing ring
  !arr' <- readSTRef arrRef
  let !mask = sizeofMutablePrimArray arr' - 1
  !t <- readSTRef tRef
  writePrimArray arr' t val
  writeSTRef tRef ((t + 1) .&. mask)
  writeSTRef cRef (cnt + 1)

-- | Doubles the capacity of the ring buffer and straightens out elements.
growRing :: WordRing s -> ST s ()
growRing (WordRing arrRef hRef tRef cRef) = do
  oldArr <- readSTRef arrRef
  let !oldCap = sizeofMutablePrimArray oldArr
      !newCap = oldCap * 2
  newArr <- newPrimArray newCap
  !h <- readSTRef hRef
  !cnt <- readSTRef cRef
  -- Copy elements in logical order from h to 0..cnt-1 in newArr
  let !firstChunk = min cnt (oldCap - h)
      !secondChunk = cnt - firstChunk
  copyMutablePrimArray newArr 0 oldArr h firstChunk
  when (secondChunk > 0) $ do
    copyMutablePrimArray newArr firstChunk oldArr 0 secondChunk
  writeSTRef arrRef newArr
  writeSTRef hRef 0
  writeSTRef tRef cnt

-- | Dequeues a word from the front of the deque in O(1).
popFront :: WordRing s -> ST s (Maybe Word32)
popFront (WordRing arrRef hRef _ cRef) = do
  !cnt <- readSTRef cRef
  if cnt == 0
    then pure Nothing
    else do
      arr <- readSTRef arrRef
      let !mask = sizeofMutablePrimArray arr - 1
      !h <- readSTRef hRef
      val <- readPrimArray arr h
      writeSTRef hRef ((h + 1) .&. mask)
      writeSTRef cRef (cnt - 1)
      pure (Just val)

-- | Dequeues a word from the back of the deque (LIFO stack pop) in O(1).
popBack :: WordRing s -> ST s (Maybe Word32)
popBack (WordRing arrRef _ tRef cRef) = do
  !cnt <- readSTRef cRef
  if cnt == 0
    then pure Nothing
    else do
      arr <- readSTRef arrRef
      let !mask = sizeofMutablePrimArray arr - 1
      !t <- readSTRef tRef
      let !newT = (t - 1) .&. mask
      val <- readPrimArray arr newT
      writeSTRef tRef newT
      writeSTRef cRef (cnt - 1)
      pure (Just val)