From e6348918b154cddf50a493701016e0fc2e58b968 Mon Sep 17 00:00:00 2001 From: YenForYang Date: Fri, 10 Sep 2021 03:16:54 -0500 Subject: [PATCH] Simplify no-copy conversion of []byte to string This is a pretty well-tested method currently in use by `strings.Builder`. It's a one-liner so there's no need to worry about the GC interfering. Messing with (*reflect.StringHeader) is often error-prone and might require a `runtime.KeepAlive` in some cases. --- bencode/misc.go | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/bencode/misc.go b/bencode/misc.go index 3b95afcecc..38b7fce84f 100644 --- a/bencode/misc.go +++ b/bencode/misc.go @@ -18,13 +18,5 @@ var unmarshalerType = reflect.TypeOf(func() *Unmarshaler { }()).Elem() func bytesAsString(b []byte) string { - if len(b) == 0 { - return "" - } - // See https://github.com/golang/go/issues/40701. - var s string - hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) - hdr.Data = uintptr(unsafe.Pointer(&b[0])) - hdr.Len = len(b) - return s + return *(*string)(unsafe.Pointer(&b)) }