This repository has been archived by the owner on Dec 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
NSData.hs
50 lines (40 loc) · 1.77 KB
/
NSData.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
{-# LANGUAGE Trustworthy #-}
-- | Bridging to and from @NSData@
module ObjectiveHaskell.NSData (
fromNSData, toNSData
) where
import Control.Applicative
import Data.ByteString.Lazy as ByteString
import Data.Word
import Foreign.C.Types
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.StablePtr
import ObjectiveHaskell.MsgSend
import ObjectiveHaskell.ObjC
-- NSData methods
declMessage "dataWithBytes" [t| Ptr () -> NSUInteger -> Class -> IO Id |] "dataWithBytes:length:"
declMessage "objc_length" [t| Id -> IO NSUInteger |] "length"
declMessage "bytes" [t| Id -> IO (Ptr ()) |] "bytes"
-- | Converts an @NSData@ object into a lazy 'ByteString'.
-- | Note that this /does not/ reuse the internal storage of the @NSData@ object, and so may not be suitable for large blobs.
fromNSData :: Id -> IO ByteString
fromNSData dat = do
sz <- objc_length dat
ptr <- bytes dat
pack <$> peekArray (fromIntegral sz) (castPtr ptr)
-- | Converts a lazy 'ByteString' into an immutable @NSData@ object.
-- | Note that this /does not/ reuse the internal storage of the 'ByteString', and so may not be suitable for large blobs.
toNSData :: ByteString -> IO Id
toNSData str =
withArray (unpack str) $ \ptr ->
getClass "NSData" >>= dataWithBytes (castPtr ptr) (fromIntegral $ ByteString.length str)
instance Bridged ByteString where
toObjC = toNSData
fromObjC = fromNSData
fromNSDataObjC :: Id -> IO (StablePtr ByteString)
fromNSDataObjC obj = fromNSData obj >>= newStablePtr
toNSDataObjC :: StablePtr ByteString -> IO Id
toNSDataObjC ptr = deRefStablePtr ptr >>= toNSData
exportFunc "OHHaskellPtrFromNSData" [t| UnsafeId -> IO (StablePtr ByteString) |] 'fromNSDataObjC
exportFunc "OHNSDataFromHaskellPtr" [t| StablePtr ByteString -> IO UnsafeId |] 'toNSDataObjC