Use go 1.20 facilities for unsafe string <-> bytes

This commit is contained in:
Kovid Goyal 2023-01-17 12:38:54 +05:30
parent 009fd6418c
commit 750f2fa4d0
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 27 additions and 2 deletions

View File

@ -1,4 +1,5 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build !go1.20
package utils
@ -6,8 +7,6 @@ import (
"unsafe"
)
// TODO: Convert these to use the safer stdlib unsafe functions added in Go 1.20
// stringHeader is the runtime representation of a string.
// It should be identical to reflect.StringHeader
type stringHeader struct {

View File

@ -0,0 +1,26 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
//go:build go1.20
package utils
import (
"fmt"
"unsafe"
)
var _ = fmt.Print
// Unsafely converts s into a byte slice.
// If you modify b, then s will also be modified. This violates the
// property that strings are immutable.
func UnsafeStringToBytes(s string) (b []byte) {
return unsafe.Slice(unsafe.StringData(s), len(s))
}
// Unsafely converts b into a string.
// If you modify b, then s will also be modified. This violates the
// property that strings are immutable.
func UnsafeBytesToString(b []byte) (s string) {
unsafe.String(unsafe.SliceData(b), len(b))
return s
}