{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE UnboxedTuples #-}

-- |
-- Module      : Pykinos.Mutable.SwissTable
-- Description : Zero-GC SWAR open-addressed hash-consing table over MutableByteArray#.
--
-- Maps 128-bit unboxed keys @(Word64, Word64)@ to 32-bit unboxed IDs ('Int32')
-- with 8-slot SWAR parallel control probing and zero boxed heap pointers.
module Pykinos.Mutable.SwissTable
  ( SwissTable128(..)
  , newSwissTable128
  , lookupOrInsert128
  , packNfNode128
  , matchH2Swar64
  ) where

import Control.Monad (when)
import Control.Monad.ST (ST)
import Data.Bits
  ( complement
  , countTrailingZeros
  , unsafeShiftL
  , unsafeShiftR
  , xor
  , (.&.)
  , (.|.)
  )
import Data.Int (Int32)
import Data.Primitive.ByteArray
  ( MutableByteArray(..)
  , newByteArray
  , readByteArray
  , setByteArray
  , writeByteArray
  )
import Data.Word (Word8, Word32, Word64)
import GHC.Exts (Int(..), readWord8ArrayAsWord64#)
import GHC.Word (Word64(W64#))
import GHC.ST (ST(..))

-- | Open-addressed SwissTable with mutable unboxed slabs wrapped in a 4-slot descriptor.
--   Because all slabs are 'MutableByteArray', GHC's GC never scans the table entries.
data SwissTable128 s = SwissTable128
  { forall s. SwissTable128 s -> MutableByteArray s
stArrays :: !(MutableByteArray s)
    -- ^ Int32[0] = count, Int32[1] = cap, Int32[2] = maxLoad
  , forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stCtrlRef :: !(SmallRef s (MutableByteArray s))
  , forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stKeysRef :: !(SmallRef s (MutableByteArray s))
  , forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stValsRef :: !(SmallRef s (MutableByteArray s))
  }

-- | Lightweight 1-slot mutable box for swapping grown ByteArrays.
newtype SmallRef s a = SmallRef (MutableByteArray s)

ctrlEmpty :: Word8
ctrlEmpty :: Word8
ctrlEmpty = Word8
0x80

-- | Allocate a power-of-two 'SwissTable128' (minimum capacity 16).
newSwissTable128 :: Int -> ST s (SwissTable128 s)
newSwissTable128 :: forall s. Int -> ST s (SwissTable128 s)
newSwissTable128 !Int
reqCap = do
  let !cap :: Int
cap     = Int -> Int
nextPow2 (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
16 Int
reqCap)
      !maxLoad :: Int
maxLoad = (Int
cap Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
7) Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
3
  ctrl <- Int -> ST s (MutableByteArray (PrimState (ST s)))
forall (m :: * -> *).
PrimMonad m =>
Int -> m (MutableByteArray (PrimState m))
newByteArray (Int
cap Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8)
  setByteArray ctrl 0 (cap + 8) ctrlEmpty
  keys <- newByteArray (cap * 16)
  vals <- newByteArray (cap * 4)
  st   <- newByteArray 12
  writeByteArray st 0 (0 :: Int32)
  writeByteArray st 1 (fromIntegral cap :: Int32)
  writeByteArray st 2 (fromIntegral maxLoad :: Int32)
  pure (SwissTable128 st (SmallRef ctrl) (SmallRef keys) (SmallRef vals))

nextPow2 :: Int -> Int
nextPow2 :: Int -> Int
nextPow2 !Int
n = Int -> Int
go Int
16
  where
    go :: Int -> Int
go !Int
p | Int
p Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
n    = Int
p
          | Bool
otherwise = Int -> Int
go (Int
p Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`unsafeShiftL` Int
1)

{-# INLINE hash128 #-}
hash128 :: Word64 -> Word64 -> Word64
hash128 :: Word64 -> Word64 -> Word64
hash128 !Word64
kLo !Word64
kHi =
  let !h0 :: Word64
h0 = (Word64
kLo Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` (Word64
kHi Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
0x9E3779B97F4A7C15)) Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
0xBF58476D1CE4E5B9
      !h1 :: Word64
h1 = (Word64
h0 Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` (Word64
h0 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
30)) Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word64
0x94D049BB133111EB
  in Word64
h1 Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` (Word64
h1 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
31)

{-# INLINE readCtrlGroup64 #-}
readCtrlGroup64 :: MutableByteArray s -> Int -> ST s Word64
readCtrlGroup64 :: forall s. MutableByteArray s -> Int -> ST s Word64
readCtrlGroup64 (MutableByteArray MutableByteArray# s
mba#) (I# Int#
slot#) = STRep s Word64 -> ST s Word64
forall s a. STRep s a -> ST s a
ST (STRep s Word64 -> ST s Word64) -> STRep s Word64 -> ST s Word64
forall a b. (a -> b) -> a -> b
$ \State# s
s0 ->
  case MutableByteArray# s -> Int# -> State# s -> (# State# s, Word64# #)
forall d.
MutableByteArray# d -> Int# -> State# d -> (# State# d, Word64# #)
readWord8ArrayAsWord64# MutableByteArray# s
mba# Int#
slot# State# s
s0 of
    (# State# s
s1, Word64#
w# #) -> (# State# s
s1, Word64# -> Word64
W64# Word64#
w# #)

{-# INLINE writeCtrlByte #-}
writeCtrlByte :: MutableByteArray s -> Int -> Int -> Word8 -> ST s ()
writeCtrlByte :: forall s. MutableByteArray s -> Int -> Int -> Word8 -> ST s ()
writeCtrlByte !MutableByteArray s
ctrl !Int
cap !Int
slot !Word8
b = do
  MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
ctrl Int
slot Word8
b
  Bool -> ST s () -> ST s ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
slot Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
8) (ST s () -> ST s ()) -> ST s () -> ST s ()
forall a b. (a -> b) -> a -> b
$
    MutableByteArray (PrimState (ST s)) -> Int -> Word8 -> ST s ()
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> a -> m ()
writeByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
ctrl (Int
cap Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
slot) Word8
b

-- | Borrow-free SWAR match returning bit (8*i + 7) == 1 iff byte i equals h2.
{-# INLINE matchH2Swar64 #-}
matchH2Swar64 :: Word64 -> Word8 -> Word64
matchH2Swar64 :: Word64 -> Word8 -> Word64
matchH2Swar64 !Word64
ctrlWord !Word8
h2 =
  let !pat :: Word64
pat  = Word64
0x0101010101010101 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
* Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
h2
      !x :: Word64
x    = Word64
ctrlWord Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
`xor` Word64
pat
      !low7 :: Word64
low7 = (Word64
x Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64
0x7F7F7F7F7F7F7F7F) Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
0x7F7F7F7F7F7F7F7F
  in Word64 -> Word64
forall a. Bits a => a -> a
complement (Word64
low7 Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word64
x Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word64
0x7F7F7F7F7F7F7F7F)

{-# INLINE matchEmptySwar64 #-}
matchEmptySwar64 :: Word64 -> Word64
matchEmptySwar64 :: Word64 -> Word64
matchEmptySwar64 !Word64
ctrlWord = Word64
ctrlWord Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64
0x8080808080808080

-- | Lookup or insert a 128-bit key, returning its dense monotonic Int32 ID.
{-# INLINE lookupOrInsert128 #-}
lookupOrInsert128
  :: SwissTable128 s
  -> Word64
  -> Word64
  -> ST s Int32
lookupOrInsert128 :: forall s. SwissTable128 s -> Word64 -> Word64 -> ST s Int32
lookupOrInsert128 SwissTable128{MutableByteArray s
SmallRef s (MutableByteArray s)
stArrays :: forall s. SwissTable128 s -> MutableByteArray s
stCtrlRef :: forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stKeysRef :: forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stValsRef :: forall s. SwissTable128 s -> SmallRef s (MutableByteArray s)
stArrays :: MutableByteArray s
stCtrlRef :: SmallRef s (MutableByteArray s)
stKeysRef :: SmallRef s (MutableByteArray s)
stValsRef :: SmallRef s (MutableByteArray s)
..} !Word64
keyLo !Word64
keyHi = do
  let SmallRef MutableByteArray s
ctrl = SmallRef s (MutableByteArray s)
stCtrlRef
      SmallRef MutableByteArray s
keys = SmallRef s (MutableByteArray s)
stKeysRef
      SmallRef MutableByteArray s
vals = SmallRef s (MutableByteArray s)
stValsRef
  cap32 :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
stArrays Int
1
  let !cap  = Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cap32 :: Int
      !mask = Int
cap Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1
      !h    = Word64 -> Word64 -> Word64
hash128 Word64
keyLo Word64
keyHi
      !h1   = Word64 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64
h Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
7) :: Int
      !h2   = Word64 -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word64
h Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.&. Word64
0x7F) :: Word8

      probeGroup !Int
groupStart !Int
step = do
        !ctrlWord <- MutableByteArray s -> Int -> ST s Word64
forall s. MutableByteArray s -> Int -> ST s Word64
readCtrlGroup64 MutableByteArray s
ctrl Int
groupStart
        let !hitMask = Word64 -> Word8 -> Word64
matchH2Swar64 Word64
ctrlWord Word8
h2
        mbFound <- checkHits groupStart mask hitMask
        case mbFound of
          Just Int32
existingVal -> Int32 -> ST s Int32
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Int32
existingVal
          Maybe Int32
Nothing -> do
            let !empMask :: Word64
empMask = Word64 -> Word64
matchEmptySwar64 Word64
ctrlWord
            if Word64
empMask Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word64
0
              then do
                let !byteIdx :: Int
byteIdx = Word64 -> Int
forall b. FiniteBits b => b -> Int
countTrailingZeros Word64
empMask Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
3
                    !slot :: Int
slot    = (Int
groupStart Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
byteIdx) Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
mask
                cnt :: Int32 <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Int32
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
stArrays Int
0
                writeByteArray stArrays 0 (cnt + 1)
                writeCtrlByte ctrl cap slot h2
                writeByteArray keys (slot * 2)     keyLo
                writeByteArray keys (slot * 2 + 1) keyHi
                writeByteArray vals slot           cnt
                pure cnt
              else
                Int -> Int -> ST s Int32
probeGroup ((Int
groupStart Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
step) Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
mask) (Int
step Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
8)

      checkHits !Int
groupStart !Int
msk !Word64
m
        | Word64
m Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
0 = Maybe Int32 -> ST s (Maybe Int32)
forall a. a -> ST s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Int32
forall a. Maybe a
Nothing
        | Bool
otherwise = do
            let !byteIdx :: Int
byteIdx = Word64 -> Int
forall b. FiniteBits b => b -> Int
countTrailingZeros Word64
m Int -> Int -> Int
forall a. Bits a => a -> Int -> a
`unsafeShiftR` Int
3
                !slot :: Int
slot    = (Int
groupStart Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
byteIdx) Int -> Int -> Int
forall a. Bits a => a -> a -> a
.&. Int
msk
            !kLo <- MutableByteArray (PrimState (ST s)) -> Int -> ST s Word64
forall a (m :: * -> *).
(Prim a, PrimMonad m) =>
MutableByteArray (PrimState m) -> Int -> m a
readByteArray MutableByteArray s
MutableByteArray (PrimState (ST s))
keys (Int
slot Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
2)
            !kHi <- readByteArray keys (slot * 2 + 1)
            if kLo == keyLo && kHi == keyHi
              then Just <$> readByteArray vals slot
              else checkHits groupStart msk (m .&. (m - 1))

  probeGroup (h1 .&. mask) 8

-- | Pack a fixed-arity normal-form DAG node into a 128-bit SwissTable key.
{-# INLINE packNfNode128 #-}
packNfNode128 :: Word8 -> Word32 -> Int32 -> Int32 -> Int32 -> (Word64, Word64)
packNfNode128 :: Word8 -> Word32 -> Int32 -> Int32 -> Int32 -> (Word64, Word64)
packNfNode128 !Word8
tag !Word32
aux !Int32
cA !Int32
cB !Int32
cC =
  let !lo :: Word64
lo = (Word8 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
tag Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftL` Int
56)
        Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. (Word32 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word32
aux Word32 -> Word32 -> Word32
forall a. Bits a => a -> a -> a
.&. Word32
0x00FFFFFF) Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftL` Int
32)
        Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word32 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cA :: Word32)
      !hi :: Word64
hi = (Word32 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cB :: Word32) Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`unsafeShiftL` Int
32)
        Word64 -> Word64 -> Word64
forall a. Bits a => a -> a -> a
.|. Word32 -> Word64
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int32 -> Word32
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
cC :: Word32)
  in (Word64
lo, Word64
hi)