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

Simplify useAsCString #516

Merged
merged 1 commit into from
May 18, 2022
Merged
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
12 changes: 5 additions & 7 deletions Data/ByteString.hs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ import Control.Monad (when, void)

import Foreign.C.String (CString, CStringLen)
import Foreign.C.Types (CSize (CSize), CInt (CInt))
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr, touchForeignPtr)
import Foreign.ForeignPtr (ForeignPtr, touchForeignPtr)
import Foreign.ForeignPtr.Unsafe(unsafeForeignPtrToPtr)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Array (allocaArray)
Expand Down Expand Up @@ -1734,12 +1734,10 @@ sort (BS input l)
-- subcomputation finishes.
useAsCString :: ByteString -> (CString -> IO a) -> IO a
useAsCString (BS fp l) action =
allocaBytes (l+1) $ \buf ->
-- Cannot use unsafeWithForeignPtr, because action can diverge
withForeignPtr fp $ \p -> do
memcpy buf p l
pokeByteOff buf l (0::Word8)
action (castPtr buf)
allocaBytes (l+1) $ \buf -> do
unsafeWithForeignPtr fp $ \p -> memcpy buf p l
pokeByteOff buf l (0::Word8)
action (castPtr buf)
sjakobi marked this conversation as resolved.
Show resolved Hide resolved

-- | /O(n) construction/ Use a @ByteString@ with a function requiring a @CStringLen@.
-- As for @useAsCString@ this function makes a copy of the original @ByteString@.
Expand Down