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 d174f9d
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 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) {

Check failure on line 11 in wsutil/util_go120_test.go

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, stable)

other declaration of fakeMake
rh := (*reflect.SliceHeader)(unsafe.Pointer(&r))
*rh = reflect.SliceHeader{
Len: n,
Cap: n,
}
return r
}

0 comments on commit d174f9d

Please sign in to comment.