module Data.Registry.Internal.Cache where
import Data.Map.Strict
import Data.Registry.Internal.Types (SpecializationPath)
import Data.Typeable (Typeable)
import Protolude as P
newtype Cache a = Cache (MVar (Map Key a))
deriving (Eq, Typeable)
type Key = Maybe [SpecializationPath]
fetch :: forall a m . (MonadIO m, Typeable a) => Cache a -> Key -> m a -> m a
fetch (Cache var) key action =
do m <- liftIO $ P.readMVar var
case lookup key m of
Just a ->
pure a
Nothing -> do
val <- action
liftIO $ modifyMVar_ var (\cached -> pure $ insert key val cached)
pure val
newCache :: IO (Cache a)
newCache = Cache <$> P.newMVar mempty