viper-app/pkg/str_util.go
2023-02-03 16:18:31 +08:00

60 lines
2.4 KiB
Go

package pkg
import (
"reflect"
"unsafe"
)
/*
使用 unsafe 的方式转换 bytes string
bench-review
cpu: Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
BenchmarkB2sFast
BenchmarkB2sFast 1000000000 0.2215 ns/op 0 B/op 0 allocs/op
BenchmarkB2sFast-4 1000000000 0.2188 ns/op 0 B/op 0 allocs/op
BenchmarkB2sFast-8 1000000000 0.2187 ns/op 0 B/op 0 allocs/op
BenchmarkB2sFast-16 1000000000 0.2190 ns/op 0 B/op 0 allocs/op
BenchmarkB2sStd
BenchmarkB2sStd 46913166 25.01 ns/op 48 B/op 1 allocs/op
BenchmarkB2sStd-4 53604633 21.23 ns/op 48 B/op 1 allocs/op
BenchmarkB2sStd-8 53374398 21.27 ns/op 48 B/op 1 allocs/op
BenchmarkB2sStd-16 55482764 21.51 ns/op 48 B/op 1 allocs/op
BenchmarkS2BFast
BenchmarkS2BFast 1000000000 0.2187 ns/op 0 B/op 0 allocs/op
BenchmarkS2BFast-4 1000000000 0.2187 ns/op 0 B/op 0 allocs/op
BenchmarkS2BFast-8 1000000000 0.2184 ns/op 0 B/op 0 allocs/op
BenchmarkS2BFast-16 1000000000 0.2188 ns/op 0 B/op 0 allocs/op
BenchmarkS2BStd
BenchmarkS2BStd 56877040 21.31 ns/op 48 B/op 1 allocs/op
BenchmarkS2BStd-4 65751385 17.43 ns/op 48 B/op 1 allocs/op
BenchmarkS2BStd-8 67193628 17.55 ns/op 48 B/op 1 allocs/op
BenchmarkS2BStd-16 66711826 17.61 ns/op 48 B/op 1 allocs/op
*/
// B2S converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func B2S(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}
// S2B converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func S2B(s string) (b []byte) {
/* #nosec G103 */
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
/* #nosec G103 */
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
return b
}