packages feed

insert-ordered-containers-0.4: src/Data/HashMap/Strict/InsOrd.hs

{-# LANGUAGE DeriveFoldable        #-}
{-# LANGUAGE DeriveFunctor         #-}
{-# LANGUAGE DeriveTraversable     #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE GADTs                 #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables   #-}
{-# LANGUAGE Trustworthy           #-}
{-# LANGUAGE TypeFamilies          #-}
-- | 'InsOrdHashMap' is like 'HashMap', but it folds and traverses in insertion order.
--
-- This module interface mimics "Data.HashMap.Strict", with some additions.
module Data.HashMap.Strict.InsOrd (
    InsOrdHashMap,
    -- * Construction
    empty,
    singleton,
    -- * Basic interface
    null,
    size,
    member,
    lookup,
    lookupDefault,
    insert,
    insertWith,
    delete,
    adjust,
    update,
    alter,
    -- * Combine
    union,
    unionWith,
    unionWithKey,
    unions,
    -- * Transformations
    map,
    mapKeys,
    traverseKeys,
    mapWithKey,
    traverseWithKey,
    -- ** Unordered
    unorderedTraverse,
    unorderedTraverseWithKey,
    -- * Difference and intersection
    difference,
    intersection,
    intersectionWith,
    intersectionWithKey,
    -- * Folds
    foldl',
    foldlWithKey',
    foldr,
    foldrWithKey,
    foldMapWithKey,
    -- ** Unordered
    unorderedFoldMap,
    unorderedFoldMapWithKey,
    -- * Filter
    filter,
    filterWithKey,
    mapMaybe,
    mapMaybeWithKey,
    -- * Conversions
    keys,
    elems,
    toList,
    toRevList,
    fromList,
    toHashMap,
    fromHashMap,
    -- * Debugging
    valid,
    ) where

import Prelude
       (Bool (..), Eq, Functor, Int, Maybe (..), Ord (compare), all, const,
       flip, fmap, fst, id, max, maybe, min, otherwise, return, seq, snd, uncurry,
       zipWith, ($), (&&), (+), (.), (<$>), (<), (==), (>), (>=), (>>=), (||))

import Control.Applicative             (Applicative, Const (..))
import Control.Arrow                   (first, second)
import Control.DeepSeq                 (NFData (..))
import Data.Data
       (Constr, Data (..), DataType, Fixity (Prefix), gcast1, gcast2, mkConstr,
       mkDataType)
import Data.Foldable                   (Foldable (foldMap))
import Data.Foldable.WithIndex         (FoldableWithIndex (..))
import Data.Functor.Apply              (Apply (..))
import Data.Functor.Bind               (Bind (..))
import Data.Functor.WithIndex          (FunctorWithIndex (..))
import Data.Hashable                   (Hashable (..))
import Data.List                       (nub, sortBy)
import Data.Maybe                      (fromMaybe)
import Data.Monoid                     (Monoid, mempty)
import Data.Ord                        (comparing)
import Data.Semigroup                  (Semigroup (..))
import Data.Traversable                (Traversable (traverse))
import Data.Traversable.WithIndex      (TraversableWithIndex (..))
import Text.ParserCombinators.ReadPrec (prec)
import Text.Read
       (Lexeme (..), Read (..), lexP, parens, readListPrecDefault)
import Text.Show                       (Show (..), showParen, showString)

import Control.Monad.Trans.State.Strict (State, runState, state)

import qualified Data.Aeson          as A
import qualified Data.Aeson.Types    as A
import qualified Data.Foldable       as F

import           Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap

import qualified GHC.Exts as Exts

import qualified Control.DeepSeq as NF

import Data.HashMap.InsOrd.Internal

-------------------------------------------------------------------------------
-- Strict Pair Int a
-------------------------------------------------------------------------------

data P a = P !Int !a
    deriving (Functor, Foldable, Traversable)

instance NFData a => NFData (P a) where
    rnf (P _ a) = rnf a

-- | @since 0.2.5
instance NF.NFData1 P where
    liftRnf rnf1 (P _ a) = rnf1 a

getPK :: P a -> Int
getPK (P i _) = i
{-# INLINABLE getPK #-}

getPV :: P a -> a
getPV (P _ a) = a
{-# INLINABLE getPV #-}

-- | Combiner for 'HashMap.fromListWith' over entries in ascending index
-- order: keep the position of the old (earlier) entry and the value of the
-- new (later) one.
keepIndex :: P a -> P a -> P a
keepIndex (P _ v) (P i _) = P i v
{-# INLINE keepIndex #-}

incPK :: Int -> P a -> P a
incPK i (P j x) = P (i + j) x
{-# INLINABLE incPK #-}

instance Eq a => Eq (P a) where
    P _ a == P _ b = a == b

instance Show a => Show (P a) where
    showsPrec d (P _ x) = showsPrec d x

instance Hashable a => Hashable (P a) where
    hashWithSalt salt (P _ x) = hashWithSalt salt x

-------------------------------------------------------------------------------
-- InsOrdHashMap
-------------------------------------------------------------------------------

-- | A 'HashMap' that keeps its entries in insertion order.
--
-- A new key is added at the end. Updating the value of an existing key keeps
-- its position. Deleting a key and inserting it again moves it to the end.
data InsOrdHashMap k v = InsOrdHashMap
    { _getIndex        :: !Int
    , getInsOrdHashMap :: !(HashMap k (P v))
    }
    deriving (Functor)

-- | Presented as a single virtual constructor @fromList@ applied to the
-- entries in insertion order.
instance (Data k, Data v, Eq k, Hashable k) => Data (InsOrdHashMap k v) where
    gfoldl f z m   = z fromList `f` toList m
    toConstr _     = fromListConstr
    gunfold k z _  = k (z fromList)
    dataTypeOf _   = insOrdHashMapDataType
    dataCast1 f    = gcast1 f
    dataCast2 f    = gcast2 f

fromListConstr :: Constr
fromListConstr = mkConstr insOrdHashMapDataType "fromList" [] Prefix

insOrdHashMapDataType :: DataType
insOrdHashMapDataType =
    mkDataType "Data.HashMap.Strict.InsOrd.InsOrdHashMap" [fromListConstr]

-- | @since 0.2.5
instance (NFData k, NFData v) => NFData (InsOrdHashMap k v) where
    rnf (InsOrdHashMap _ hm) = rnf hm

-- | @since 0.2.5
instance NFData k => NF.NFData1 (InsOrdHashMap k) where
    liftRnf rnf2 = NF.liftRnf2 rnf rnf2

-- | @since 0.2.5
instance NF.NFData2 InsOrdHashMap  where
    liftRnf2 rnf1 rnf2 (InsOrdHashMap _ m) = NF.liftRnf2 rnf1 (NF.liftRnf rnf2) m

-- | Equality is order sensitive: maps with the same entries in a different
-- insertion order are not equal.
instance (Eq k, Eq v) => Eq (InsOrdHashMap k v) where
    a == b = toList a == toList b

-- | Compares the entries lexicographically, in insertion order.
--
-- @since FIXME
instance (Ord k, Ord v) => Ord (InsOrdHashMap k v) where
    compare a b = compare (toList a) (toList b)

instance (Show k, Show v) => Show (InsOrdHashMap k v) where
    showsPrec d m = showParen (d > 10) $
        showString "fromList " . showsPrec 11 (toList m)

instance (Eq k, Hashable k, Read k, Read v) => Read (InsOrdHashMap k v) where
    readPrec = parens $ prec 10 $ do
      Ident "fromList" <- lexP
      xs <- readPrec
      return (fromList xs)

    readListPrec = readListPrecDefault

instance (Eq k, Hashable k) => Semigroup (InsOrdHashMap k v) where
    (<>) = union

instance (Eq k, Hashable k) => Monoid (InsOrdHashMap k v) where
    mempty = empty

-- We cannot derive this, as we want to ordered folding and traversing
instance Foldable (InsOrdHashMap k) where
    -- in newer base only
    -- length = length . getInsOrdHashMap
    foldMap f = foldMap (f . snd) . toList

    null = null
    toList = elems
    length = size

instance Traversable (InsOrdHashMap k) where
    traverse f m = traverseWithKey (\_ -> f) m

instance (Eq k, Hashable k) => Apply (InsOrdHashMap k) where
    (<.>) = intersectionWith id
    (<. ) = intersectionWith const
    ( .>) = intersectionWith (const id)

instance (Eq k, Hashable k) => Bind (InsOrdHashMap k) where
    m >>- f = mapMaybeWithKey (\k -> lookup k . f) m

-- | @hashWithSalt salt . toHashMap = hashWithSalt salt@.
instance (Hashable k, Hashable v) => Hashable (InsOrdHashMap k v) where
    hashWithSalt salt (InsOrdHashMap _ m) =
        hashWithSalt salt m

instance (Eq k, Hashable k) => Exts.IsList (InsOrdHashMap k v) where
    type Item (InsOrdHashMap k v) = (k, v)
    fromList = fromList
    toList   = toList

-------------------------------------------------------------------------------
-- Aeson
-------------------------------------------------------------------------------

instance A.ToJSON2 InsOrdHashMap where
  liftToJSON2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList =
    A.liftToJSON omitNothing encodeKVPair encodeKVPairList . toList
    where
      omitNothing _ = False
      encodeKVPair = A.liftToJSON2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList
      encodeKVPairList = A.listValue encodeKVPair
  liftToEncoding2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList =
    A.liftToEncoding omitNothing encodeKVPair encodeKVPairList . toList
    where
      omitNothing _ = False
      encodeKVPair = A.liftToEncoding2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList
      encodeKVPairList = A.listEncoding encodeKVPair

instance (A.ToJSON k) => A.ToJSON1 (InsOrdHashMap k) where
    liftToJSON = A.liftToJSON2 A.omitField A.toJSON A.toJSONList
    liftToEncoding = A.liftToEncoding2 A.omitField A.toEncoding A.toEncodingList

instance (A.ToJSON k, A.ToJSON v) => A.ToJSON (InsOrdHashMap k v) where
    toJSON = A.toJSON1
    toEncoding = A.toEncoding1

-------------------------------------------------------------------------------

instance (Eq k, Hashable k, A.FromJSON k) => A.FromJSON1 (InsOrdHashMap k) where
    liftParseJSON o p pl v = fromList  <$> A.liftParseJSON Nothing pkv plkv v
      where
        pkv = A.liftParseJSON2 A.omittedField A.parseJSON A.parseJSONList o p pl
        plkv = A.listParser pkv

instance (Eq k, Hashable k, A.FromJSON k, A.FromJSON v) => A.FromJSON (InsOrdHashMap k v) where
    parseJSON = A.parseJSON1

-------------------------------------------------------------------------------
-- indexed-traversals
-------------------------------------------------------------------------------

instance (Eq k, Hashable k) => FunctorWithIndex k (InsOrdHashMap k) where
    imap = mapWithKey
instance (Eq k, Hashable k) => FoldableWithIndex k (InsOrdHashMap k) where
    ifoldMap = foldMapWithKey
    ifoldr   = foldrWithKey
instance (Eq k, Hashable k) => TraversableWithIndex k (InsOrdHashMap k) where
    itraverse = traverseWithKey

-------------------------------------------------------------------------------
-- Construction
-------------------------------------------------------------------------------

empty :: InsOrdHashMap k v
empty = InsOrdHashMap 0 HashMap.empty
{-# INLINABLE empty #-}

singleton :: Hashable k => k -> v -> InsOrdHashMap k v
singleton k v = InsOrdHashMap 1 (HashMap.singleton k (P 0 v))
{-# INLINABLE singleton #-}

-------------------------------------------------------------------------------
-- Basic interface
-------------------------------------------------------------------------------

null :: InsOrdHashMap k v -> Bool
null = HashMap.null . getInsOrdHashMap
{-# INLINABLE null #-}

size :: InsOrdHashMap k v -> Int
size = HashMap.size . getInsOrdHashMap
{-# INLINABLE size #-}

member :: (Eq k, Hashable k) => k -> InsOrdHashMap k a -> Bool
member k = HashMap.member k . getInsOrdHashMap
{-# INLINABLE member #-}

lookup :: (Eq k, Hashable k) => k -> InsOrdHashMap k v -> Maybe v
lookup k = fmap getPV . HashMap.lookup k . getInsOrdHashMap
{-# INLINABLE lookup #-}

lookupDefault
    :: (Eq k, Hashable k)
    => v  -- ^ Default value to return.
    -> k -> InsOrdHashMap k v -> v
lookupDefault def k m = fromMaybe def $ lookup k m
{-# INLINABLE lookupDefault #-}

delete :: (Eq k, Hashable k) => k -> InsOrdHashMap k v -> InsOrdHashMap k v
delete k (InsOrdHashMap i m) = InsOrdHashMap i $ HashMap.delete k m
{-# INLINABLE delete #-}

insert :: (Eq k, Hashable k) => k -> v -> InsOrdHashMap k v -> InsOrdHashMap k v
insert = insertWith const
{-# INLINABLE insert #-}

insertWith
    :: (Eq k, Hashable k)
    => (v -> v -> v) -> k -> v -> InsOrdHashMap k v -> InsOrdHashMap k v
insertWith f k v = alter (Just . maybe v (f v)) k
{-# INLINABLE insertWith #-}

adjust
    :: (Eq k, Hashable k)
    => (v -> v) -> k -> InsOrdHashMap k v -> InsOrdHashMap k v
adjust f = alter (fmap f)
{-# INLINABLE adjust #-}

update
    :: (Eq k, Hashable k)
    => (a -> Maybe a) -> k -> InsOrdHashMap k a -> InsOrdHashMap k a
update f = alter (>>= f)
{-# INLINABLE update #-}

alter
    :: (Eq k, Hashable k)
    => (Maybe v -> Maybe v) -> k -> InsOrdHashMap k v -> InsOrdHashMap k v
alter f k insm@(InsOrdHashMap j m) =
    case HashMap.lookup k m of
        Nothing       -> case f Nothing of
            Nothing   -> insm
            Just v    -> InsOrdHashMap (j + 1) (HashMap.insert k (P j v) m)
        Just (P i v)  -> case f (Just v) of
            Nothing   -> InsOrdHashMap j (HashMap.delete k m)
            Just u    -> InsOrdHashMap j (HashMap.insert k (P i u) m)
{-# INLINABLE alter #-}

-------------------------------------------------------------------------------
-- Combine
-------------------------------------------------------------------------------

-- | Like 'union', but if a key occurs in both maps, the given function
-- combines the two values.
unionWith
    :: (Eq k, Hashable k)
    => (v -> v -> v)
    -> InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v
unionWith f = unionWithKey (\_ -> f)

-- | Like 'unionWith', but the function also receives the key.
unionWithKey
    :: (Eq k, Hashable k)
    => (k -> v -> v -> v)
    -> InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v
unionWithKey f (InsOrdHashMap i a) (InsOrdHashMap j b) =
    mk $ HashMap.unionWithKey f' a b'
  where
    -- the threshold is arbitrary, it meant to amortise need for packing of indices
    mk | i > 0xfffff || j >= 0xfffff = fromHashMapP
       | otherwise                   = InsOrdHashMap (i + j)
    b' = HashMap.map (incPK i) b
    f' k (P ii x) (P _ y) = P ii (f k x y)

-- | The union of two maps: the entries of the first map in their order,
-- followed by the entries of the second map whose keys are not in the first,
-- in their order.
union
    :: (Eq k, Hashable k)
    => InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v
union = unionWith const

unions
    :: (Eq k, Hashable k, Foldable f)
    => f (InsOrdHashMap k v) -> InsOrdHashMap k v
unions = F.foldl' union empty

-------------------------------------------------------------------------------
-- Transformations
-------------------------------------------------------------------------------

-- | Order preserving mapping of keys.
--
-- If @f@ maps several keys to the same key, the result takes the position of
-- the earliest of them and the value of the latest, so
-- @mapKeys f = 'fromList' . fmap (first f) . 'toList'@.
mapKeys :: (Eq k', Hashable k') => (k -> k') -> InsOrdHashMap k v -> InsOrdHashMap k' v
mapKeys f (InsOrdHashMap i m) = InsOrdHashMap i $
    mergeKeys . fmap (first f) . HashMap.toList $ m
{-# INLINABLE mapKeys #-}

-- | Order preserving traversal of keys.
--
-- The effects are performed in insertion order. Keys that @f@ maps to the
-- same key are merged as in 'mapKeys'.
traverseKeys
    :: (Eq k', Hashable k', Applicative f)
    => (k -> f k') -> InsOrdHashMap k v -> f (InsOrdHashMap k' v)
traverseKeys f (InsOrdHashMap i m) =
    -- The entries are traversed in ascending index order, so the cheaper
    -- 'keepIndex' suffices here instead of 'mergeKeys'.
    InsOrdHashMap i . HashMap.fromListWith keepIndex <$>
        traverse (\(k, p) -> (\k' -> (k', p)) <$> f k)
            (sortBy (comparing (getPK . snd)) (HashMap.toList m))
{-# INLINABLE traverseKeys #-}

-- | Build a map from entries, in any order, whose keys may have been merged.
-- A merged key takes the earliest position and the value of the latest entry.
--
-- While merging, each key carries its earliest position and its latest entry.
-- Keeping only a single 'P' would lose track of which position the value came
-- from, and the result would then depend on the order of the list. For a list
-- already in ascending index order, use 'keepIndex' instead.
mergeKeys :: (Eq k, Hashable k) => [(k, P v)] -> HashMap k (P v)
mergeKeys = HashMap.map finish . HashMap.fromListWith merge . fmap start
  where
    start (k, p) = (k, P (getPK p) p)

    merge (P a p) (P b q) = P (min a b) (if getPK p > getPK q then p else q)

    finish (P a (P _ v)) = P a v
{-# INLINABLE mergeKeys #-}

map :: (v1 -> v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2
map f (InsOrdHashMap i m) = InsOrdHashMap i $ HashMap.map (fmap f) m

mapWithKey :: (k -> v1 -> v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2
mapWithKey f (InsOrdHashMap i m) =
    InsOrdHashMap i $ HashMap.mapWithKey f' m
  where
    f' k (P j x) = P j (f k x)

foldMapWithKey :: Monoid m => (k -> a -> m) -> InsOrdHashMap k a -> m
foldMapWithKey f = foldMap (uncurry f) . toList

traverseWithKey :: Applicative f => (k -> a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)
traverseWithKey f (InsOrdHashMap n m) = InsOrdHashMap n <$>
    traverseWithKeyOrderedBy getPK (\k (P i v) -> P i <$> f k v) m

-------------------------------------------------------------------------------
-- Unordered
-------------------------------------------------------------------------------

-- | More efficient than 'foldMap', when folding in insertion order is not important.
unorderedFoldMap :: Monoid m => (a -> m) -> InsOrdHashMap k a -> m
unorderedFoldMap f (InsOrdHashMap _ m) = foldMap (f . getPV) m

-- | More efficient than 'foldMapWithKey', when folding in insertion order is not important.
unorderedFoldMapWithKey :: Monoid m => (k -> a -> m) -> InsOrdHashMap k a -> m
unorderedFoldMapWithKey f m =
    getConst (unorderedTraverseWithKey (\k a -> Const (f k a)) m)

-- | More efficient than 'traverse', when traversing in insertion order is not important.
unorderedTraverse :: Applicative f => (a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)
unorderedTraverse f = unorderedTraverseWithKey (\_ -> f)

-- | More efficient than `traverseWithKey`, when traversing in insertion order is not important.
unorderedTraverseWithKey :: Applicative f => (k -> a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)
unorderedTraverseWithKey f (InsOrdHashMap i m) =
    InsOrdHashMap i <$> HashMap.traverseWithKey f' m
  where
    f' k (P j x) = P j <$> f k x

-------------------------------------------------------------------------------
-- Difference and intersection
-------------------------------------------------------------------------------

difference
    :: (Eq k, Hashable k)
    => InsOrdHashMap k v -> InsOrdHashMap k w -> InsOrdHashMap k v
difference (InsOrdHashMap i a) (InsOrdHashMap _ b) =
    InsOrdHashMap i $ HashMap.difference a b

-- | The intersection of two maps: the entries of the first map whose keys
-- are also in the second map, in the order of the first map.
intersection
    :: (Eq k, Hashable k)
    => InsOrdHashMap k v -> InsOrdHashMap k w -> InsOrdHashMap k v
intersection = intersectionWith const

-- | Like 'intersection', but combines the values of both maps with the given
-- function.
intersectionWith
    :: (Eq k, Hashable k)
    => (v1 -> v2 -> v3)
    -> InsOrdHashMap k v1 -> InsOrdHashMap k v2 -> InsOrdHashMap k v3
intersectionWith f = intersectionWithKey (\_ -> f)

-- | Like 'intersectionWith', but the function also receives the key.
intersectionWithKey
    :: (Eq k, Hashable k)
    => (k -> v1 -> v2 -> v3)
    -> InsOrdHashMap k v1 -> InsOrdHashMap k v2 -> InsOrdHashMap k v3
intersectionWithKey f (InsOrdHashMap i a) (InsOrdHashMap _ b) =
    InsOrdHashMap i $ HashMap.intersectionWithKey f' a b
  where
    f' k (P j x) (P _ y) = P j (f k x y)

-------------------------------------------------------------------------------
-- Folds
-------------------------------------------------------------------------------

foldl' :: (a -> v -> a) -> a -> InsOrdHashMap k v -> a
foldl' f x = F.foldl' f' x . toList
  where
    f' a (_, v) = f a v

foldlWithKey' :: (a -> k -> v -> a) -> a -> InsOrdHashMap k v -> a
foldlWithKey' f x = F.foldl' f' x . toList
  where
    f' a (k, v) = f a k v

foldr :: (v -> a -> a) -> a -> InsOrdHashMap k v -> a
foldr f x = F.foldr f' x . toList
  where
    f' (_, v) a = f v a

foldrWithKey :: (k -> v -> a -> a) -> a -> InsOrdHashMap k v -> a
foldrWithKey f x = F.foldr f' x . toList
  where
    f' (k, v) a = f k v a

-------------------------------------------------------------------------------
-- Filter
-------------------------------------------------------------------------------

filter :: (v -> Bool) -> InsOrdHashMap k v -> InsOrdHashMap k v
filter f (InsOrdHashMap i m) =
    InsOrdHashMap i $ HashMap.filter (f . getPV) m

filterWithKey :: (k -> v -> Bool) -> InsOrdHashMap k v -> InsOrdHashMap k v
filterWithKey f (InsOrdHashMap i m) =
    InsOrdHashMap i $ HashMap.filterWithKey f' m
  where
    f' k (P _ x) = f k x

mapMaybe :: (v1 -> Maybe v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2
mapMaybe f (InsOrdHashMap i m) = InsOrdHashMap i $ HashMap.mapMaybe f' m
  where
    f' (P j x) = P j <$> f x

mapMaybeWithKey :: (k -> v1 -> Maybe v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2
mapMaybeWithKey f (InsOrdHashMap i m) =
    InsOrdHashMap i $ HashMap.mapMaybeWithKey f' m
  where
    f' k (P j x) = P j <$> f k x

-------------------------------------------------------------------------------
-- Conversions
-------------------------------------------------------------------------------

keys :: InsOrdHashMap k v -> [k]
keys = fmap fst . toList
{-# INLINABLE keys #-}

elems :: InsOrdHashMap k v -> [v]
elems = fmap snd . toList
{-# INLINABLE elems #-}

-- | Construct a map from a list of key-value pairs.
--
-- If a key occurs more than once, it keeps the position of its first
-- occurrence and the value of its last.
--
-- >>> fromList [(1, 'a'), (2, 'b'), (1, 'c')]
-- fromList [(1,'c'),(2,'b')]
fromList :: (Eq k, Hashable k) => [(k, v)] -> InsOrdHashMap k v
fromList xs = InsOrdHashMap counter m
  where
    m = HashMap.fromListWith keepIndex (zipWith indexed [0 ..] xs)

    -- Forcing the P here avoids handing a thunk to fromListWith.
    indexed i (k, v) = let p = P i v in p `seq` (k, p)

    counter = HashMap.foldl' (\i (P j _) -> max i (j + 1)) 0 m
{-# INLINABLE fromList #-}

toList :: InsOrdHashMap k v -> [(k, v)]
toList
    = fmap (second getPV)
    . sortBy (comparing (getPK . snd))
    . HashMap.toList
    . getInsOrdHashMap

toRevList :: InsOrdHashMap k v -> [(k, v)]
toRevList
    = fmap (second getPV)
    . sortBy (flip $ comparing (getPK . snd))
    . HashMap.toList
    . getInsOrdHashMap

-- | Convert a 'HashMap'. The insertion order of the result is the order of
-- 'HashMap.toList', which is unspecified.
--
-- The values are evaluated to WHNF.
fromHashMap :: HashMap k v -> InsOrdHashMap k v
fromHashMap m = case numberWith P m of
    (n, m') -> InsOrdHashMap n m'

toHashMap :: InsOrdHashMap k v -> HashMap k v
toHashMap (InsOrdHashMap _ m) = HashMap.map getPV m

-------------------------------------------------------------------------------
-- Internal
-------------------------------------------------------------------------------

fromHashMapP :: HashMap k (P v) -> InsOrdHashMap k v
fromHashMapP = mk . flip runState 0 . traverseWithKeyOrderedBy getPK (\_ (P _ v) -> newP v)
  where
    mk (m, i) = InsOrdHashMap i m

-- | Test if the internal map structure is valid.
valid :: InsOrdHashMap k v -> Bool
valid (InsOrdHashMap i m) = indexesDistinct && indexesSmaller
  where
    indexes :: [Int]
    indexes = getPK <$> HashMap.elems m

    indexesDistinct = indexes == nub indexes
    indexesSmaller  = all (< i) indexes

newP :: a -> State Int (P a)
newP x = state $ \s -> (P s x, s + 1)