From f3bf67df99152ae565179518f2d2f3d120cd0f8e Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Sun, 29 Mar 2015 10:43:11 +0100 Subject: [PATCH] add withByteArray --- Crypto/Internal/ByteArray.hs | 7 ++++++- Crypto/Internal/Memory.hs | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/Crypto/Internal/ByteArray.hs b/Crypto/Internal/ByteArray.hs index acbd9cb..c9b705c 100644 --- a/Crypto/Internal/ByteArray.hs +++ b/Crypto/Internal/ByteArray.hs @@ -28,10 +28,12 @@ import qualified Data.ByteString.Internal as B class ByteArray ba where byteArrayAlloc :: Int -> (Ptr p -> IO ()) -> IO ba byteArrayLength :: ba -> Int + withByteArray :: ba -> (Ptr p -> IO a) -> IO a instance ByteArray Bytes where - byteArrayAlloc = bytesAlloc + byteArrayAlloc = bytesAlloc byteArrayLength = bytesLength + withByteArray = withBytes instance ByteArray ByteString where byteArrayAlloc sz f = do @@ -39,6 +41,8 @@ instance ByteArray ByteString where withForeignPtr fptr (f . castPtr) return $! B.PS fptr 0 sz byteArrayLength = B.length + withByteArray b f = withForeignPtr fptr $ \ptr -> f (ptr `plusPtr` off) + where (fptr, off, _) = B.toForeignPtr b instance ByteArray SecureMem where byteArrayAlloc sz f = do @@ -46,6 +50,7 @@ instance ByteArray SecureMem where withSecureMemPtr out (f . castPtr) return out byteArrayLength = secureMemGetSize + withByteArray b f = withSecureMemPtr b (f . castPtr) byteArrayAllocAndFreeze :: ByteArray a => Int -> (Ptr p -> IO ()) -> a byteArrayAllocAndFreeze sz f = unsafeDoIO (byteArrayAlloc sz f) diff --git a/Crypto/Internal/Memory.hs b/Crypto/Internal/Memory.hs index b1f55b2..b549603 100644 --- a/Crypto/Internal/Memory.hs +++ b/Crypto/Internal/Memory.hs @@ -17,6 +17,7 @@ module Crypto.Internal.Memory , bytesCopyTemporary , bytesAlloc , bytesLength + , withBytes ) where import Data.Word @@ -77,3 +78,6 @@ bytesAlloc sz f = do bytesLength :: Bytes -> Int bytesLength = sizeofBytes + +withBytes :: Bytes -> (Ptr p -> IO a) -> IO a +withBytes = withPtr