Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A demonstration of using QuickCheck to test C code
-- This is a snippet cut-and-paste from a larger code body, might not compile or
-- work as expected as such
import Prelude hiding (pi)
import Data.Bits
import Data.Word (Word32)
import Foreign.C.Types (CSize)
import Foreign.Marshal.Array (withArrayLen)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr)
import Foreign.Storable (peek)
import Test.QuickCheck
foreign import ccall unsafe "hashword" fHashWord
:: Ptr Word32 -> CSize -> Word32 -> IO Word32
-- | A wrapper for native 'hashword'
hashWord :: [Word32] -- ^ Input values to hash
-> Word32 -- ^ Initial salt
-> IO Word32 -- ^ Hash result
hashWord as i = withArrayLen as $ \l p -> fHashWord p (fromIntegral l) i
foreign import ccall unsafe "hashword2" fHashWord2
:: Ptr Word32 -> CSize -> Ptr Word32 -> Ptr Word32 -> IO ()
-- | A wrapper for native 'hashword2'
hashWord2 :: [Word32] -- ^ Input values to hash
-> Word32 -- ^ First salt
-> Word32 -- ^ Second salt
-> IO (Word32, Word32) -- ^ Hashes
hashWord2 as i j = withArrayLen as $ \las pas ->
with i $ \pi -> do
j' <- with j $ \pj -> do
fHashWord2 pas (fromIntegral las) pi pj
peek pj
i' <- peek pi
return (i', j')
prop_hashword_fst_hashword2 :: [Word32] -> Word32 -> IO Bool
prop_hashword_fst_hashword2 a i = do
h <- hashWord a i
h' <- fst `fmap` hashWord2 a i 0
return $ h == h'
main = quickCheck (prop_hashword_fst_hashword2 :: [Word32] -> Word32 -> IO Bool)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.