How to serialize small-end PODs painlessly?

Let's say I have the following type:

data WaveFormatChunk = WaveFormatChunk { 
    compression :: Word16,
    channels :: Word16,
    sampleRate :: Word32,
    averageBps :: Word32,
    blockAlign :: Word16,
    significantBits :: Word16
    } deriving (Show)

Is there a way to just dump all of this in a ByteString (or similar structure) in bulk (in the manner of old C structures)? If not, and I need to write a function that separately puts all of them in a list, are there at least functions that make it easy to insert a value into a Word8 list, for example, Word8? Something like putWordBBxe, with the exception of strings or a list of bytes (although I, most likely, am very mistaken, since I have not read it correctly in Monads, it seems to me that Get / Put is mainly used with streams).

Data.Binary is not quite what I'm looking for, it seems more useful for just dumping data on disk than saving it in a specific format with specific (and "wrong") content.

+5
2

Data.Binary bytestring, little-endian.

{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# LANGUAGE RecordWildCards #-}

import Data.Binary
import Data.Binary.Put

import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy  as L

data WaveFormatChunk =
        WaveFormatChunk { 
            compression     :: !Word16,
            channels        :: !Word16,
            sampleRate      :: !Word32,
            averageBps      :: !Word32,
            blockAlign      :: !Word16,
            significantBits :: !Word16
        } 

instance Binary WaveFormatChunk where
    put (WaveFormatChunk{..}) = do
        putWord16le compression 
        putWord16le channels
        putWord32le sampleRate
        putWord32le averageBps
        putWord16le blockAlign
        putWord16le significantBits

    get = undefined

main = C.putStr $ C.concat $ L.toChunks $ encode test
  where
    test = WaveFormatChunk {
            compression     = 0xcafe
          , channels        = 0xface
          , sampleRate      = 0xdeadbeef
          , averageBps      = 0xf01dab1e
          , blockAlign      = 0x5566
          , significantBits = 0xb01d
          }

:

 $ ./A | od -x
 0000000 cafe face beef dead ab1e f01d 5566 b01d

, . , .

+12

, . ByteString:

import Data.ByteString (ByteString)

newtype WaveFormatChunk =
    WaveFormatChunk {
      getWaveFormatChunk :: ByteString
    }

. ​​, :

data Compression = {- ... -}

compression :: Lens' WaveFormatChunk Compression

:

compression :: Lens' WaveFormatChunk Word16

. : -, , . -, ByteString. , , , .

, Haskell . , .

+4

All Articles