packages feed

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

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -Wno-unused-top-binds -Wno-deprecations #-}
-- | Module: Pykinos.Queue.BitTrie64
-- Description: 3-level 64-ary unboxed Word64 bitmap priority set-queue over [0..262143]
--
-- Represents a dynamic set/priority queue of dense 18-bit unsigned integers
-- (@0 .. 262143 = 64^3 - 1@) using two flat unscanned 'MutablePrimArray's
-- (@L1@ = 64 words = 512 B, @L2@ = 4096 words = 32 KiB) and a 1-word root
-- summary mask. All operations run in O(1) time with zero GC pointer scanning.
module Pykinos.Queue.BitTrie64
  ( maxBitTrieKey
  , BitTrie64
  , newBitTrie64
  , insertTrie
  , deleteTrie
  , memberTrie
  , findMinTrie
  , findMaxTrie
  , popMinTrie
  ) where

import Control.Monad.ST (ST)
import Data.Bits
  ( clearBit
  , countLeadingZeros
  , countTrailingZeros
  , setBit
  , shiftL
  , shiftR
  , testBit
  , (.&.)
  , (.|.)
  )
import Data.Primitive.PrimArray
  ( MutablePrimArray
  , newPrimArray
  , readPrimArray
  , setPrimArray
  , writePrimArray
  )
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)
import Data.Word (Word64)

-- | Maximum supported key (@64^3 - 1 = 262143@).
maxBitTrieKey :: Int
maxBitTrieKey = 262143

-- | 3-level 64-ary bitmap trie in @ST s@ (zero GC pointers).
data BitTrie64 s = BitTrie64
  { btRoot :: !(STRef s Word64)
  , btL1   :: !(MutablePrimArray s Word64) -- ^ 64 words
  , btL2   :: !(MutablePrimArray s Word64) -- ^ 4096 words
  }

-- | Allocates an empty 'BitTrie64'.
newBitTrie64 :: ST s (BitTrie64 s)
newBitTrie64 = do
  rootRef <- newSTRef 0
  l1 <- newPrimArray 64
  setPrimArray l1 0 64 (0 :: Word64)
  l2 <- newPrimArray 4096
  setPrimArray l2 0 4096 (0 :: Word64)
  pure (BitTrie64 rootRef l1 l2)

-- | Inserts @k@ in O(1). Returns 'True' if @k@ was newly inserted.
insertTrie :: BitTrie64 s -> Int -> ST s Bool
insertTrie (BitTrie64 rootRef l1 l2) !k
  | k < 0 || k > maxBitTrieKey = pure False
  | otherwise = do
      let !idx2 = k `shiftR` 6
          !bit2 = k .&. 63
          !idx1 = idx2 `shiftR` 6
          !bit1 = idx2 .&. 63
      w2 <- readPrimArray l2 idx2
      if testBit w2 bit2
        then pure False
        else do
          writePrimArray l2 idx2 (setBit w2 bit2)
          w1 <- readPrimArray l1 idx1
          writePrimArray l1 idx1 (setBit w1 bit1)
          r0 <- readSTRef rootRef
          writeSTRef rootRef (setBit r0 idx1)
          pure True

-- | Deletes @k@ in O(1). Returns 'True' if @k@ was present.
deleteTrie :: BitTrie64 s -> Int -> ST s Bool
deleteTrie (BitTrie64 rootRef l1 l2) !k
  | k < 0 || k > maxBitTrieKey = pure False
  | otherwise = do
      let !idx2 = k `shiftR` 6
          !bit2 = k .&. 63
          !idx1 = idx2 `shiftR` 6
          !bit1 = idx2 .&. 63
      w2 <- readPrimArray l2 idx2
      if not (testBit w2 bit2)
        then pure False
        else do
          let !w2' = clearBit w2 bit2
          writePrimArray l2 idx2 w2'
          if w2' /= 0
            then pure True
            else do
              w1 <- readPrimArray l1 idx1
              let !w1' = clearBit w1 bit1
              writePrimArray l1 idx1 w1'
              if w1' /= 0
                then pure True
                else do
                  r0 <- readSTRef rootRef
                  writeSTRef rootRef (clearBit r0 idx1)
                  pure True

-- | Tests membership of @k@ in O(1) with a single L2 word read.
memberTrie :: BitTrie64 s -> Int -> ST s Bool
memberTrie (BitTrie64 _ _ l2) !k
  | k < 0 || k > maxBitTrieKey = pure False
  | otherwise = do
      w2 <- readPrimArray l2 (k `shiftR` 6)
      pure (testBit w2 (k .&. 63))

-- | Returns the smallest present key in O(1) via three @ctz@ instructions.
findMinTrie :: BitTrie64 s -> ST s (Maybe Int)
findMinTrie (BitTrie64 rootRef l1 l2) = do
  r0 <- readSTRef rootRef
  if r0 == 0
    then pure Nothing
    else do
      let !idx1 = countTrailingZeros r0
      w1 <- readPrimArray l1 idx1
      let !bit1 = countTrailingZeros w1
          !idx2 = (idx1 `shiftL` 6) .|. bit1
      w2 <- readPrimArray l2 idx2
      let !bit2 = countTrailingZeros w2
      pure (Just ((idx2 `shiftL` 6) .|. bit2))

-- | Returns the largest present key in O(1) via three @clz@ instructions.
findMaxTrie :: BitTrie64 s -> ST s (Maybe Int)
findMaxTrie (BitTrie64 rootRef l1 l2) = do
  r0 <- readSTRef rootRef
  if r0 == 0
    then pure Nothing
    else do
      let !idx1 = 63 - countLeadingZeros r0
      w1 <- readPrimArray l1 idx1
      let !bit1 = 63 - countLeadingZeros w1
          !idx2 = (idx1 `shiftL` 6) .|. bit1
      w2 <- readPrimArray l2 idx2
      let !bit2 = countTrailingZeros w2
      pure (Just ((idx2 `shiftL` 6) .|. bit2))

-- | Extracts and deletes the minimum key in O(1).
popMinTrie :: BitTrie64 s -> ST s (Maybe Int)
popMinTrie trie = do
  m <- findMinTrie trie
  case m of
    Nothing -> pure Nothing
    Just k  -> do
      _ <- deleteTrie trie k
      pure (Just k)