Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement 'unlines' directly #479

Merged
merged 2 commits into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions Data/ByteString/Char8.hs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ import Data.ByteString.ReadNat
import Data.Char ( isSpace )
-- See bytestring #70
import GHC.Char (eqChar)
import qualified Data.List as List (concatMap)
import qualified Data.List as List

import System.IO (Handle,stdout)
import Foreign
Expand Down Expand Up @@ -965,10 +965,21 @@ lines (BS x l) = go x l
else return [BS f i]
-}

-- | 'unlines' is an inverse operation to 'lines'. It joins lines,
-- after appending a terminating newline to each.
-- | 'unlines' joins lines, appending a terminating newline after each.
--
-- Equivalent to
-- @'concat' . Data.List.concatMap (\\x -> [x, 'singleton' \'\\n'])@.
unlines :: [ByteString] -> ByteString
unlines = concat . List.concatMap (\x -> [x, singleton '\n'])
unlines = \li -> let
totLen = List.foldl' (\acc s -> acc +! length s +! 1) 0 li
(+!) = checkedAdd "Char8.unlines"

go [] _ = pure ()
go (BS srcFP len : srcs) dest = do
unsafeWithForeignPtr srcFP $ \src -> memcpy dest src len
pokeElemOff dest len (c2w '\n')
go srcs $ dest `plusPtr` (len + 1)
in unsafeCreate totLen (go li)

-- | 'words' breaks a ByteString up into a list of words, which
-- were delimited by Chars representing white space.
Expand Down
8 changes: 5 additions & 3 deletions Data/ByteString/Lazy/Char8.hs
Original file line number Diff line number Diff line change
Expand Up @@ -908,10 +908,12 @@ lines (Chunk c0 cs0) = loop0 c0 cs0
let !c' = revChunks (B.unsafeTake n c : line)
in c' : loop0 (B.unsafeDrop (n+1) c) cs

-- | 'unlines' is an inverse operation to 'lines'. It joins lines,
-- after appending a terminating newline to each.
-- | 'unlines' joins lines, appending a terminating newline after each.
--
-- Equivalent to
-- @'concat' . Data.List.concatMap (\\x -> [x, 'singleton' \'\\n'])@.
unlines :: [ByteString] -> ByteString
unlines = concat . List.concatMap (\x -> [x, singleton '\n'])
unlines = List.foldr (\x t -> x `append` cons '\n' t) Empty

-- | 'words' breaks a ByteString up into a list of words, which
-- were delimited by Chars representing white space. And
Expand Down