From 8204bda87615ad8c14ac4c54c3af808cef563733 Mon Sep 17 00:00:00 2001 From: Vladimir Stolyarov Date: Mon, 18 Sep 2023 23:31:41 +0400 Subject: [PATCH] Use new `unsafe` functions introduced in go 1.20 This eliminates usage of deprecated and error prone `reflect.SliceHeader` and `reflect.StringHeader`. Backwards compatibility saved with build tags --- util_unsafe.go => util_unsafe_119.go | 4 ++-- util_unsafe_120.go | 14 ++++++++++++++ wsutil/writer_test.go | 12 +----------- 3 files changed, 17 insertions(+), 13 deletions(-) rename util_unsafe.go => util_unsafe_119.go (85%) create mode 100644 util_unsafe_120.go diff --git a/util_unsafe.go b/util_unsafe_119.go similarity index 85% rename from util_unsafe.go rename to util_unsafe_119.go index b732297..41f8a17 100644 --- a/util_unsafe.go +++ b/util_unsafe_119.go @@ -1,5 +1,5 @@ -//go:build !purego -// +build !purego +//go:build !purego && !go1.20 +// +build !purego,!go1.20 package ws diff --git a/util_unsafe_120.go b/util_unsafe_120.go new file mode 100644 index 0000000..8857251 --- /dev/null +++ b/util_unsafe_120.go @@ -0,0 +1,14 @@ +//go:build !purego && go1.20 +// +build !purego,go1.20 + +package ws + +import "unsafe" + +func strToBytes(str string) (bts []byte) { + return unsafe.Slice(unsafe.StringData(str), len(str)) +} + +func btsToString(bts []byte) (str string) { + return unsafe.String(&bts[0], len(bts)) +} diff --git a/wsutil/writer_test.go b/wsutil/writer_test.go index d069d09..ec879e3 100644 --- a/wsutil/writer_test.go +++ b/wsutil/writer_test.go @@ -8,7 +8,6 @@ import ( "reflect" "strconv" "testing" - "unsafe" "github.com/gobwas/ws" ) @@ -131,15 +130,6 @@ func genReserveTestCases(s ws.State, n, m, exp int) []reserveTestCase { return ret } -func fakeMake(n int) (r []byte) { - rh := (*reflect.SliceHeader)(unsafe.Pointer(&r)) - *rh = reflect.SliceHeader{ - Len: n, - Cap: n, - } - return r -} - var reserveTestCases = []reserveTestCase{ { name: "len7", @@ -215,7 +205,7 @@ func TestNewWriterBuffer(t *testing.T) { t.Errorf("unexpected panic: %v", thePanic) } }() - w := NewWriterBuffer(nil, test.state, 0, fakeMake(test.buf)) + w := NewWriterBuffer(nil, test.state, 0, make([]byte, test.buf)) if act, exp := len(w.raw)-len(w.buf), test.expOffset; act != exp { t.Errorf( "NewWriteBuffer(%d bytes) has offset %d; want %d",