Sfoglia il codice sorgente

Fix possible memory confusion in unsafe slice cast (#21)

* fix possible memory confusion in unsafe slice cast

* update unsafe.go to use simpler, still safe cast
Johannes Lauinger 5 anni fa
parent
commit
05015c3ec1
1 ha cambiato i file con 6 aggiunte e 7 eliminazioni
  1. 6 7
      unsafe.go

+ 6 - 7
unsafe.go

@@ -11,12 +11,11 @@ func unsafeBytes2String(b []byte) string {
 	return *(*string)(unsafe.Pointer(&b))
 }
 
-func unsafeString2Bytes(s string) []byte {
+func unsafeString2Bytes(s string) (b []byte) {
 	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
-	bh := reflect.SliceHeader{
-		Data: sh.Data,
-		Len:  sh.Len,
-		Cap:  sh.Len,
-	}
-	return *(*[]byte)(unsafe.Pointer(&bh))
+	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
+	bh.Data = sh.Data
+	bh.Cap = sh.Len
+	bh.Len = sh.Len
+	return b
 }