Skip to content

[go1.20] Added support for unsafe.SliceData #1298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ func (fc *funcContext) translateBuiltin(name string, sig *types.Signature, args
case "Offsetof":
sel, _ := fc.selectionOf(astutil.RemoveParens(args[0]).(*ast.SelectorExpr))
return fc.formatExpr("%d", typesutil.OffsetOf(sizes32, sel))
case "SliceData":
t := fc.typeOf(args[0]).Underlying().(*types.Slice)
return fc.formatExpr(`$sliceData(%e, %s)`, args[0], fc.typeName(t))
default:
panic(fmt.Sprintf("Unhandled builtin: %s\n", name))
}
Expand Down
7 changes: 7 additions & 0 deletions compiler/prelude/prelude.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,3 +569,10 @@ var $instanceOf = (x, y) => {
var $typeOf = x => {
return typeof (x);
};

var $sliceData = (slice, typ) => {
if (slice === typ.nil) {
return $ptrType(typ.elem).nil;
}
return $indexPtr(slice.$array, slice.$offset, typ.elem);
};
39 changes: 39 additions & 0 deletions tests/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"
"testing"
"time"
"unsafe"

"github.com/google/go-cmp/cmp"
"github.com/gopherjs/gopherjs/js"
Expand Down Expand Up @@ -936,3 +937,41 @@ func TestStructWithNonIdentifierJSTag(t *testing.T) {
t.Errorf("value via js.Object.Get gave %q, want %q", got, want)
}
}

func TestSliceData(t *testing.T) {
var (
s0 = []int(nil)
s1 = []int{}
s2 = []int{1, 2, 3}
s3 = s2[1:]
s4 = []int{4, 5, 6}

sd0 = unsafe.SliceData(s0)
sd1 = unsafe.SliceData(s1)
sd2 = unsafe.SliceData(s2)
sd3 = unsafe.SliceData(s3)
sd4 = unsafe.SliceData(s4)
)

if sd0 != nil {
t.Errorf("slice data for nil slice was not nil")
}
if sd1 == nil {
t.Errorf("slice data for empty slice was nil")
}
if sd2 == nil {
t.Errorf("slice data for non-empty slice was nil")
}
if sd3 == nil {
t.Errorf("slice data for sub-slice was nil")
}
if sd1 == sd2 {
t.Errorf("slice data for empty and non-empty slices were the same")
}
if sd2 == sd3 {
t.Errorf("slice data for slice and sub-slice were the same")
}
if sd2 == sd4 {
t.Errorf("slice data for different slices were the same")
}
}
Loading