From 1139357cb6c0daf0a3b4f1668b8df0aa7eb469a4 Mon Sep 17 00:00:00 2001 From: Tristan Cacqueray Date: Tue, 28 May 2024 15:49:19 -0400 Subject: [PATCH] Data.Text.Foreign: added peekCString Fixes: #239 --- src/Data/Text/Foreign.hs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Data/Text/Foreign.hs b/src/Data/Text/Foreign.hs index 82f010e7..ca2b2702 100644 --- a/src/Data/Text/Foreign.hs +++ b/src/Data/Text/Foreign.hs @@ -21,6 +21,7 @@ module Data.Text.Foreign , useAsPtr , asForeignPtr -- ** Encoding as UTF-8 + , peekCString , withCString , peekCStringLen , withCStringLen @@ -34,7 +35,7 @@ module Data.Text.Foreign ) where import Control.Monad.ST.Unsafe (unsafeSTToIO) -import Data.ByteString.Unsafe (unsafePackCStringLen, unsafeUseAsCStringLen) +import Data.ByteString.Unsafe (unsafePackCStringLen, unsafePackCString, unsafeUseAsCStringLen) import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Text.Internal (Text(..), empty) import Data.Text.Internal.Unsafe (unsafeWithForeignPtr) @@ -179,6 +180,16 @@ peekCStringLen cs = do bs <- unsafePackCStringLen cs return $! decodeUtf8 bs +-- | /O(n)/ Decode a null-terminated C string, which is assumed +-- to have been encoded as UTF-8. If decoding fails, a +-- 'UnicodeException' is thrown. +-- +-- @since 2.1.2 +peekCString :: CString -> IO Text +peekCString cs = do + bs <- unsafePackCString cs + return $! decodeUtf8 bs + -- | Marshal a 'Text' into a C string encoded as UTF-8 in temporary -- storage, with explicit length information. The encoded string may -- contain NUL bytes, and is not followed by a trailing NUL byte.