Skip to content
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

EncodeNested with custom keys #133

Open
3052 opened this issue Dec 19, 2023 · 3 comments
Open

EncodeNested with custom keys #133

3052 opened this issue Dec 19, 2023 · 3 comments
Labels
triage Issues that need to be reviewed by maintainers

Comments

@3052
Copy link

3052 commented Dec 19, 2023

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?

@3052 3052 added the triage Issues that need to be reviewed by maintainers label Dec 19, 2023
@dylan-bourque
Copy link

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
Copy link
Author

3052 commented Dec 19, 2023

look at this:

csproto/encoder_test.go

Lines 759 to 767 in 5b2bf93

var (
name = "test"
val int32 = 42
expected = []byte{0xa, 0x8, 0xa, 0x4, 0x74, 0x65, 0x73, 0x74, 0x10, 0x2a}
)
m := testNestedMsg{
Name: &name,
Value: &val,
}

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
Copy link

dylan-bourque commented Dec 19, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
triage Issues that need to be reviewed by maintainers
Projects
None yet
Development

No branches or pull requests

2 participants