From 9f01408ea7bb68684ec709fe1dabafd20254e055 Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Sun, 30 Mar 2025 17:56:44 +0800 Subject: Avoid allocations by using unsafe strinng/bytes conversions --- unsafe.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 unsafe.go (limited to 'unsafe.go') diff --git a/unsafe.go b/unsafe.go new file mode 100644 index 0000000..418a910 --- /dev/null +++ b/unsafe.go @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: BSD-2-Clause +// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu + +package main + +import "unsafe" + +// stringToBytes converts a string to a byte slice without copying the string. +// Memory is borrowed from the string. +// The resulting byte slice must not be modified in any form. +func stringToBytes(s string) (bytes []byte) { + return unsafe.Slice(unsafe.StringData(s), len(s)) +} + +// bytesToString converts a byte slice to a string without copying the bytes. +// Memory is borrowed from the byte slice. +// The source byte slice must not be modified. +func bytesToString(b []byte) string { + return unsafe.String(&b[0], len(b)) +} -- cgit v1.2.3