Use go 1.20 facilities for unsafe string <-> bytes
This commit is contained in:
parent
009fd6418c
commit
750f2fa4d0
@ -1,4 +1,5 @@
|
|||||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||||
|
//go:build !go1.20
|
||||||
|
|
||||||
package utils
|
package utils
|
||||||
|
|
||||||
@ -6,8 +7,6 @@ import (
|
|||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: Convert these to use the safer stdlib unsafe functions added in Go 1.20
|
|
||||||
|
|
||||||
// stringHeader is the runtime representation of a string.
|
// stringHeader is the runtime representation of a string.
|
||||||
// It should be identical to reflect.StringHeader
|
// It should be identical to reflect.StringHeader
|
||||||
type stringHeader struct {
|
type stringHeader struct {
|
||||||
|
|||||||
26
tools/utils/unsafeutil_modern.go
Normal file
26
tools/utils/unsafeutil_modern.go
Normal 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
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user