Skip to content

Commit eb1163d

Browse files
Refactor copyToBuf function
1 parent bbc06cd commit eb1163d

1 file changed

Lines changed: 21 additions & 22 deletions

File tree

core/src/Streamly/Internal/FileSystem/Posix/ReadDir.hsc

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -643,30 +643,29 @@ readEitherByteChunks confMod alldirs =
643643

644644
copyToBuf dstArr pos dirPath name = do
645645
nameLen <- fmap fromIntegral (liftIO $ c_strlen name)
646-
let PosixPath (Array dirArr start end) = dirPath
647-
dirLen = end - start
646+
-- We know it is already pinned.
647+
MutByteArray.unsafeAsPtr dstArr (\ptr -> liftIO $ do
648648
-- XXX We may need to decode and encode the path if the
649649
-- output encoding differs from fs encoding.
650-
--
651-
-- Account for separator and newline bytes.
652-
byteCount = dirLen + nameLen + 2
653-
if pos + byteCount <= bufSize
654-
then do
655-
-- XXX append a path separator to a dir path
656-
-- We know it is already pinned.
657-
MutByteArray.unsafeAsPtr dstArr (\ptr -> liftIO $ do
658-
MutByteArray.unsafePutSlice dirArr start dstArr pos dirLen
659-
let ptr1 = ptr `plusPtr` (pos + dirLen)
660-
separator = 47 :: Word8
661-
poke ptr1 separator
662-
let ptr2 = ptr1 `plusPtr` 1
663-
_ <- c_memcpy ptr2 (castPtr name) (fromIntegral nameLen)
664-
let ptr3 = ptr2 `plusPtr` nameLen
665-
newline = 10 :: Word8
666-
poke ptr3 newline
667-
)
668-
return (Just (pos + byteCount))
669-
else return Nothing
650+
let PosixPath (Array dirArr start end) = dirPath
651+
dirLen = end - start
652+
endDir = pos + dirLen
653+
endPos = endDir + nameLen + 2 -- sep + newline
654+
sepOff = ptr `plusPtr` endDir -- separator offset
655+
nameOff = sepOff `plusPtr` 1 -- file name offset
656+
nlOff = nameOff `plusPtr` nameLen -- newline offset
657+
separator = 47 :: Word8
658+
newline = 10 :: Word8
659+
if (endPos < bufSize)
660+
then do
661+
-- XXX We can keep a trailing separator on the dir itself.
662+
MutByteArray.unsafePutSlice dirArr start dstArr pos dirLen
663+
poke sepOff separator
664+
_ <- c_memcpy nameOff (castPtr name) (fromIntegral nameLen)
665+
poke nlOff newline
666+
return (Just endPos)
667+
else return Nothing
668+
)
670669

671670
step _ ChunkStreamByteInit = do
672671
mbarr <- liftIO $ MutByteArray.new' bufSize

0 commit comments

Comments
 (0)