Skip to content

Commit 8d92cf5

Browse files
Bryan Millsdsymonds
Bryan Mills
authored andcommitted
Add specific error for oneof with nil element.
Signed-off-by: David Symonds <[email protected]>
1 parent d120e2f commit 8d92cf5

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

proto/all_test.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1329,9 +1329,18 @@ func TestRequiredFieldEnforcement(t *testing.T) {
13291329

13301330
func TestTypedNilMarshal(t *testing.T) {
13311331
// A typed nil should return ErrNil and not crash.
1332-
_, err := Marshal((*GoEnum)(nil))
1333-
if err != ErrNil {
1334-
t.Errorf("Marshal: got err %v, want ErrNil", err)
1332+
{
1333+
var m *GoEnum
1334+
if _, err := Marshal(m); err != ErrNil {
1335+
t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
1336+
}
1337+
}
1338+
1339+
{
1340+
m := &Communique{Union: &Communique_Msg{nil}}
1341+
if _, err := Marshal(m); err == nil || err == ErrNil {
1342+
t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err)
1343+
}
13351344
}
13361345
}
13371346

proto/encode.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ var (
6464
// a struct with a repeated field containing a nil element.
6565
errRepeatedHasNil = errors.New("proto: repeated field has nil element")
6666

67+
// errOneofHasNil is the error returned if Marshal is called with
68+
// a struct with a oneof field containing a nil element.
69+
errOneofHasNil = errors.New("proto: oneof field has nil value")
70+
6771
// ErrNil is the error returned if Marshal is called with nil.
6872
ErrNil = errors.New("proto: Marshal called with nil")
6973
)
@@ -1222,7 +1226,9 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
12221226
// Do oneof fields.
12231227
if prop.oneofMarshaler != nil {
12241228
m := structPointer_Interface(base, prop.stype).(Message)
1225-
if err := prop.oneofMarshaler(m, o); err != nil {
1229+
if err := prop.oneofMarshaler(m, o); err == ErrNil {
1230+
return errOneofHasNil
1231+
} else if err != nil {
12261232
return err
12271233
}
12281234
}

0 commit comments

Comments
 (0)