Last active
December 30, 2019 02:51
-
-
Save axman6/3a1528111aad4cb79ea44b51836dec85 to your computer and use it in GitHub Desktop.
An example of how Foreign.Marshal.ContT can make FFI code nicer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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