From 3e0b863b642e6dd3476dd34dcab6560bd65e4c6d Mon Sep 17 00:00:00 2001 From: spaced4ndy <8711996+spaced4ndy@users.noreply.github.com> Date: Thu, 25 Jan 2024 18:57:38 +0400 Subject: [PATCH] core: add cChatJsonLength function (#3753) --- src/Simplex/Chat/Mobile.hs | 7 +++++++ tests/MobileTests.hs | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/src/Simplex/Chat/Mobile.hs b/src/Simplex/Chat/Mobile.hs index 7c74a7325..57e062cd0 100644 --- a/src/Simplex/Chat/Mobile.hs +++ b/src/Simplex/Chat/Mobile.hs @@ -20,6 +20,7 @@ import qualified Data.ByteArray as BA import qualified Data.ByteString.Base64.URL as U import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B +import qualified Data.ByteString.Lazy.Char8 as LB import Data.Functor (($>)) import Data.List (find) import qualified Data.List.NonEmpty as L @@ -94,6 +95,8 @@ foreign export ccall "chat_password_hash" cChatPasswordHash :: CString -> CStrin foreign export ccall "chat_valid_name" cChatValidName :: CString -> IO CString +foreign export ccall "chat_json_length" cChatJsonLength :: CString -> IO CInt + foreign export ccall "chat_encrypt_media" cChatEncryptMedia :: StablePtr ChatController -> CString -> Ptr Word8 -> CInt -> IO CString foreign export ccall "chat_decrypt_media" cChatDecryptMedia :: CString -> Ptr Word8 -> CInt -> IO CString @@ -176,6 +179,10 @@ cChatPasswordHash cPwd cSalt = do cChatValidName :: CString -> IO CString cChatValidName cName = newCString . mkValidName =<< peekCString cName +-- | returns length of JSON encoded string +cChatJsonLength :: CString -> IO CInt +cChatJsonLength s = fromIntegral . subtract 2 . LB.length . J.encode . safeDecodeUtf8 <$> B.packCString s + mobileChatOpts :: String -> ChatOpts mobileChatOpts dbFilePrefix = ChatOpts diff --git a/tests/MobileTests.hs b/tests/MobileTests.hs index 0ed1b30f5..2fb4446a6 100644 --- a/tests/MobileTests.hs +++ b/tests/MobileTests.hs @@ -68,6 +68,8 @@ mobileTests = do it "no exception on missing file" testMissingFileEncryptionCApi describe "validate name" $ do it "should convert invalid name to a valid name" testValidNameCApi + describe "JSON length" $ do + it "should compute length of JSON encoded string" testChatJsonLengthCApi noActiveUser :: LB.ByteString noActiveUser = @@ -356,6 +358,13 @@ testValidNameCApi _ = do cName2 <- cChatValidName =<< newCString " @'Джон' Доу 👍 " peekCString cName2 `shouldReturn` goodName +testChatJsonLengthCApi :: FilePath -> IO () +testChatJsonLengthCApi _ = do + cInt1 <- cChatJsonLength =<< newCString "Hello!" + cInt1 `shouldBe` 6 + cInt2 <- cChatJsonLength =<< newCString "こんにちは!" + cInt2 `shouldBe` 18 + jDecode :: FromJSON a => String -> IO (Maybe a) jDecode = pure . J.decode . LB.pack