瀏覽代碼

codec: document that Selfer should not blindly call (Must)?(En|De)code

Ugorji Nwoke 7 年之前
父節點
當前提交
405bbdfe11
共有 2 個文件被更改,包括 20 次插入0 次删除
  1. 13 0
      codec/codec_test.go
  2. 7 0
      codec/helper.go

+ 13 - 0
codec/codec_test.go

@@ -46,6 +46,15 @@ type testMbsCustStrT []testCustomStringT
 
 func (testMbsCustStrT) MapBySlice() {}
 
+// type testSelferRecur struct{}
+
+// func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) {
+// 	e.MustEncode(s)
+// }
+// func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) {
+// 	d.MustDecode(s)
+// }
+
 type testIntfMapI interface {
 	GetIntfMapV() string
 }
@@ -2677,6 +2686,10 @@ func TestMsgpackDecodeMapAndExtSizeMismatch(t *testing.T) {
 	b = []byte{0xc9, 0x7f, 0xff, 0xff, 0xff, 0xda, 0x1}
 	var a interface{}
 	fn(t, b, &a)
+
+	// b = []byte{0x00}
+	// var s testSelferRecur
+	// fn(t, b, &s)
 }
 
 // ----------

+ 7 - 0
codec/helper.go

@@ -424,6 +424,13 @@ var immutableKindsSet = [32]bool{
 // Consequently, during (en|de)code, this takes precedence over
 // (text|binary)(M|Unm)arshal or extension support.
 //
+// By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself.
+// If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error.
+// For example, the snippet below will cause such an error.
+//     type testSelferRecur struct{}
+//     func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) }
+//     func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) }
+//
 // Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
 // This is because, during each decode, we first check the the next set of bytes
 // represent nil, and if so, we just set the value to nil.