File tree 3 files changed +40
-16
lines changed 3 files changed +40
-16
lines changed Original file line number Diff line number Diff line change @@ -13,29 +13,13 @@ import (
13
13
"unsafe"
14
14
)
15
15
16
- const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112)
17
-
18
16
// UnsafeString returns a string pointer without allocation
19
17
//
20
18
//nolint:gosec // unsafe is used for better performance here
21
19
func UnsafeString (b []byte ) string {
22
20
return * (* string )(unsafe .Pointer (& b ))
23
21
}
24
22
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
-
39
23
// CopyString copies a string to make it immutable
40
24
func CopyString (s string ) string {
41
25
return string (UnsafeBytes (s ))
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments