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

Optional required strictness for decoding #65

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 16 additions & 9 deletions thrift/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ type Decoder interface {
}

type decoder struct {
r ProtocolReader
r ProtocolReader
enforceRequired bool
}

// DecodeStruct tries to deserialize a struct from a Thrift stream
func DecodeStruct(r ProtocolReader, v interface{}) (err error) {
return DecodeStructWithStrictness(r, true, v)
}

func DecodeStructWithStrictness(r ProtocolReader, enforceRequired bool, v interface{}) (err error) {
if de, ok := v.(Decoder); ok {
return de.DecodeThrift(r)
}
Expand All @@ -32,7 +37,7 @@ func DecodeStruct(r ProtocolReader, v interface{}) (err error) {
err = r.(error)
}
}()
d := &decoder{r}
d := &decoder{r: r, enforceRequired: enforceRequired}
vo := reflect.ValueOf(v)
for vo.Kind() != reflect.Ptr {
d.error(&UnsupportedValueError{Value: vo, Str: "pointer to struct expected"})
Expand Down Expand Up @@ -173,13 +178,15 @@ func (d *decoder) readValue(thriftType byte, rf reflect.Value) {
d.error(err)
}

if req != 0 {
for i := 0; req != 0; i, req = i+1, req>>1 {
if req&1 != 0 {
d.error(&MissingRequiredField{
StructName: v.Type().Name(),
FieldName: meta.fields[i].name,
})
if d.enforceRequired {
if req != 0 {
for i := 0; req != 0; i, req = i+1, req>>1 {
if req&1 != 0 {
d.error(&MissingRequiredField{
StructName: v.Type().Name(),
FieldName: meta.fields[i].name,
})
}
}
}
}
Expand Down