-
Notifications
You must be signed in to change notification settings - Fork 17.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: encoding/binary: Add SizeUvarint()
and SizeVarint()
#66284
Comments
What's the intended use-case for this? You could also use |
We'd like to preallocate a buffer which includes a uvarint in the middle. Actually, our use case is pretty similar to that of protobuf's implementation looking at the references. It doesn't really make sense for us to import a whole library just for one line of code though, in fact it seems like the existence of this code in |
I usually preallocate |
That doesn't quite work for us because we want to determine if adding a field into our serialized buffer causes the buffer to exceed a certain size, and if so we do a different allocation strategy (potentially writing it to a different buffer). Hardcoding the buffer to |
Though the use-case seems genuine, it seems like a pretty obscure one as in most cases (as @Jorropo points out) you can allocate a local temporary array of the maximum varint size (10) and encode into that to find the size, then copy from the local buffer to the output buffer. BTW, the proposal should include a signed variant as well. |
SizeUvarint()
SizeUvarint()
and SizeVarint()
A little copying never hurt :) That said, I agree these would be good additions to the stdlib. I've written them myself a number of times when working with serialization code. |
There is the existing A IIRC, protobuf had another use case for this where you're encoding a large slice of integers, and it is faster to pre-compute the necessary buffer before encoding. Naively assuming that the buffer needs to be |
I don't mean to jump the gun, but #66366 merely follows protowire.SizeVarint to compute the encoded size. Signed integers follow the zigzag encoding in go/src/encoding/binary/varint.go Lines 102 to 108 in 0a6f05e
|
Change https://go.dev/cl/572196 mentions this issue: |
Proposal Details
It would be nice to have a function like
SizeUvarint()
andSizeVarint()
that calculates the size of aUVarint
orVarint
representation without actually appending the bytes to a buffer. Exactly like AppendUvarint but it simply counts the bytes that would have been appended.The current roundabout way of doing this is something like:
The text was updated successfully, but these errors were encountered: