Skip to content

Commit

Permalink
Prevent Lazy.uncons from allocating a thunk (haskell#559)
Browse files Browse the repository at this point in the history
...at least for the second component of its result.
The thunk for the first component is a bit hairier because
the readWord8OffAddr# is considered a side effect by GHC
and hence can currently never go away unless it is used lazily.

See also haskell#558.
  • Loading branch information
clyring authored and Bodigrim committed Nov 26, 2022
1 parent f309b52 commit abc756f
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions Data/ByteString/Lazy.hs
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,13 @@ head (Chunk c _) = S.unsafeHead c
-- if it is empty.
uncons :: ByteString -> Maybe (Word8, ByteString)
uncons Empty = Nothing
uncons (Chunk c cs)
= Just (S.unsafeHead c,
if S.length c == 1 then cs else Chunk (S.unsafeTail c) cs)
uncons (Chunk c cs) = case S.length c of
-- Don't move this test inside of the Just or (,).
-- We don't want to allocate a thunk to put inside of the tuple!
-- And if "let !tl = ... in Just (..., tl)" seems more appealing,
-- remember that this function must remain lazy in cs.
1 -> Just (S.unsafeHead c, cs)
_ -> Just (S.unsafeHead c, Chunk (S.unsafeTail c) cs)
{-# INLINE uncons #-}

-- | /O(1)/ Extract the elements after the head of a ByteString, which must be
Expand Down

0 comments on commit abc756f

Please sign in to comment.