module Language.Lean.Internal.String
( mkLeanString
, mkLeanText
, getLeanString
, decodeLeanString
, withLeanStringPtr
, withLeanTextPtr
) where
import Control.Exception (bracket, finally, throwIO)
import qualified Data.ByteString as BS
import Data.ByteString.Unsafe (unsafePackCString, unsafeUseAsCString)
import Data.String
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding (decodeUtf8', encodeUtf8)
import Foreign.Ptr
import Foreign.C (CChar, CString)
lean_string_del :: (CString) -> IO ()
lean_string_del a1 =
(flip ($)) a1 $ \a1' ->
lean_string_del'_ a1' >>
return ()
decodeLeanText :: CString -> IO Text
decodeLeanText cstr = do
bs <- unsafePackCString cstr
case decodeUtf8' bs of
Left e -> throwIO e
Right v -> return v
decodeLeanString :: CString -> IO String
decodeLeanString cstr = Text.unpack <$> decodeLeanText cstr
mkLeanText :: IO CString -> IO Text
mkLeanText alloc = bracket alloc lean_string_del $ decodeLeanText
mkLeanString :: IO CString -> IO String
mkLeanString alloc = bracket alloc lean_string_del $ decodeLeanString
getLeanString :: CString -> IO String
getLeanString ptr = decodeLeanString ptr `finally` lean_string_del ptr
withLeanStringPtr :: String -> (CString -> IO a) -> IO a
withLeanStringPtr s f = withLeanTextPtr (fromString s) f
withLeanTextPtr :: Text -> (CString -> IO a) -> IO a
withLeanTextPtr txt f =
unsafeUseAsCString (encodeUtf8 txt `BS.snoc` 0) f
foreign import ccall unsafe "Language/Lean/Internal/String.chs.h lean_string_del"
lean_string_del'_ :: ((Ptr CChar) -> (IO ()))