{-# LANGUAGE TemplateHaskell #-}
module Rattletrap.Type.Section
( Section(..)
, toSection
)
where
import Rattletrap.Type.Common
import Rattletrap.Type.Word32le
import Rattletrap.Utility.Crc
import qualified Data.Binary as Binary
import qualified Data.Binary.Put as Binary
import qualified Data.ByteString as Bytes
import qualified Data.ByteString.Lazy as LazyBytes
data Section a = Section
{ sectionSize :: Word32le
, sectionCrc :: Word32le
, sectionBody :: a
} deriving (Eq, Ord, Show)
$(deriveJson ''Section)
toSection :: (a -> Binary.Put) -> a -> Section a
toSection encode body =
let bytes = LazyBytes.toStrict . Binary.runPut $ encode body
in
Section
{ sectionSize = Word32le . fromIntegral $ Bytes.length bytes
, sectionCrc = Word32le $ getCrc32 bytes
, sectionBody = body
}