packages feed

crypton-2.3.1 / Crypto / Internal / Builder.hs

{-# LANGUAGE BangPatterns #-}-- |-- Module      : Crypto.Internal.Builder-- License     : BSD-style-- Maintainer  : Olivier Chéron <olivier.cheron@gmail.com>-- Stability   : stable-- Portability : Good---- Delaying and merging ByteArray allocations.  This is similar to module-- "Data.ByteArray.Pack" except the total length is computed automatically based-- on what is appended.module Crypto.Internal.Builder (    Builder,    buildAndFreeze,    builderLength,    byte,    bytes,    zero,) whereimport Data.ByteArray (ByteArray, ByteArrayAccess)import qualified Data.ByteArray as Bimport Data.Memory.PtrMethods (memSet)import Foreign.Ptr (Ptr, plusPtr)import Foreign.Storable (poke)import Crypto.Internal.Imports hiding (empty)data Builder = Builder !Int (Ptr Word8 -> IO ()) -- size and initializerinstance Semigroup Builder where    (Builder s1 f1) <> (Builder s2 f2) = Builder (s1 + s2) f      where        f p = f1 p >> f2 (p `plusPtr` s1)builderLength :: Builder -> IntbuilderLength (Builder s _) = sbuildAndFreeze :: ByteArray ba => Builder -> babuildAndFreeze (Builder s f) = B.allocAndFreeze s fbyte :: Word8 -> Builderbyte !b = Builder 1 (`poke` b)bytes :: ByteArrayAccess ba => ba -> Builderbytes bs = Builder (B.length bs) (B.copyByteArrayToPtr bs)zero :: Int -> Builderzero s = if s > 0 then Builder s (\p -> memSet p 0 s) else emptyempty :: Builderempty = Builder 0 (const $ return ())