@@ -1,5 +1,3 @@
1−{-# LANGUAGE CPP #-}
2−
31module Network.Wai.Handler.Warp.MultiMap (
42 MMap
53 , isEmpty
@@ -15,11 +13,14 @@ module Network.Wai.Handler.Warp.MultiMap (
1513
1614import Data.IntMap.Strict (IntMap)
1715import qualified Data.IntMap.Strict as I
18−import qualified Network.Wai.Handler.Warp.Some as S
16+import qualified Data.List.NonEmpty as NE
17+import Data.Semigroup
18+
19+import Network.Wai.Handler.Warp.Imports hiding ((<>), union, empty, insert)
1920
2021----------------------------------------------------------------
2122
22−type MMap v = IntMap (S.Some v)
23+type MMap v = IntMap (NonEmpty v)
2324
2425----------------------------------------------------------------
2526
@@ -35,7 +36,7 @@ empty = I.empty
3536
3637-- | O(1)
3738singleton :: Int -> v -> MMap v
38−singleton k v = I.singleton k (S.singleton v)
39+singleton k v = I.singleton k (v :| [])
3940
4041----------------------------------------------------------------
4142
@@ -43,19 +44,19 @@ singleton k v = I.singleton k (S.singleton v)
4344search :: Int -> MMap v -> Maybe v
4445search k m = case I.lookup k m of
4546 Nothing -> Nothing
46− Just s -> Just $! S.top s
47+ Just s -> Just $! NE.head s
4748
4849-- | O(log n)
4950searchWith :: Int -> (v -> Bool) -> MMap v -> Maybe v
5051searchWith k f m = case I.lookup k m of
51− Nothing -> Nothing
52− Just s -> S.lookupWith f s
52+ Nothing -> Nothing
53+ Just nxs -> find f $ NE.toList nxs
5354
5455----------------------------------------------------------------
5556
5657-- | O(log n)
5758insert :: Int -> v -> MMap v -> MMap v
58−insert k v m = I.insertWith S.union k (S.singleton v) m
59+insert k v m = I.insertWith (<>) k (v :| []) m
5960
6061----------------------------------------------------------------
6162
@@ -63,7 +64,7 @@ insert k v m = I.insertWith S.union k (S.singleton v) m
6364toList :: MMap v -> [v]
6465toList m = concatMap f $ I.toAscList m
6566 where
66− f (_,s) = S.toList s
67+ f (_,s) = NE.toList s
6768
6869----------------------------------------------------------------
6970
@@ -75,7 +76,7 @@ pruneWith m action = I.fromAscList <$> go (I.toDescList m) []
7576 where
7677 go [] acc = return acc
7778 go ((k,s):kss) acc = do
78− mt <- S.prune action s
79+ mt <- prune action s
7980 case mt of
8081 Nothing -> go kss acc
8182 Just t -> go kss ((k,t) : acc)
@@ -84,4 +85,15 @@ pruneWith m action = I.fromAscList <$> go (I.toDescList m) []
8485
8586-- O(n + m) where N is the size of the second argument
8687merge :: MMap v -> MMap v -> MMap v
87−merge m1 m2 = I.unionWith S.union m1 m2
88+merge m1 m2 = I.unionWith (<>) m1 m2
89+
90+----------------------------------------------------------------
91+
92+prune :: (a -> IO Bool) -> NonEmpty a -> IO (Maybe (NonEmpty a))
93+prune act nxs = NE.nonEmpty <$> go (NE.toList nxs)
94+ where
95+ go [] = return []
96+ go (x:xs) = do
97+ keep <- act x
98+ rs <- go xs
99+ return $ if keep then x:rs else rs