module Raaz.Core.Util.ByteString
( length, replicate
, fromByteStringStorable
, createFrom
, withByteString
, unsafeCopyToPointer
, unsafeNCopyToPointer
) where
import Prelude hiding (length, replicate)
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Data.ByteString.Internal( toForeignPtr
, create
)
import Data.Word
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Ptr (castPtr, plusPtr)
import Foreign.Storable (peek, Storable)
import System.IO.Unsafe (unsafePerformIO)
import Raaz.Core.Types.Pointer
length :: ByteString -> BYTES Int
length = BYTES . B.length
replicate :: LengthUnit l => l -> Word8 -> ByteString
replicate l = B.replicate sz
where BYTES sz = inBytes l
unsafeCopyToPointer :: ByteString
-> Pointer
-> IO ()
unsafeCopyToPointer bs cptr = withForeignPtr fptr $
\ p -> memcpy dest (p `plusPtr` offset) (BYTES n)
where (fptr, offset,n) = toForeignPtr bs
dest = castPtr cptr
unsafeNCopyToPointer :: LengthUnit n
=> n
-> ByteString
-> Pointer
-> IO ()
unsafeNCopyToPointer n bs cptr = withForeignPtr fptr $
\ p -> memcpy dest (p `plusPtr` offset) n
where (fptr, offset,_) = toForeignPtr bs
dest = castPtr cptr
withByteString :: ByteString -> (Pointer -> IO a) -> IO a
withByteString bs f = withForeignPtr fptr (f . flip plusPtr off . castPtr)
where (fptr, off, _) = toForeignPtr bs
fromByteStringStorable :: Storable k => ByteString -> k
fromByteStringStorable src = unsafePerformIO $ withByteString src (peek . castPtr)
createFrom :: LengthUnit l => l -> Pointer -> IO ByteString
createFrom l cptr = create bytes filler
where filler dest = memcpy (castPtr dest) cptr l
BYTES bytes = inBytes l