瀏覽代碼

codec: make detachZeroCopyBytes robuts so it works well for bytes and IO paths

Ugorji Nwoke 6 年之前
父節點
當前提交
bbab85ee41
共有 3 個文件被更改,包括 23 次插入11 次删除
  1. 21 9
      codec/decode.go
  2. 1 1
      codec/helper.go
  3. 1 1
      codec/reader.go

+ 21 - 9
codec/decode.go

@@ -1929,17 +1929,29 @@ func decByteSlice(r *decRd, clen, maxInitLen int, bs []byte) (bsOut []byte) {
 	return
 }
 
+// detachZeroCopyBytes will copy the in bytes into dest,
+// or create a new one if not large enough.
+//
+// It is used to ensure that the []byte returned is not
+// part of the input stream or input stream buffers.
 func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) {
-	if xlen := len(in); xlen > 0 {
-		if isBytesReader || xlen <= scratchByteArrayLen {
-			if cap(dest) >= xlen {
-				out = dest[:xlen]
-			} else {
-				out = make([]byte, xlen)
-			}
-			copy(out, in)
-			return
+	if len(in) > 0 {
+		// if isBytesReader || len(in) <= scratchByteArrayLen {
+		// 	if cap(dest) >= len(in) {
+		// 		out = dest[:len(in)]
+		// 	} else {
+		// 		out = make([]byte, len(in))
+		// 	}
+		// 	copy(out, in)
+		// 	return
+		// }
+		if cap(dest) >= len(in) {
+			out = dest[:len(in)]
+		} else {
+			out = make([]byte, len(in))
 		}
+		copy(out, in)
+		return
 	}
 	return in
 }

+ 1 - 1
codec/helper.go

@@ -150,7 +150,7 @@ const (
 	// rvNLen is the length of the array for readn or writen calls
 	rwNLen = 7
 
-	scratchByteArrayLen = 64
+	// scratchByteArrayLen = 64
 	// initCollectionCap   = 16 // 32 is defensive. 16 is preferred.
 
 	// Support encoding.(Binary|Text)(Unm|M)arshaler.

+ 1 - 1
codec/reader.go

@@ -93,7 +93,7 @@ type ioDecReader struct {
 	rr io.Reader
 	br io.ByteScanner
 
-	x [scratchByteArrayLen]byte // for: get struct field name, swallow valueTypeBytes, etc
+	x [64]byte // for: get struct field name, swallow valueTypeBytes, etc
 	// _ [1]uint64                 // padding
 }