Skip to content

Commit

Permalink
Add withCString
Browse files Browse the repository at this point in the history
  • Loading branch information
dpwiz authored and Bodigrim committed May 17, 2022
1 parent 3649ea9 commit 3517e18
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Data/Text/Foreign.hs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ module Data.Text.Foreign
, useAsPtr
, asForeignPtr
-- ** Encoding as UTF-8
, withCString
, peekCStringLen
, withCStringLen
-- * Unsafe conversion code
Expand All @@ -40,10 +41,11 @@ import Data.Text.Internal.Unsafe (unsafeWithForeignPtr)
import Data.Text.Show (addrLen)
import Data.Text.Unsafe (lengthWord8)
import Data.Word (Word8)
import Foreign.C.String (CStringLen)
import Foreign.C.String (CString, CStringLen)
import Foreign.ForeignPtr (ForeignPtr, mallocForeignPtrArray)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (Ptr, castPtr)
import Foreign.Storable (pokeByteOff)
import GHC.Exts (Ptr(..))
import qualified Data.Text.Array as A

Expand Down Expand Up @@ -149,6 +151,21 @@ asForeignPtr t@(Text _arr _off len) = do
unsafeWithForeignPtr fp $ unsafeCopyToPtr t
return (fp, I8 len)

-- | Marshal a 'Text' into a C string with a trailing NUL byte,
-- encoded as UTF-8 in temporary storage.
--
-- The temporary storage is freed when the subcomputation terminates
-- (either normally or via an exception), so the pointer to the
-- temporary storage must /not/ be used after this function returns.
--
-- @since 2.0.1
withCString :: Text -> (CString -> IO a) -> IO a
withCString t@(Text _arr _off len) action =
allocaBytes (len + 1) $ \buf -> do
unsafeCopyToPtr t buf
pokeByteOff buf len (0 :: Word8)
action (castPtr buf)

-- | /O(n)/ Decode a C string with explicit length, which is assumed
-- to have been encoded as UTF-8. If decoding fails, a
-- 'UnicodeException' is thrown.
Expand Down

0 comments on commit 3517e18

Please sign in to comment.