Skip to content

Instantly share code, notes, and snippets.

@axman6
Last active December 30, 2019 02:51
Show Gist options
  • Save axman6/3a1528111aad4cb79ea44b51836dec85 to your computer and use it in GitHub Desktop.
Save axman6/3a1528111aad4cb79ea44b51836dec85 to your computer and use it in GitHub Desktop.
An example of how Foreign.Marshal.ContT can make FFI code nicer
compile :: ByteString -> [PCREOption] -> Either String Regex
compile str flags = unsafePerformIO $
useAsCString str $ \pattern -> do
alloca $ \errptr -> do
alloca $ \erroffset -> do
pcre_ptr <- c_pcre_compile pattern (combineOptions flags) errptr erroffset nullPtr
if pcre_ptr == nullPtr
then do
err <- peekCString =<< peek errptr
return (Left err)
else do
reg <- newForeignPtr finalizerFree pcre_ptr -- release with free()
return (Right (Regex reg str))
-- becomes
compile :: ByteString -> [PCREOption] -> Either String Regex
compile str flags = unsafePerformIO $ lowerContT $ do
pattern <- useAsCString str
errptr <- alloca
erroffset <- alloca
pcre_ptr <- c_pcre_compile pattern (combineOptions flags) errptr erroffset nullPtr
if pcre_ptr == nullPtr
then do
err <- peekCString =<< peek errptr
return (Left err)
else do
reg <- newForeignPtr finalizerFree pcre_ptr -- release with free()
return (Right (Regex reg str))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment