{-# LANGUAGE FlexibleContexts #-}
-- | Cache blocks in memory
--
-- Intended for qualified import.
--
-- > import           Ouroboros.Consensus.Storage.ChainDB.Impl.BlockCache (BlockCache)
-- > import qualified Ouroboros.Consensus.Storage.ChainDB.Impl.BlockCache as BlockCache
module Ouroboros.Consensus.Storage.ChainDB.Impl.BlockCache (
    cacheBlock
  , empty
  , lookup
  , singleton
    -- * opaque
  , BlockCache
  ) where

import           Prelude hiding (lookup)

import           Data.Map (Map)
import qualified Data.Map as Map

import           Ouroboros.Consensus.Block

newtype BlockCache blk = BlockCache (Map (HeaderHash blk) blk)

empty :: BlockCache blk
empty :: BlockCache blk
empty = Map (HeaderHash blk) blk -> BlockCache blk
forall blk. Map (HeaderHash blk) blk -> BlockCache blk
BlockCache Map (HeaderHash blk) blk
forall k a. Map k a
Map.empty

singleton :: HasHeader blk => blk -> BlockCache blk
singleton :: blk -> BlockCache blk
singleton blk
blk = blk -> BlockCache blk -> BlockCache blk
forall blk.
HasHeader blk =>
blk -> BlockCache blk -> BlockCache blk
cacheBlock blk
blk BlockCache blk
forall blk. BlockCache blk
empty

cacheBlock :: HasHeader blk => blk -> BlockCache blk -> BlockCache blk
cacheBlock :: blk -> BlockCache blk -> BlockCache blk
cacheBlock blk
blk (BlockCache Map (HeaderHash blk) blk
cache) = Map (HeaderHash blk) blk -> BlockCache blk
forall blk. Map (HeaderHash blk) blk -> BlockCache blk
BlockCache (HeaderHash blk
-> blk -> Map (HeaderHash blk) blk -> Map (HeaderHash blk) blk
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (blk -> HeaderHash blk
forall b. HasHeader b => b -> HeaderHash b
blockHash blk
blk) blk
blk Map (HeaderHash blk) blk
cache)

lookup :: HasHeader blk => HeaderHash blk -> BlockCache blk -> Maybe blk
lookup :: HeaderHash blk -> BlockCache blk -> Maybe blk
lookup HeaderHash blk
hash (BlockCache Map (HeaderHash blk) blk
cache) = HeaderHash blk -> Map (HeaderHash blk) blk -> Maybe blk
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup HeaderHash blk
hash Map (HeaderHash blk) blk
cache