如何使用Data.Binary.BitPut

时间:2016-03-05 14:37:15

标签: haskell monads

我想将数据(:: DnsMessage)打包成ByteString。通过一点网页搜索,我了解到我可以使用Data.Binary.BitPut Library将Bool或Int等数据打包到ByteString中。现在我正在努力通过辩论。

此代码工作正常。

import qualified Data.Binary.BitPut as BP
import qualified Data.ByteString.Internal as BSI

main :: IO()
main = do
  let res = BP.runBitPut makePacket
  print res

makePacket :: BP.BitPut
makePacket = do
  BP.putBit True
  BP.putNBits 7 $ BSI.c2w 'A'
  BP.putByteString $ BS.pack $ map BSI.c2w "AAAA"

现在我想这样做。

defaultQuery :: DnsMessage

main :: IO()
main = do
  let res = defaultQuery BP.runBitPut makePacket
  print res

makePacket :: DnsMessage -> BP.BitPut
makePacket msg = do
  BP.putBit $ foo msg
  BP.putNBits 5 $ bar msg
  BP.putByteString ...

我该如何做到这一点?

https://hackage.haskell.org/package/binary-strict-0.4.8.3/docs/Data-Binary-BitPut.html

data DnsMessage = DnsMessage {
  header      :: DnsHeader,
  question    :: DnsQuestion,
  answer      :: [DnsResourceRecord],
  authority   :: [DnsResourceRecord],
  additional  :: [DnsResourceRecord]
}

data DnsHeader = DnsHeader {
  mid     :: Word16,
  flags   :: DnsFlags,
  qdcount :: Word16,
  ancount :: Word16,
  nscount :: Word16,
  arcount :: Word16
}

data DnsFlags = DnsFlags {
  isres   :: Bool,
  opcode  :: Word8,
  aa      :: Bool,
  tc      :: Bool,
  rd      :: Bool,
  ra      :: Bool,
  z       :: Word8,
  rcode   :: Word8
}

data DnsQuestion = DnsQuestion {
  qname   :: [Word8],
  qtype   :: Word16,
  qclass  :: Word16
}

--The answer, authority, and additional sections all share this format
data DnsResourceRecord = DnsResourceRecord {
  rrname        :: [Word8],
  rrtype        :: Word16,
  rrclass       :: Word16,
  rrttl         :: Word32,
  rdatalength   :: Word16,
  rdata         :: [Word8]
}

0 个答案:

没有答案