add a simple abstraction for bytearray allocation+fill
This commit is contained in:
parent
1a8a5aef62
commit
41039c7b5b
46
Crypto/Internal/ByteArray.hs
Normal file
46
Crypto/Internal/ByteArray.hs
Normal file
@ -0,0 +1,46 @@
|
||||
-- |
|
||||
-- Module : Crypto.Internal.ByteArray
|
||||
-- License : BSD-style
|
||||
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
|
||||
-- Stability : stable
|
||||
-- Portability : Good
|
||||
--
|
||||
-- Simple and efficient byte array types
|
||||
--
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE MagicHash #-}
|
||||
{-# LANGUAGE UnboxedTuples #-}
|
||||
module Crypto.Internal.ByteArray
|
||||
( ByteArray(..)
|
||||
, byteArrayAllocAndFreeze
|
||||
) where
|
||||
|
||||
import Data.SecureMem
|
||||
import Crypto.Internal.Memory
|
||||
import Crypto.Internal.Compat
|
||||
import Foreign.Ptr
|
||||
import Foreign.ForeignPtr
|
||||
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString.Internal as B
|
||||
|
||||
class ByteArray ba where
|
||||
byteArrayAlloc :: Int -> (Ptr p -> IO ()) -> IO ba
|
||||
|
||||
instance ByteArray Bytes where
|
||||
byteArrayAlloc = bytesAlloc
|
||||
|
||||
instance ByteArray ByteString where
|
||||
byteArrayAlloc sz f = do
|
||||
fptr <- B.mallocByteString sz
|
||||
withForeignPtr fptr (f . castPtr)
|
||||
return $! B.PS fptr 0 sz
|
||||
|
||||
instance ByteArray SecureMem where
|
||||
byteArrayAlloc sz f = do
|
||||
out <- allocateSecureMem sz
|
||||
withSecureMemPtr out (f . castPtr)
|
||||
return out
|
||||
|
||||
byteArrayAllocAndFreeze :: ByteArray a => Int -> (Ptr p -> IO ()) -> a
|
||||
byteArrayAllocAndFreeze sz f = unsafeDoIO (byteArrayAlloc sz f)
|
||||
Loading…
Reference in New Issue
Block a user