Skip to content

Commit 70b3af3

Browse files
jmaraisdsnet
authored andcommitted
proto: return errors when using deterministic marshaling with custom Marshalers
Custom marshalers cannot report that they are definitely deterministic. It is better to report that this is not supported than to give undefined behavior.
1 parent 0cb4f73 commit 70b3af3

File tree

5 files changed

+417
-352
lines changed

5 files changed

+417
-352
lines changed

proto/all_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2303,6 +2303,17 @@ func TestInvalidUTF8(t *testing.T) {
23032303
}
23042304
}
23052305

2306+
func TestDeterministicErrorOnCustomMarshaler(t *testing.T) {
2307+
u := uint64(0)
2308+
in := &CustomDeterministicMarshaler{Field1: &u}
2309+
var b1 Buffer
2310+
b1.SetDeterministic(true)
2311+
err := b1.Marshal(in)
2312+
if !strings.Contains(err.Error(), "deterministic") {
2313+
t.Fatalf("Expected: %s but got %s", "proto: deterministic not supported by the Marshal method of test_proto.CustomDeterministicMarshaler", err.Error())
2314+
}
2315+
}
2316+
23062317
// Benchmarks
23072318

23082319
func testMsg() *GoTest {

proto/table_marshal.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,9 @@ func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte
225225
// If the message can marshal itself, let it do it, for compatibility.
226226
// NOTE: This is not efficient.
227227
if u.hasmarshaler {
228+
if deterministic {
229+
return nil, errors.New("proto: deterministic not supported by the Marshal method of " + u.typ.String())
230+
}
228231
m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
229232
b1, err := m.Marshal()
230233
b = append(b, b1...)

proto/test_proto/deterministic.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package test_proto
2+
3+
func (m *CustomDeterministicMarshaler) Marshal() ([]byte, error) {
4+
return []byte{}, nil
5+
}

0 commit comments

Comments
 (0)