From e13fd755ee30acf326335f582317aa53ea3f34f7 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Mon, 3 Apr 2023 15:10:38 +1000 Subject: [PATCH] bencode: Only use unsafe.String for go>=1.20 --- bencode/decode.go | 3 +-- bencode/misc.go | 5 ----- bencode/string.go | 9 +++++++++ bencode/string_go120.go | 9 +++++++++ 4 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 bencode/string.go create mode 100644 bencode/string_go120.go diff --git a/bencode/decode.go b/bencode/decode.go index 6300f5cd..3839b849 100644 --- a/bencode/decode.go +++ b/bencode/decode.go @@ -10,7 +10,6 @@ import ( "runtime" "strconv" "sync" - "unsafe" ) // The default bencode string length limit. This is a poor attempt to prevent excessive memory @@ -256,7 +255,7 @@ func (d *Decoder) parseString(v reflect.Value) error { d.buf.Grow(length) b := d.buf.Bytes()[:length] read(b) - x, err := strconv.ParseBool(unsafe.String(unsafe.SliceData(b), len(b))) + x, err := strconv.ParseBool(bytesAsString(b)) if err != nil { x = length != 0 } diff --git a/bencode/misc.go b/bencode/misc.go index 2e9f1fac..66900085 100644 --- a/bencode/misc.go +++ b/bencode/misc.go @@ -2,7 +2,6 @@ package bencode import ( "reflect" - "unsafe" ) // Wow Go is retarded. @@ -10,7 +9,3 @@ var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() ) - -func bytesAsString(b []byte) string { - return *(*string)(unsafe.Pointer(&b)) -} diff --git a/bencode/string.go b/bencode/string.go new file mode 100644 index 00000000..0c6e307a --- /dev/null +++ b/bencode/string.go @@ -0,0 +1,9 @@ +//go:build !go1.20 + +package bencode + +import "unsafe" + +func bytesAsString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/bencode/string_go120.go b/bencode/string_go120.go new file mode 100644 index 00000000..1688d9b6 --- /dev/null +++ b/bencode/string_go120.go @@ -0,0 +1,9 @@ +//go:build go1.20 + +package bencode + +import "unsafe" + +func bytesAsString(b []byte) string { + return unsafe.String(unsafe.SliceData(b), len(b)) +}