使用Data.Cereal或Data.Binary序列化字符串 [英] Serializing a String with Data.Cereal or Data.Binary

查看:123
本文介绍了使用Data.Cereal或Data.Binary序列化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个协议,该协议规定表示密码的字符串应串行化为固定长度的10字节字段。我正在使用Data.Cereal来执行此任务。以下是我最近的一次访问:

I am implementing a protocol that dictates that a string representing a password should be serialized to a fixed length, 10-byte field. I am using Data.Cereal to perform this task. Here's my most recent go at it:

padText :: Int -> Text -> Text
padText fieldLen = T.justifyLeft fieldLen '\NUL'

putPassword :: Putter Password
putPassword = put . TE.encodeUtf8 . padText 10

置于ByteStrings前面的是一个额外的8字节块, :

put on ByteStrings prepends an additional 8-byte chunk onto the front of what it is encoding making:

 runPut $ putPassword "Friend"

导致:

result in :

"\NUL\NUL\NUL\NUL\NUL\NUL\NUL\nFriend\NUL\NUL\NUL\NUL"

我不想要额外的块。为什么这样表现?

I don't want the extra chunk. Why is put behaving this way?

有人知道如何序列化只有10个原始字节吗?

Does anyone know how to serialize only the 10 original bytes?

推荐答案

我假设额外的块是指\NUL\NUL\NUL\NUL\NUL\NUL\NUL\\\
。这是一个64位长的字段(注意它的值是 10 ),它是 ByteString 。因为在调用 TE.encodeUtf8 之后你已经有了一个字节串,所以我建议你只用 putByteString 来避免使用长度字段(或者如果您导入惰性文本编码模块,< putLazyByteString )。

I assume by "the extra chunk" you mean the first bit of "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\n. That is a 64 bit length field (notice it's value is 10) which is part of the Serialize definition for ByteString. Since you already have a bytestring after calling TE.encodeUtf8, I suggest you just use putByteString to avoid the length field (or putLazyByteString if you're importing a lazy text encoding module).

这篇关于使用Data.Cereal或Data.Binary序列化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆