[Haskell-cafe] ByteString and ByteString.Builder questions
Zoran BoĆĄnjak
zoran.bosnjak at via.si
Thu Nov 30 06:58:32 UTC 2023
Thanks for your answer. That makes sense. In particular the fact that there should be no need to read own output.
However, one problem remains. Data format I am working with contains a total-length prefix. That is:
2 bytes of total length somewhere in the header of the message (header is of the fixed length). But the builder does not directly provide length.
So, how do I suppose to effectively encode the message in the form:
msg = header <> chunk1 <> chunk2 <> ...
Should I use (Builder, Sum Int) instead of plain Builder when composing?
Or
data MyBuilder = MyBuilder Builder Int
... and create a Monoid instance?
Or any other approach?
Zoran
----- Original Message -----
From: "Viktor Dukhovni" <ietf-dane at dukhovni.org>
To: "haskell-cafe" <haskell-cafe at haskell.org>
Sent: Thursday, November 30, 2023 12:27:18 AM
Subject: Re: [Haskell-cafe] ByteString and ByteString.Builder questions
On Wed, Nov 29, 2023 at 12:24:17PM -0500, Viktor Dukhovni wrote:
>
> > if I understand correctly, the ByteString.Builder is used to
> > efficiently construct sequence of bytes from smaller parts.
>
> Best used in continuation-passing-style (right-associatively), where all
> the subsequent builders are lazily added as part of constructing the
> "head" builder.
>
> builder = chunk1 <> (chunk2 <> (chunk3 <> (... <> chunkN)...))
>
> Repeatedly appending tail chunks (effectively left-associate) is
> noticeably less efficient (similar to lists). A work-around is to
> instead append (Builder->Builder) endomorphisms.
>
> b1 = Endo (mappend chunk1)
> b2 = b1 <> Endo (mappend chunk2)
> b3 = b2 <> Endo (mappend chunk3)
> ...
> bN = ...
Actually, this part is was a myth I failed to check, looking at the
`Builder` code, I see that builder `mappend` is already endomorphism
composition, so the extra wrapping is redundant.
So use builders for output, and don't attempt to model some hybrid of
builders and bytestrings. It is rather unclear what problem that is
actually intended to solve.
--
Viktor.
_______________________________________________
Haskell-Cafe mailing list
To (un)subscribe, modify options or view archives go to:
http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
Only members subscribed via the mailman list are allowed to post.
More information about the Haskell-Cafe
mailing list