Skip to content
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

reflect.SliceHeader uses uintptr for Len and Cap instead of int #3093

Closed
dgryski opened this issue Aug 24, 2022 · 5 comments
Closed

reflect.SliceHeader uses uintptr for Len and Cap instead of int #3093

dgryski opened this issue Aug 24, 2022 · 5 comments

Comments

@dgryski
Copy link
Member

dgryski commented Aug 24, 2022

https://github.com/golang/go/blob/master/src/reflect/value.go#L2695

vs

https://github.com/tinygo-org/tinygo/blob/release/src/reflect/value.go#L773

This causes a build failure for https://github.com/goccy/go-json

internal/encoder/string.go:20:9: cannot use len(s) / 8 (value of type int) as uintptr value in struct literal
@aykevl
Copy link
Member

aykevl commented Aug 24, 2022

Please take a look here: #1284

I believe this is a duplicate, and there is nothing to fix.

@dgryski
Copy link
Member Author

dgryski commented Aug 24, 2022

Closing. I'll try to come up with a patch for goccy/go-json to make it work on both implementations.

@dgryski dgryski closed this as completed Aug 24, 2022
@dgryski
Copy link
Member Author

dgryski commented Aug 24, 2022

 func stringToUint64Slice(s string) []uint64 {
-       return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{
-               Data: ((*reflect.StringHeader)(unsafe.Pointer(&s))).Data,
-               Len:  len(s) / 8,
-               Cap:  len(s) / 8,
-       }))
+       hdr := *(*reflect.StringHeader)(unsafe.Pointer(&s))
+       return unsafe.Slice((*uint64)(unsafe.Pointer(hdr.Data)), len(s)/8)
 }

@twmb
Copy link

twmb commented Aug 31, 2022

The one change I would make to the prior comment is

- hdr := *(*reflect.StringHeader)(unsafe.Pointer(&s))
+ hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))

@aykevl
Copy link
Member

aykevl commented Aug 31, 2022

Just so you know: casting to []uint64 can result in unaligned accesses. This can lead to problems on most architectures (including amd64!).
Also, writing to a []uint64 that used to be a string is very much undefined behavior, but I guess you already knew that ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants