add length abstraction for byte array

This commit is contained in:
Vincent Hanquez 2015-03-29 09:16:44 +01:00
parent a4d3dc4d10
commit 37557af615
2 changed files with 10 additions and 1 deletions

View File

@ -22,25 +22,30 @@ import Foreign.Ptr
import Foreign.ForeignPtr
import Data.ByteString (ByteString)
import qualified Data.ByteString as B (length)
import qualified Data.ByteString.Internal as B
class ByteArray ba where
byteArrayAlloc :: Int -> (Ptr p -> IO ()) -> IO ba
byteArrayAlloc :: Int -> (Ptr p -> IO ()) -> IO ba
byteArrayLength :: ba -> Int
instance ByteArray Bytes where
byteArrayAlloc = bytesAlloc
byteArrayLength = bytesLength
instance ByteArray ByteString where
byteArrayAlloc sz f = do
fptr <- B.mallocByteString sz
withForeignPtr fptr (f . castPtr)
return $! B.PS fptr 0 sz
byteArrayLength = B.length
instance ByteArray SecureMem where
byteArrayAlloc sz f = do
out <- allocateSecureMem sz
withSecureMemPtr out (f . castPtr)
return out
byteArrayLength = secureMemGetSize
byteArrayAllocAndFreeze :: ByteArray a => Int -> (Ptr p -> IO ()) -> a
byteArrayAllocAndFreeze sz f = unsafeDoIO (byteArrayAlloc sz f)

View File

@ -16,6 +16,7 @@ module Crypto.Internal.Memory
, bytesTemporary
, bytesCopyTemporary
, bytesAlloc
, bytesLength
) where
import Data.Word
@ -73,3 +74,6 @@ bytesAlloc sz f = do
ba <- newBytes sz
withPtr ba f
return ba
bytesLength :: Bytes -> Int
bytesLength = sizeofBytes