CrowdStrike / csproto

CrowdStrike's Protocol Buffers library
MIT License
122 stars 13 forks source link

EncodeNested with custom keys #133

Open 3052 opened 8 months ago

3052 commented 8 months ago

I see this:

https://godocs.io/github.com/CrowdStrike/csproto#Encoder.EncodeNested

but its not clear what keys are being used. after some testing it seems the code just pick 1 and then 2, etc. is it possible to encode something like this with custom keys?

dylan-bourque commented 8 months ago

A nested message is encoded as a bytes field using whatever tag gets passed to EncodeNested. The tags for the fields within that nested message come from the message itself. The only thing that is hard-coded are the field tags for map elements, which are always 1 for the key and 2 for the value.

I'm not exactly sure what you're asking. Can you clarify?

3052 commented 8 months ago

look at this:

https://github.com/CrowdStrike/csproto/blob/5b2bf93eaee9a349760479418b1cc93ec2c8ada2/encoder_test.go#L759-L767

no keys are explicitly given to the Name and Value fields, but if you decode the resulting bytes its discovered that 1 and 2 were used.

dylan-bourque commented 8 months ago

I see. That testNestedMsg type is a local "mock" specifically for those tests, not an actual protobuf message. The tags actually are hard-coded in testNestedMsg.MarshalTo() here. csproto.Marshal() will call that method, if it exists, passing in a pre-allocated buffer based on the value returned by the message's Size() method. In this case, I took advantage of that to not have to generate code from a .proto file for these tests.

For a real message, the tags would come from the field IDs in the .proto file.