@@ -20,7 +20,9 @@ module Data.Text.Foreign
2020 , useAsPtr
2121 , asForeignPtr
2222 -- ** Encoding as UTF-8
23+ , peekCString
2324 , peekCStringLen
25+ , withCString
2426 , withCStringLen
2527 -- * Unsafe conversion code
2628 , lengthWord16
@@ -39,12 +41,12 @@ import Control.Monad.ST.Unsafe (unsafeIOToST)
3941#else
4042import Control.Monad.ST (unsafeIOToST )
4143#endif
42- import Data.ByteString.Unsafe (unsafePackCStringLen , unsafeUseAsCStringLen )
44+ import Data.ByteString.Unsafe (unsafePackCString , unsafePackCStringLen , unsafeUseAsCString , unsafeUseAsCStringLen )
4345import Data.Text.Encoding (decodeUtf8 , encodeUtf8 )
4446import Data.Text.Internal (Text (.. ), empty )
4547import Data.Text.Unsafe (lengthWord16 )
4648import Data.Word (Word16 )
47- import Foreign.C.String (CStringLen )
49+ import Foreign.C.String (CString , CStringLen )
4850import Foreign.ForeignPtr (ForeignPtr , mallocForeignPtrArray , withForeignPtr )
4951import Foreign.Marshal.Alloc (allocaBytes )
5052import Foreign.Ptr (Ptr , castPtr , plusPtr )
@@ -153,6 +155,16 @@ asForeignPtr t@(Text _arr _off len) = do
153155 withForeignPtr fp $ unsafeCopyToPtr t
154156 return (fp, I16 len)
155157
158+ -- | /O(n)/ Decode a NUL terminated C string, which is assumed to have
159+ -- been encoded as UTF-8. If decoding fails, a 'UnicodeException' is
160+ -- thrown.
161+ --
162+ -- @since 1.2.4.0
163+ peekCString :: CString -> IO Text
164+ peekCString cs = do
165+ bs <- unsafePackCString cs
166+ return $! decodeUtf8 bs
167+
156168-- | /O(n)/ Decode a C string with explicit length, which is assumed
157169-- to have been encoded as UTF-8. If decoding fails, a
158170-- 'UnicodeException' is thrown.
@@ -163,9 +175,22 @@ peekCStringLen cs = do
163175 bs <- unsafePackCStringLen cs
164176 return $! decodeUtf8 bs
165177
166- -- | Marshal a 'Text' into a C string encoded as UTF-8 in temporary
167- -- storage, with explicit length information. The encoded string may
168- -- contain NUL bytes, and is not followed by a trailing NUL byte.
178+ -- | /O(n)/ Marshal a 'Text' into a NUL terminated C string encoded as
179+ -- UTF-8 in temporary storage. The 'Text' must not contain any NUL
180+ -- characters.
181+ --
182+ -- The temporary storage is freed when the subcomputation terminates
183+ -- (either normally or via an exception), so the pointer to the
184+ -- temporary storage must /not/ be used after this function returns.
185+ --
186+ -- @since 1.2.4.0
187+ withCString :: Text -> (CString -> IO a ) -> IO a
188+ withCString t act = unsafeUseAsCString (encodeUtf8 t) act
189+
190+ -- | /O(n)/ Marshal a 'Text' into a C string encoded as UTF-8 in
191+ -- temporary storage, with explicit length information. The encoded
192+ -- string may contain NUL bytes, and is not followed by a trailing NUL
193+ -- byte.
169194--
170195-- The temporary storage is freed when the subcomputation terminates
171196-- (either normally or via an exception), so the pointer to the
0 commit comments