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 8204bda
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 13 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: 1 addition & 11 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 Expand Up @@ -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",
Expand Down

0 comments on commit 8204bda

Please sign in to comment.