Enhace constants pool handling.
[hs-java.git] / JVM / Common.hs
1 {-# LANGUAGE TypeFamilies, StandaloneDeriving, FlexibleInstances, FlexibleContexts, UndecidableInstances #-}
2 -- | This module declares some commonly used functions and instances.
3 module JVM.Common
4   (toCharList,
5   poolSize,
6   (!),
7   showListIx,
8   mapFindIndex,
9   byteString
10   ) where
11
12 import Data.Binary
13 import Data.Binary.Put
14 import qualified Data.ByteString.Lazy as B
15 import qualified Data.Map as M
16 import Data.Default
17 import Data.List
18
19 import JVM.ClassFile
20
21 instance Default B.ByteString where
22   def = B.empty
23
24 instance Default Word16 where
25   def = 0
26
27 toCharList :: B.ByteString -> [Int]
28 toCharList bstr = map fromIntegral $ B.unpack bstr
29
30 poolSize :: Pool stage -> Int
31 poolSize = M.size
32
33 (!) :: (Ord k) => M.Map k a -> k -> a
34 (!) = (M.!)
35
36 showListIx :: (Show i, Show a) => [(i,a)] -> String
37 showListIx list = unlines $ map s list
38   where s (i, x) = show i ++ ":\t" ++ show x
39
40 byteString ::  (Binary t) => t -> B.ByteString
41 byteString x = runPut (put x)
42
43 mapFindIndex :: (Num k) => (v -> Bool) -> M.Map k v -> Maybe k
44 mapFindIndex check m =
45   case find (check . snd) (M.assocs m) of
46     Nothing -> Nothing
47     Just (k,_) -> Just k
48