{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}

module Cardano.Ledger.State.Transform where

import Data.Map.Strict.Internal

intern :: Ord k => k -> Map k a -> k
intern :: forall k a. Ord k => k -> Map k a -> k
intern !k
k Map k a
m =
  case forall k a. Ord k => k -> Map k a -> Maybe k
internMaybe k
k Map k a
m of
    Just k
kx -> k
kx
    Maybe k
Nothing -> k
k

internMaybe :: Ord k => k -> Map k a -> Maybe k
internMaybe :: forall k a. Ord k => k -> Map k a -> Maybe k
internMaybe !k
k = Map k a -> Maybe k
go
  where
    go :: Map k a -> Maybe k
go Map k a
Tip = forall a. Maybe a
Nothing
    go (Bin Size
_ k
kx a
_ Map k a
l Map k a
r) =
      case forall a. Ord a => a -> a -> Ordering
compare k
k k
kx of
        Ordering
LT -> Map k a -> Maybe k
go Map k a
l
        Ordering
GT -> Map k a -> Maybe k
go Map k a
r
        Ordering
EQ -> forall a. a -> Maybe a
Just k
kx

internVal :: (Eq a, Ord k) => k -> a -> Map k a -> a
internVal :: forall a k. (Eq a, Ord k) => k -> a -> Map k a -> a
internVal !k
k !a
a Map k a
m =
  case forall a k. (Eq a, Ord k) => k -> a -> Map k a -> Maybe a
internValMaybe k
k a
a Map k a
m of
    Just a
ax -> a
ax
    Maybe a
Nothing -> a
a

internsVal :: (Eq a, Ord k) => k -> a -> [Map k a] -> a
internsVal :: forall a k. (Eq a, Ord k) => k -> a -> [Map k a] -> a
internsVal !k
k !a
a = [Map k a] -> a
go
  where
    go :: [Map k a] -> a
go [] = a
a
    go (Map k a
m : [Map k a]
ms) =
      case forall a k. (Eq a, Ord k) => k -> a -> Map k a -> Maybe a
internValMaybe k
k a
a Map k a
m of
        Just a
ax -> a
ax
        Maybe a
Nothing -> [Map k a] -> a
go [Map k a]
ms

internValMaybe :: (Eq a, Ord k) => k -> a -> Map k a -> Maybe a
internValMaybe :: forall a k. (Eq a, Ord k) => k -> a -> Map k a -> Maybe a
internValMaybe !k
k !a
a = Map k a -> Maybe a
go
  where
    go :: Map k a -> Maybe a
go Map k a
Tip = forall a. Maybe a
Nothing
    go (Bin Size
_ k
kx a
ax Map k a
l Map k a
r) =
      case forall a. Ord a => a -> a -> Ordering
compare k
k k
kx of
        Ordering
LT -> Map k a -> Maybe a
go Map k a
l
        Ordering
GT -> Map k a -> Maybe a
go Map k a
r
        Ordering
EQ
          | a
a forall a. Eq a => a -> a -> Bool
== a
ax -> forall a. a -> Maybe a
Just a
ax
          | Bool
otherwise -> forall a. Maybe a
Nothing