packages feed

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

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}
-- | Module: Pykinos.Queue.WordHeap8
-- Description: Flat 8-ary implicit min-heap of (Word64, Word32) packed in contiguous memory
--
-- Implements an 8-ary cache-conscious min-priority queue over unboxed 'MutablePrimArray's.
-- With an arity of 8, each internal node's 8 children are contiguous in memory (sharing
-- adjacent cache lines), and tree height is $\log_8(N)$ rather than $\log_2(N)$ (3x fewer levels).
module Pykinos.Queue.WordHeap8
  ( WordHeap8
  , newWordHeap8
  , insertHeap8
  , findMinHeap8
  , popMinHeap8
  , heap8Size
  ) where

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

-- | Flat 8-ary unboxed implicit min-heap in @ST s@.
data WordHeap8 s = WordHeap8
  { whKeys  :: !(STRef s (MutablePrimArray s Word64))
  , whVals  :: !(STRef s (MutablePrimArray s Word32))
  , whCount :: !(STRef s Int)
  }

-- | Allocates an empty 8-ary min-heap with initial capacity (min 16).
newWordHeap8 :: Int -> ST s (WordHeap8 s)
newWordHeap8 !minCap = do
  let !cap = max 16 minCap
  kArr <- newPrimArray cap
  vArr <- newPrimArray cap
  kRef <- newSTRef kArr
  vRef <- newSTRef vArr
  cRef <- newSTRef 0
  pure (WordHeap8 kRef vRef cRef)

-- | Current number of elements in the heap.
heap8Size :: WordHeap8 s -> ST s Int
heap8Size (WordHeap8 _ _ cRef) = readSTRef cRef

-- | Inserts @(key, payload)@ into the heap and sifts up along the $\log_8(N)$ branch.
insertHeap8 :: WordHeap8 s -> Word64 -> Word32 -> ST s ()
insertHeap8 (WordHeap8 kRef vRef cRef) !k !v = do
  !cnt <- readSTRef cRef
  kArr <- readSTRef kRef
  let !cap = sizeofMutablePrimArray kArr
  when (cnt == cap) $ do
    let !newCap = cap * 2
    newK <- newPrimArray newCap
    newV <- newPrimArray newCap
    vArr <- readSTRef vRef
    copyMutablePrimArray newK 0 kArr 0 cnt
    copyMutablePrimArray newV 0 vArr 0 cnt
    writeSTRef kRef newK
    writeSTRef vRef newV
  curKArr <- readSTRef kRef
  curVArr <- readSTRef vRef
  writePrimArray curKArr cnt k
  writePrimArray curVArr cnt v
  writeSTRef cRef (cnt + 1)
  siftUp curKArr curVArr cnt

-- | Sifts up element at index @i@ until heap invariant holds.
siftUp :: MutablePrimArray s Word64 -> MutablePrimArray s Word32 -> Int -> ST s ()
siftUp !kArr !vArr !i
  | i <= 0    = pure ()
  | otherwise = do
      let !p = (i - 1) `div` 8
      pk <- readPrimArray kArr p
      ik <- readPrimArray kArr i
      when (ik < pk) $ do
        pv <- readPrimArray vArr p
        iv <- readPrimArray vArr i
        writePrimArray kArr p ik
        writePrimArray vArr p iv
        writePrimArray kArr i pk
        writePrimArray vArr i pv
        siftUp kArr vArr p

-- | Peeks at the minimum @(key, payload)@ in O(1).
findMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))
findMinHeap8 (WordHeap8 kRef vRef cRef) = do
  !cnt <- readSTRef cRef
  if cnt == 0
    then pure Nothing
    else do
      kArr <- readSTRef kRef
      vArr <- readSTRef vRef
      k <- readPrimArray kArr 0
      v <- readPrimArray vArr 0
      pure (Just (k, v))

-- | Pops the minimum @(key, payload)@ and sifts down the replacement root.
popMinHeap8 :: WordHeap8 s -> ST s (Maybe (Word64, Word32))
popMinHeap8 (WordHeap8 kRef vRef cRef) = do
  !cnt <- readSTRef cRef
  if cnt == 0
    then pure Nothing
    else do
      kArr <- readSTRef kRef
      vArr <- readSTRef vRef
      minK <- readPrimArray kArr 0
      minV <- readPrimArray vArr 0
      let !lastIdx = cnt - 1
      lastK <- readPrimArray kArr lastIdx
      lastV <- readPrimArray vArr lastIdx
      writePrimArray kArr 0 lastK
      writePrimArray vArr 0 lastV
      writeSTRef cRef lastIdx
      when (lastIdx > 1) $ do
        siftDown kArr vArr lastIdx 0
      pure (Just (minK, minV))

-- | Sifts down element at index @i@ across its up to 8 contiguous children.
siftDown :: MutablePrimArray s Word64 -> MutablePrimArray s Word32 -> Int -> Int -> ST s ()
siftDown !kArr !vArr !n !i = do
  let !firstChild = 8 * i + 1
  if firstChild >= n
    then pure ()
    else do
      let !lastChild = min (firstChild + 7) (n - 1)
      -- Find smallest child among [firstChild .. lastChild]
      let findBestChild !c !bestIdx !bestK
            | c > lastChild = pure bestIdx
            | otherwise = do
                ck <- readPrimArray kArr c
                if ck < bestK
                  then findBestChild (c + 1) c ck
                  else findBestChild (c + 1) bestIdx bestK
      firstK <- readPrimArray kArr firstChild
      !bestChildIdx <- findBestChild (firstChild + 1) firstChild firstK
      bestChildK <- readPrimArray kArr bestChildIdx
      curK <- readPrimArray kArr i
      when (bestChildK < curK) $ do
        curV <- readPrimArray vArr i
        bestChildV <- readPrimArray vArr bestChildIdx
        writePrimArray kArr i bestChildK
        writePrimArray vArr i bestChildV
        writePrimArray kArr bestChildIdx curK
        writePrimArray vArr bestChildIdx curV
        siftDown kArr vArr n bestChildIdx