Persistent instance Maybe

I am trying to find an instance of Foreign.Storable for Maybe . Google has included an instance of C2HS

 instance Storable a => Storable (Maybe a) where sizeOf _ = sizeOf (undefined :: Ptr ()) alignment _ = alignment (undefined :: Ptr ()) peek p = do ptr <- peek (castPtr p) if ptr == nullPtr then return Nothing else liftM Just $ peek ptr poke pv = do ptr <- case v of Nothing -> return nullPtr Just v' -> new v' poke (castPtr p) ptr 

but also a message about how he loses his memory. Is there an existing instance somewhere else or a way to improve the C2HS instance? Why is Foreign.Storable no instance in Foreign.Storable ?

+6
source share
1 answer

Here's a potential instance available at School of Haskell . The idea is to store an extra byte containing either 0 or 1, indicating whether this value exists.

There are, of course, more effective approaches to an individual instance of Storable . For example, Maybe Bool can be stored in one byte instead of two bytes. But I don't think you can avoid a 1-byte overhead in the general case.

Here is the main part of my solution:

 instance Storable a => Storable (Maybe a) where sizeOf x = sizeOf (stripMaybe x) + 1 alignment x = alignment (stripMaybe x) peek ptr = do filled <- peekByteOff ptr $ sizeOf $ stripMaybe $ stripPtr ptr if filled == (1 :: Word8) then do x <- peek $ stripMaybePtr ptr return $ Just x else return Nothing poke ptr Nothing = pokeByteOff ptr (sizeOf $ stripMaybe $ stripPtr ptr) (0 :: Word8) poke ptr (Just a) = do poke (stripMaybePtr ptr) a pokeByteOff ptr (sizeOf a) (1 :: Word8) 
+3
source

Source: https://habr.com/ru/post/973628/


All Articles