Skip to content

Commit 64212ab

Browse files
committed
Extract alterCollision
1 parent 65af25c commit 64212ab

File tree

1 file changed

+29
-14
lines changed

1 file changed

+29
-14
lines changed

Data/HashMap/Internal.hs

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,25 +1328,40 @@ alter' f !h0 !k0 = go_alter' h0 k0 0
13281328
_ -> Full (A.update ary i st')
13291329
where i = index h s
13301330
go_alter' h k s t@(Collision hy ls)
1331-
| h == hy = case indexOf k ls of
1332-
Just i -> do
1333-
case A.index# ls i of
1334-
(# L _ v #) ->
1335-
case f $ Just v of
1336-
Nothing
1337-
| A.length ls == 2 ->
1338-
case A.index# ls (otherOfOneOrZero i) of
1339-
(# l #) -> Leaf h l
1340-
| otherwise -> Collision hy (A.delete ls i)
1341-
Just v' -> Collision hy $ A.update ls i $ L k v'
1342-
Nothing -> case f Nothing of
1343-
Nothing -> t
1344-
Just v' -> Collision hy $ A.snoc ls $ L k v'
1331+
| h == hy = alterCollision f h k ls t
13451332
| otherwise = case f Nothing of
13461333
Nothing -> t
13471334
Just v' -> runST $ two s h k v' hy t
13481335
{-# INLINE alter' #-}
13491336

1337+
alterCollision
1338+
:: Eq k
1339+
=> (Maybe v -> Maybe v)
1340+
-> Hash
1341+
-> k
1342+
-> A.Array (Leaf k v)
1343+
-> HashMap k v
1344+
-- ^ The original Collision node which will be re-used if the array is unchanged.
1345+
--
1346+
-- It is the caller's responsibility to ensure that this argument is in WHNF.
1347+
-> HashMap k v
1348+
alterCollision f !h !k !ary orig =
1349+
case indexOf k ary of
1350+
Just i -> do
1351+
case A.index# ary i of
1352+
(# L _ v #) ->
1353+
case f $ Just v of
1354+
Nothing
1355+
| A.length ary == 2 ->
1356+
case A.index# ary (otherOfOneOrZero i) of
1357+
(# l #) -> Leaf h l
1358+
| otherwise -> Collision h (A.delete ary i)
1359+
Just v' -> Collision h $ A.update ary i $ L k v'
1360+
Nothing -> case f Nothing of
1361+
Nothing -> orig
1362+
Just v' -> Collision h $ A.snoc ary $ L k v'
1363+
{-# INLINABLE alterCollision #-}
1364+
13501365
-- | \(O(\log n)\) The expression @('alterF' f k map)@ alters the value @x@ at
13511366
-- @k@, or absence thereof.
13521367
--

0 commit comments

Comments
 (0)