22567a845157fbb7a3124cdc87d50518dbb71931
[mate.git] / Mate / Strings.hs
1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE ForeignFunctionInterface #-}
3 module Mate.Strings (
4   getUniqueStringAddr
5   ) where
6
7 import Data.Word
8 import qualified Data.Map as M
9 import qualified Data.ByteString.Lazy as B
10 import Text.Printf
11
12 import Foreign.Ptr
13 import Foreign.Marshal.Alloc
14 import Foreign.Marshal.Utils
15 import Foreign.Marshal.Array
16
17 import Mate.Types
18
19
20 getUniqueStringAddr :: B.ByteString -> IO Word32
21 getUniqueStringAddr str = do
22   smap <- get_stringsmap >>= ptr2stringsmap
23   case M.lookup str smap of
24     Nothing -> do
25       addr <- allocateJavaString str
26       let smap' = M.insert str addr smap
27       stringsmap2ptr smap' >>= set_stringsmap
28       return addr
29     Just addr -> return addr
30
31 allocateJavaString :: B.ByteString -> IO Word32
32 allocateJavaString str = do
33   -- TODO(bernhard): is this also true for UTF8 stuff?
34   -- (+1) for \0
35   let strlen = (+1) $ fromIntegral $ B.length str
36   arr <- newArray $ ((map fromIntegral $ B.unpack str) :: [Word8])
37   newstr <- mallocBytes strlen
38   copyBytes newstr arr strlen
39   let w32_ptr = fromIntegral $ ptrToIntPtr newstr
40   printf "new str ptr: 0x%08x (%s)@%d\n" w32_ptr (toString str) strlen
41   return w32_ptr