commit 2f0ba64eeee1b7475734862b56c0249b75d89d93
parent d44961600f8cdf70c6688379a19e20ef1ca8df6f
Author: Jared Tobin <jared@jtobin.io>
Date: Wed, 4 Nov 2026 20:47:56 +0400
lib: share scratch arrays across a tree update
update now runs over one pair of state and block arrays, threading
them through its path via node#, which hashes with hash_branch#. Each
level allocates only its new node, which is built strictly to avoid a
per-level thunk: insert allocates ~17KB, down from ~50KB, and delete
under 1KB.
Diffstat:
1 file changed, 27 insertions(+), 15 deletions(-)
diff --git a/lib/Data/MSSMT/Internal.hs b/lib/Data/MSSMT/Internal.hs
@@ -425,15 +425,23 @@ leaf v s
| BS.null v && s == 0 = Empty
| otherwise = Leaf (Commitment (hash_leaf v s) s) v
--- branch at the given depth; two empty children make an empty subtree,
--- as hashing them would. callers rule out sum overflow
-node :: Scheme -> Int -> Tree -> Tree -> Tree
-node _ _ Empty Empty = Empty
-node sc d l r =
+-- branch at the given depth, hashed over the given state and block
+-- arrays; two empty children make an empty subtree, as hashing them
+-- would. callers rule out sum overflow
+node#
+ :: Scheme -> Buffer -> Buffer -> Int -> Tree -> Tree
+ -> State# Exts.RealWorld -> (# State# Exts.RealWorld, Tree #)
+node# _ _ _ _ Empty Empty s0 = (# s0, Empty #)
+node# sc st bk d l r s0 =
let !(Commitment hl sl) = commit sc (d + 1) l
!(Commitment hr sr) = commit sc (d + 1) r
- in Node l (Commitment (hash_branch sc hl sl hr sr) (sl + sr)) r
-{-# INLINE node #-}
+ in case hash_branch# sc st bk hl sl hr sr s0 of
+ (# s1, h #) ->
+ -- built strictly; a lazy tuple component would allocate a
+ -- thunk for the node per level
+ let !n = Node l (Commitment h (sl + sr)) r
+ in (# s1, n #)
+{-# INLINE node# #-}
-- children of a subtree above leaf depth
children :: Tree -> (# Tree, Tree #)
@@ -442,15 +450,19 @@ children Empty = (# Empty, Empty #)
children (Leaf _ _) = (# Empty, Empty #) -- unreachable above leaf depth
{-# INLINE children #-}
--- replace the subtree at the given key's leaf
+-- replace the subtree at the given key's leaf, rehashing the path to it
+-- over one pair of state and block arrays
update :: Scheme -> Key -> Tree -> Tree -> Tree
-update sc k new = go 0 where
- go !d t
- | d == _HEIGHT = new
- | otherwise = case children t of
- (# l, r #)
- | bit k d -> node sc d l (go (d + 1) r)
- | otherwise -> node sc d (go (d + 1) l) r
+update sc k new t0 = with_scratch $ \st bk ->
+ let go !d t s0
+ | d == _HEIGHT = (# s0, new #)
+ | otherwise = case children t of
+ (# l, r #)
+ | bit k d -> case go (d + 1) r s0 of
+ (# s1, r' #) -> node# sc st bk d l r' s1
+ | otherwise -> case go (d + 1) l s0 of
+ (# s1, l' #) -> node# sc st bk d l' r s1
+ in go 0 t0
-- tree -----------------------------------------------------------------------