From a28c7ebcf1adeccd1830c4fccc0aaf0b768aae5d Mon Sep 17 00:00:00 2001 From: xfy Date: Fri, 8 May 2026 18:06:25 +0800 Subject: [PATCH] refactor(utils): add unified b2s/s2b conversion functions Extract duplicate b2s/s2b functions from proxy/utils.go into internal/utils/bytes.go. These are zero-allocation unsafe conversions for byte slice <-> string conversion. - Create utils.B2s() and utils.S2b() as unified implementations - Update proxy/utils.go to call utils functions - Add safety documentation about shared memory warning Co-Authored-By: Claude Opus 4.7 --- internal/proxy/utils.go | 13 ++++--------- internal/utils/bytes.go | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 9 deletions(-) create mode 100644 internal/utils/bytes.go diff --git a/internal/proxy/utils.go b/internal/proxy/utils.go index b995f7d..b75de49 100644 --- a/internal/proxy/utils.go +++ b/internal/proxy/utils.go @@ -2,27 +2,22 @@ package proxy import ( "bytes" - "unsafe" + + "rua.plus/lolly/internal/utils" ) // b2s converts byte slice to string without allocation. // WARNING: The returned string shares memory with the original slice. // Do not modify the slice after calling this function. func b2s(b []byte) string { - if len(b) == 0 { - return "" - } - return unsafe.String(&b[0], len(b)) + return utils.B2s(b) } // s2b converts string to byte slice without allocation. // WARNING: The returned slice shares memory with the original string. // Do not modify the slice contents. func s2b(s string) []byte { - if s == "" { - return nil - } - return unsafe.Slice(unsafe.StringData(s), len(s)) + return utils.S2b(s) } // isInWhitelist checks if a header key is in the whitelist. diff --git a/internal/utils/bytes.go b/internal/utils/bytes.go new file mode 100644 index 0000000..1741fea --- /dev/null +++ b/internal/utils/bytes.go @@ -0,0 +1,23 @@ +package utils + +import "unsafe" + +// B2s converts byte slice to string without allocation. +// WARNING: The returned string shares memory with the original slice. +// Do not modify the slice after calling this function. +func B2s(b []byte) string { + if len(b) == 0 { + return "" + } + return unsafe.String(&b[0], len(b)) +} + +// S2b converts string to byte slice without allocation. +// WARNING: The returned slice shares memory with the original string. +// Do not modify the slice contents. +func S2b(s string) []byte { + if s == "" { + return nil + } + return unsafe.Slice(unsafe.StringData(s), len(s)) +}