packages feed

pykinos-penelope-0.1.1.0: src/Pykinos/Penelope/WriterSlab.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE TupleSections #-}

-- | Module: Pykinos.Penelope.WriterSlab
-- Description: Sub-4KB chunked append slab with O(1) watermark Listen and in-place Censor
--
-- Replaces pointer-chasing @[a]@ / @DList@ Writer accumulators with contiguous
-- 64-slot 'SmallMutableArray' chunks (512 bytes per chunk, strictly nursery-safe
-- under GHC's 3277-byte @BF_LARGE@ threshold).
module Pykinos.Penelope.WriterSlab
  ( slabChunkSize
  , SlabMark(..)
  , WriterSlab
  , newWriterSlab
  , tellSlab
  , tellManySlab
  , markSlab
  , listenSlice
  , censorSlice
  , freezeSlab
  ) where

import Control.Monad (forM_)
import Control.Monad.ST (ST)
import Data.Primitive.SmallArray
  ( SmallMutableArray
  , newSmallArray
  , readSmallArray
  , writeSmallArray
  )
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)

-- | Fixed chunk capacity (64 words = 512 bytes; strictly Sub4KB nursery-safe).
slabChunkSize :: Int
slabChunkSize = 64

-- | O(1) cursor watermark into a 'WriterSlab'.
newtype SlabMark = SlabMark { unSlabMark :: Int }
  deriving stock (Eq, Ord, Show)

-- | Internal linked list of fixed-capacity chunks (stored newest-first for O(1) append).
data SlabState s a = SlabState
  { ssTotal     :: !Int
  , ssChunkUsed :: !Int
  , ssCurrent   :: !(SmallMutableArray s a)
  , ssFullRev   :: ![SmallMutableArray s a]
  }

-- | Transient chunked append slab for high-throughput @Writer@ effects in @ST s@.
newtype WriterSlab s a = WriterSlab (STRef s (SlabState s a))

-- | Allocates a fresh empty 'WriterSlab'.
newWriterSlab :: ST s (WriterSlab s a)
newWriterSlab = do
  arr <- newSmallArray slabChunkSize (error "WriterSlab: uninitialized slot")
  ref <- newSTRef (SlabState 0 0 arr [])
  pure (WriterSlab ref)

-- | Appends a single element in amortized O(1) time.
tellSlab :: WriterSlab s a -> a -> ST s ()
tellSlab (WriterSlab ref) !x = do
  st <- readSTRef ref
  if ssChunkUsed st < slabChunkSize
    then do
      writeSmallArray (ssCurrent st) (ssChunkUsed st) x
      writeSTRef ref st
        { ssTotal     = ssTotal st + 1
        , ssChunkUsed = ssChunkUsed st + 1
        }
    else do
      fresh <- newSmallArray slabChunkSize (error "WriterSlab: uninitialized slot")
      writeSmallArray fresh 0 x
      writeSTRef ref SlabState
        { ssTotal     = ssTotal st + 1
        , ssChunkUsed = 1
        , ssCurrent   = fresh
        , ssFullRev   = ssCurrent st : ssFullRev st
        }

-- | Appends a foldable sequence of elements.
tellManySlab :: Foldable t => WriterSlab s a -> t a -> ST s ()
tellManySlab slab = mapM_ (tellSlab slab)

-- | Captures the current append position in O(1) for 'listenSlice' or 'censorSlice'.
markSlab :: WriterSlab s a -> ST s SlabMark
markSlab (WriterSlab ref) = SlabMark . ssTotal <$> readSTRef ref

-- | Materializes all chunks in chronological order with their active lengths.
orderedChunks :: SlabState s a -> [(SmallMutableArray s a, Int)]
orderedChunks st =
  map (, slabChunkSize) (reverse (ssFullRev st))
    ++ [(ssCurrent st, ssChunkUsed st)]

-- | Extracts all elements appended since watermark @startMark@ without allocating
-- a separate nested Writer buffer.
listenSlice :: WriterSlab s a -> SlabMark -> ST s [a]
listenSlice (WriterSlab ref) (SlabMark startIdx) = do
  st <- readSTRef ref
  let total = ssTotal st
      clampedStart = max 0 (min startIdx total)
  readRange (orderedChunks st) 0 clampedStart total

readRange :: [(SmallMutableArray s a, Int)] -> Int -> Int -> Int -> ST s [a]
readRange [] _ _ _ = pure []
readRange ((arr, len) : rest) !base !lo !hi
  | base >= hi = pure []
  | base + len <= lo = readRange rest (base + len) lo hi
  | otherwise = do
      let localLo = max 0 (lo - base)
          localHi = min len (hi - base)
      xs <- go localLo localHi
      ys <- readRange rest (base + len) lo hi
      pure (xs ++ ys)
  where
    go !i !end
      | i >= end = pure []
      | otherwise = do
          v <- readSmallArray arr i
          vs <- go (i + 1) end
          pure (v : vs)

-- | Transforms elements appended since watermark @startMark@ in place (O(slice length)).
censorSlice :: WriterSlab s a -> SlabMark -> (a -> a) -> ST s ()
censorSlice (WriterSlab ref) (SlabMark startIdx) f = do
  st <- readSTRef ref
  let total = ssTotal st
      clampedStart = max 0 (min startIdx total)
  goChunks (orderedChunks st) 0 clampedStart total
  where
    goChunks [] _ _ _ = pure ()
    goChunks ((arr, len) : rest) !base !lo !hi
      | base >= hi = pure ()
      | base + len <= lo = goChunks rest (base + len) lo hi
      | otherwise = do
          let localLo = max 0 (lo - base)
              localHi = min len (hi - base)
          forM_ [localLo .. localHi - 1] $ \i -> do
            v <- readSmallArray arr i
            let !v' = f v
            writeSmallArray arr i v'
          goChunks rest (base + len) lo hi

-- | Freezes the full accumulated slab contents in chronological order.
freezeSlab :: WriterSlab s a -> ST s [a]
freezeSlab slab = listenSlice slab (SlabMark 0)