stdlib: support go1.17 unsafe functions

This adds support for go1.17 `unsafe.Add` and `unsafe.Slice`.
This commit is contained in:
Nicholas Wiersma
2021-08-19 10:38:05 +02:00
committed by GitHub
parent b84278dcc6
commit a69b9bc2dc
4 changed files with 101 additions and 1 deletions

23
_test/unsafe6.go Normal file
View File

@@ -0,0 +1,23 @@
package main
import (
"fmt"
"unsafe"
)
type S struct {
X int
Y int
Z int
}
func main() {
x := S{Z: 5}
ptr := unsafe.Pointer(&x)
offset := int(unsafe.Offsetof(x.Z))
p := unsafe.Add(ptr, offset)
i := *(*int)(p)
fmt.Println(i)
}

20
_test/unsafe7.go Normal file
View File

@@ -0,0 +1,20 @@
package main
import (
"fmt"
"unsafe"
)
type S struct {
X int
Y int
Z int
}
func main() {
x := [2]S{{Z: 5}, {Z: 10}}
s := unsafe.Slice(&x[0], 2)
fmt.Println(s)
}

View File

@@ -98,7 +98,9 @@ func TestInterpConsistencyBuild(t *testing.T) {
file.Name() == "server1.go" || // syntax parsing
file.Name() == "server0.go" || // syntax parsing
file.Name() == "server.go" || // syntax parsing
file.Name() == "range9.go" { // expect error
file.Name() == "range9.go" || // expect error
file.Name() == "unsafe6.go" || // needs go.mod to be 1.17
file.Name() == "unsafe7.go" { // needs go.mod to be 1.17
continue
}

View File

@@ -0,0 +1,55 @@
//go:build go1.17
// +build go1.17
// Package unsafe provides wrapper of standard library unsafe package to be imported natively in Yaegi.
package unsafe
import (
"errors"
"reflect"
"unsafe"
)
func init() {
// Add builtin functions to unsafe.
Symbols["unsafe/unsafe"]["Add"] = reflect.ValueOf(add)
Symbols["unsafe/unsafe"]["Slice"] = reflect.ValueOf(slice)
}
func add(ptr unsafe.Pointer, l int) unsafe.Pointer {
return unsafe.Pointer(uintptr(ptr) + uintptr(l))
}
type emptyInterface struct {
_ uintptr
data unsafe.Pointer
}
func slice(i interface{}, l int) interface{} {
if l == 0 {
return nil
}
v := reflect.ValueOf(i)
if v.Type().Kind() != reflect.Ptr {
panic(errors.New("first argument to unsafe.Slice must be pointer"))
}
if v.IsNil() {
panic(errors.New("unsafe.Slice: ptr is nil and len is not zero"))
}
if l < 0 {
panic(errors.New("unsafe.Slice: len out of range"))
}
ih := *(*emptyInterface)(unsafe.Pointer(&i))
inter := reflect.MakeSlice(reflect.SliceOf(v.Type().Elem()), l, l).Interface()
ptr := (*emptyInterface)(unsafe.Pointer(&inter)).data
sh := (*reflect.SliceHeader)(ptr)
sh.Data = uintptr(ih.data)
sh.Len = l
sh.Cap = l
return inter
}