Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to determine if "length" of ByteString Builder >= N?

Given a Builder what's the most efficient way to determine if the serialized/reified data is greater than, say, 1kB? . My best plan currently is using toLazyByteStringWith with a 1kB initial chunk size, and inspect just the first chunk to see if it's full.

But is there some way to do this without writing any data at all? (and preferably in a pure function?)

I got a bit lost trying to understand how running Builder directly on a socket works.

like image 282
jberryman Avatar asked Oct 27 '25 08:10

jberryman


1 Answers

If efficiency is super important, you may want to write a small wrapper around a monoid that tracks the length explicitly:

type SizedBuilder = (Sum Int, Builder)

byteString = liftA2 (,) (Sum . BS.length) Builder.byteString
word8 = (,) 1 . Builder.word8
word32LE = (,) 4 . Builder.word32LE
string8 = liftA2 (,) (Sum . length) Builder.string8
-- etc.

There's already a suitable monoid instance for this type, but of course if you choose to use newtype instead of type you may want to add one with deriving.

like image 129
Daniel Wagner Avatar answered Oct 29 '25 06:10

Daniel Wagner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!