packages feed

pykinos-core-0.1.1.0: src/Pykinos/Interval/IntervalMap.hs

{-# LANGUAGE BangPatterns #-}
-- | Module: Pykinos.Interval.IntervalMap
-- Description: Maple-Tree-inspired non-overlapping [lo, hi) Word64 interval map with logarithmic index
-- License: EUPL-1.2 OR Apache-2.0
--
-- Provides cache-conscious non-overlapping [lo, hi) interval indexing over unboxed Word64
-- endpoints. Supports point stabbing ('lookupPoint'), overlap range scanning ('queryOverlap'),
-- free allocation gap discovery ('findFreeGap'), and automatic adjacent extent coalescing.
module Pykinos.Interval.IntervalMap
  ( Extent(..)
  , IntervalMap
  , emptyIntervalMap
  , intervalMapSize
  , insertExtent
  , lookupPoint
  , queryOverlap
  , findFreeGap
  , extentList
  ) where

import qualified Data.Map.Strict as Map
import Data.Word (Word64)

-- | Half-open contiguous interval [extLo, extHi) carrying payload value.
data Extent a = Extent
  { extLo  :: {-# UNPACK #-} !Word64
  , extHi  :: {-# UNPACK #-} !Word64
  , extVal :: !a
  } deriving stock (Eq, Show)

-- | Non-overlapping interval map indexed by low endpoint.
newtype IntervalMap a = IntervalMap (Map.Map Word64 (Extent a))
  deriving stock (Eq, Show)

-- | Empty interval map.
emptyIntervalMap :: IntervalMap a
emptyIntervalMap = IntervalMap Map.empty

-- | Number of active extents in the map.
intervalMapSize :: IntervalMap a -> Int
intervalMapSize (IntervalMap m) = Map.size m

-- | All extents in strictly ascending order.
extentList :: IntervalMap a -> [(Word64, Word64, a)]
extentList (IntervalMap m) = [(extLo e, extHi e, extVal e) | e <- Map.elems m]

-- | Inserts a half-open extent @[lo, hi)@ into the map.
-- Rejects overlapping intervals with 'Left'.
-- Automatically coalesces immediately adjacent intervals sharing identical payloads.
insertExtent :: (Eq a) => Word64 -> Word64 -> a -> IntervalMap a -> Either String (IntervalMap a)
insertExtent !lo !hi val (IntervalMap m)
  | lo >= hi  = Left "Invalid interval: lo >= hi"
  | otherwise =
      -- Check overlap with predecessor
      case Map.lookupLE lo m of
        Just (_, Extent pLo pHi _)
          | pHi > lo ->
              Left $ "Interval overlap: [" ++ show lo ++ ", " ++ show hi ++ ") overlaps with [" ++ show pLo ++ ", " ++ show pHi ++ ")"
        _ ->
          -- Check overlap with successor
          case Map.lookupGE lo m of
            Just (sLo, Extent _ sHi _)
              | sLo < hi ->
                  Left $ "Interval overlap: [" ++ show lo ++ ", " ++ show hi ++ ") overlaps with [" ++ show sLo ++ ", " ++ show sHi ++ ")"
            _ ->
              -- No overlap! Check coalescing with predecessor and successor
              let (!coalescedLo, !mAfterPred) = case Map.lookupLE lo m of
                    Just (pLo, Extent _ pHi pVal)
                      | pHi == lo && pVal == val -> (pLo, Map.delete pLo m)
                    _ -> (lo, m)
                  (!coalescedHi, !mAfterSucc) = case Map.lookupGE hi mAfterPred of
                    Just (sLo, Extent _ sHi sVal)
                      | sLo == hi && sVal == val -> (sHi, Map.delete sLo mAfterPred)
                    _ -> (hi, mAfterPred)
                  !newExt = Extent coalescedLo coalescedHi val
              in Right (IntervalMap (Map.insert coalescedLo newExt mAfterSucc))

-- | Point stabbing query: returns payload if point @p@ falls within any @[lo, hi)@ extent.
lookupPoint :: Word64 -> IntervalMap a -> Maybe a
lookupPoint !p (IntervalMap m) =
  case Map.lookupLE p m of
    Just (_, Extent _ eHi eVal)
      | p < eHi   -> Just eVal
      | otherwise -> Nothing
    Nothing -> Nothing

-- | Range overlap query: returns all extents overlapping query window @[lo, hi)@.
queryOverlap :: Word64 -> Word64 -> IntervalMap a -> [(Word64, Word64, a)]
queryOverlap !lo !hi (IntervalMap m)
  | lo >= hi  = []
  | otherwise =
      let -- Start scanning from the predecessor of lo (which might extend past lo)
          startLo = case Map.lookupLE lo m of
            Just (pLo, Extent _ pHi _) | pHi > lo -> pLo
            _                                     -> lo
          -- Submap of potential overlapping intervals
          candidates = Map.elems (fst (Map.split hi (snd (Map.split (startLo - 1) m))))
      in [ (extLo e, extHi e, extVal e)
         | e <- candidates
         , max lo (extLo e) < min hi (extHi e)
         ]

-- | Finds the lowest unallocated free address space gap of size @gapSize@
-- within range @[rangeMin, rangeMax)@.
findFreeGap :: Word64 -> Word64 -> Word64 -> IntervalMap a -> Maybe Word64
findFreeGap !rangeMin !rangeMax !gapSize (IntervalMap m)
  | rangeMin + gapSize > rangeMax = Nothing
  | otherwise = go rangeMin (Map.elems m)
  where
    go !curPos []
      | curPos + gapSize <= rangeMax = Just curPos
      | otherwise                    = Nothing
    go !curPos (Extent eLo eHi _ : es)
      | eHi <= curPos =
          go curPos es
      | eLo <= curPos =
          go (max curPos eHi) es
      | otherwise =
          let !availLo = max curPos rangeMin
              !availHi = min eLo rangeMax
          in if availLo + gapSize <= availHi
               then Just availLo
               else if eHi >= rangeMax
                 then Nothing
                 else go (max eHi rangeMin) es