From abc756ffbbce1570462faa273da8c5c77d6696c3 Mon Sep 17 00:00:00 2001 From: Matthew Craven Date: Thu, 24 Nov 2022 19:02:57 -0500 Subject: [PATCH] Prevent Lazy.uncons from allocating a thunk (#559) ...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 #558. --- Data/ByteString/Lazy.hs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Data/ByteString/Lazy.hs b/Data/ByteString/Lazy.hs index 1d18dd787..9e5ad5108 100644 --- a/Data/ByteString/Lazy.hs +++ b/Data/ByteString/Lazy.hs @@ -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