Skip to content

Commit 1f5758d

Browse files
committed
using Proxy.
1 parent 54b872f commit 1f5758d

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

Network/Socket/Posix/Cmsg.hsc

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ module Network.Socket.Posix.Cmsg where
1111
#include <sys/socket.h>
1212

1313
import Data.ByteString.Internal
14+
import Data.Proxy
1415
import Foreign.ForeignPtr
1516
import System.IO.Unsafe (unsafeDupablePerformIO)
1617
import System.Posix.Types (Fd(..))
@@ -87,24 +88,27 @@ filterCmsg cid cmsgs = filter (\cmsg -> cmsgId cmsg == cid) cmsgs
8788
-- Each control message type has a numeric 'CmsgId' and a 'Storable'
8889
-- data representation.
8990
class Storable a => ControlMessage a where
90-
controlMessageId :: a -> CmsgId
91+
controlMessageId :: Proxy a -> CmsgId
9192

92-
encodeCmsg :: ControlMessage a => a -> Cmsg
93+
encodeCmsg :: forall a . ControlMessage a => a -> Cmsg
9394
encodeCmsg x = unsafeDupablePerformIO $ do
9495
bs <- create siz $ \p0 -> do
9596
let p = castPtr p0
9697
poke p x
97-
return $ Cmsg (controlMessageId x) bs
98+
let cmsid = controlMessageId (Proxy :: Proxy a)
99+
return $ Cmsg cmsid bs
98100
where
99101
siz = sizeOf x
100102

101-
decodeCmsg :: forall a . Storable a => Cmsg -> Maybe a
102-
decodeCmsg (Cmsg _ (PS fptr off len))
103-
| len < siz = Nothing
104-
| otherwise = unsafeDupablePerformIO $ withForeignPtr fptr $ \p0 -> do
103+
decodeCmsg :: forall a . (ControlMessage a, Storable a) => Cmsg -> Maybe a
104+
decodeCmsg (Cmsg cmsid (PS fptr off len))
105+
| cid /= cmsid = Nothing
106+
| len < siz = Nothing
107+
| otherwise = unsafeDupablePerformIO $ withForeignPtr fptr $ \p0 -> do
105108
let p = castPtr (p0 `plusPtr` off)
106109
Just <$> peek p
107110
where
111+
cid = controlMessageId (Proxy :: Proxy a)
108112
siz = sizeOf (undefined :: a)
109113

110114
----------------------------------------------------------------

0 commit comments

Comments
 (0)