From 750f2fa4d0f22d0953bbed21967129b732c1ea14 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 17 Jan 2023 12:38:54 +0530 Subject: [PATCH] Use go 1.20 facilities for unsafe string <-> bytes --- tools/utils/unsafeutil.go | 3 +-- tools/utils/unsafeutil_modern.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 tools/utils/unsafeutil_modern.go diff --git a/tools/utils/unsafeutil.go b/tools/utils/unsafeutil.go index 5c741a040..9ed6d1859 100644 --- a/tools/utils/unsafeutil.go +++ b/tools/utils/unsafeutil.go @@ -1,4 +1,5 @@ // License: GPLv3 Copyright: 2022, Kovid Goyal, +//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 { diff --git a/tools/utils/unsafeutil_modern.go b/tools/utils/unsafeutil_modern.go new file mode 100644 index 000000000..deb3de525 --- /dev/null +++ b/tools/utils/unsafeutil_modern.go @@ -0,0 +1,26 @@ +// License: GPLv3 Copyright: 2023, Kovid Goyal, +//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 +}