Skip to content

File tree

3 files changed

+40
-16
lines changed

3 files changed

+40
-16
lines changed

utils/convert.go

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,13 @@ import (
1313
"unsafe"
1414
)
1515

16-
const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)
17-
1816
// UnsafeString returns a string pointer without allocation
1917
//
2018
//nolint:gosec // unsafe is used for better performance here
2119
func UnsafeString(b []byte) string {
2220
return *(*string)(unsafe.Pointer(&b))
2321
}
2422

25-
// UnsafeBytes returns a byte pointer without allocation.
26-
// String length shouldn't be more than 2147418112.
27-
//
28-
//nolint:gosec // unsafe is used for better performance here
29-
func UnsafeBytes(s string) []byte {
30-
if s == "" {
31-
return nil
32-
}
33-
34-
return (*[MaxStringLen]byte)(unsafe.Pointer(
35-
(*reflect.StringHeader)(unsafe.Pointer(&s)).Data),
36-
)[:len(s):len(s)]
37-
}
38-
3923
// CopyString copies a string to make it immutable
4024
func CopyString(s string) string {
4125
return string(UnsafeBytes(s))

utils/convert_s2b_new.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
//go:build go1.20
2+
// +build go1.20
3+
4+
package utils
5+
6+
import (
7+
"unsafe"
8+
)
9+
10+
// UnsafeBytes returns a byte pointer without allocation.
11+
//
12+
//nolint:gosec // unsafe is used for better performance here
13+
func UnsafeBytes(s string) []byte {
14+
return unsafe.Slice(unsafe.StringData(s), len(s))
15+
}

utils/convert_s2b_old.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//go:build !go1.20
2+
// +build !go1.20
3+
4+
package utils
5+
6+
import (
7+
"reflect"
8+
"unsafe"
9+
)
10+
11+
const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)
12+
13+
// UnsafeBytes returns a byte pointer without allocation.
14+
// String length shouldn't be more than 2147418112.
15+
//
16+
//nolint:gosec // unsafe is used for better performance here
17+
func UnsafeBytes(s string) []byte {
18+
if s == "" {
19+
return nil
20+
}
21+
22+
return (*[MaxStringLen]byte)(unsafe.Pointer(
23+
(*reflect.StringHeader)(unsafe.Pointer(&s)).Data),
24+
)[:len(s):len(s)]
25+
}

0 commit comments

Comments
 (0)