Skip to content

Commit

Permalink
Use new unsafe functions introduced in go 1.20
Browse files Browse the repository at this point in the history
This eliminates usage of deprecated and error prone `reflect.SliceHeader` and `reflect.StringHeader`. Backwards compatibility saved with build tags
  • Loading branch information
xakep666 committed Sep 18, 2023
1 parent 032f6d9 commit 8154550
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 12 deletions.
4 changes: 2 additions & 2 deletions util_unsafe.go → util_unsafe_119.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//go:build !purego
// +build !purego
//go:build !purego && !go1.20
// +build !purego,!go1.20

package ws

Expand Down
14 changes: 14 additions & 0 deletions util_unsafe_120.go
Original file line number Diff line number Diff line change
@@ -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))

Check failure on line 9 in util_unsafe_120.go

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, oldstable)

unsafe.StringData requires go1.20 or later (-lang was set to go1.15; check go.mod)
}

func btsToString(bts []byte) (str string) {
return unsafe.String(&bts[0], len(bts))

Check failure on line 13 in util_unsafe_120.go

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, oldstable)

unsafe.String requires go1.20 or later (-lang was set to go1.15; check go.mod)
}
12 changes: 12 additions & 0 deletions wsutil/util_go119_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build go1.20
// +build go1.20

package wsutil

import (
"unsafe"
)

func fakeMake(n int) []byte {
return unsafe.Slice((*byte)(nil), n) // len and cap are 'n'
}
18 changes: 18 additions & 0 deletions wsutil/util_go120_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//go:build !go1.20
// +build !go1.20

package wsutil

import (
"reflect"
"unsafe"
)

func fakeMake(n int) (r []byte) {
rh := (*reflect.SliceHeader)(unsafe.Pointer(&r))
*rh = reflect.SliceHeader{
Len: n,
Cap: n,
}
return r
}
10 changes: 0 additions & 10 deletions wsutil/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"reflect"
"strconv"
"testing"
"unsafe"

"github.com/gobwas/ws"
)
Expand Down Expand Up @@ -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",
Expand Down

0 comments on commit 8154550

Please sign in to comment.