2023-09-22 13:45:16 +01:00
|
|
|
{-# LANGUAGE LambdaCase #-}
|
|
|
|
|
2023-09-01 19:43:27 +01:00
|
|
|
module Simplex.Chat.Mobile.Shared where
|
|
|
|
|
|
|
|
import qualified Data.ByteString as B
|
2023-09-22 13:45:16 +01:00
|
|
|
import Data.ByteString.Internal (ByteString (..), memcpy)
|
|
|
|
import qualified Data.ByteString.Lazy as LB
|
|
|
|
import qualified Data.ByteString.Lazy.Internal as LB
|
|
|
|
import Foreign
|
2023-11-26 18:16:37 +00:00
|
|
|
import Foreign.C (CInt, CString)
|
2023-09-01 19:43:27 +01:00
|
|
|
|
|
|
|
type CJSONString = CString
|
|
|
|
|
2023-09-22 13:45:16 +01:00
|
|
|
type JSONByteString = LB.ByteString
|
|
|
|
|
2023-09-01 19:43:27 +01:00
|
|
|
getByteString :: Ptr Word8 -> CInt -> IO ByteString
|
|
|
|
getByteString ptr len = do
|
|
|
|
fp <- newForeignPtr_ ptr
|
2023-09-22 13:45:16 +01:00
|
|
|
pure $ BS fp $ fromIntegral len
|
|
|
|
{-# INLINE getByteString #-}
|
2023-09-01 19:43:27 +01:00
|
|
|
|
|
|
|
putByteString :: Ptr Word8 -> ByteString -> IO ()
|
2023-09-22 13:45:16 +01:00
|
|
|
putByteString ptr (BS fp len) =
|
|
|
|
withForeignPtr fp $ \p -> memcpy ptr p len
|
|
|
|
{-# INLINE putByteString #-}
|
|
|
|
|
|
|
|
putLazyByteString :: Ptr Word8 -> LB.ByteString -> IO ()
|
|
|
|
putLazyByteString ptr = \case
|
|
|
|
LB.Empty -> pure ()
|
|
|
|
LB.Chunk ch s -> do
|
|
|
|
putByteString ptr ch
|
|
|
|
putLazyByteString (ptr `plusPtr` B.length ch) s
|
|
|
|
|
|
|
|
newCStringFromBS :: ByteString -> IO CString
|
|
|
|
newCStringFromBS s = do
|
|
|
|
let len = B.length s
|
|
|
|
buf <- mallocBytes (len + 1)
|
|
|
|
putByteString buf s
|
|
|
|
pokeByteOff buf len (0 :: Word8)
|
|
|
|
pure $ castPtr buf
|
|
|
|
|
|
|
|
newCStringFromLazyBS :: LB.ByteString -> IO CString
|
|
|
|
newCStringFromLazyBS s = do
|
|
|
|
let len = fromIntegral $ LB.length s
|
|
|
|
buf <- mallocBytes (len + 1)
|
|
|
|
putLazyByteString buf s
|
|
|
|
pokeByteOff buf len (0 :: Word8)
|
|
|
|
pure $ castPtr buf
|