github.com/kelleygo/clashcore@v1.0.2/common/utils/string_unsafe.go (about) 1 package utils 2 3 import "unsafe" 4 5 // ImmutableBytesFromString is equivalent to []byte(s), except that it uses the 6 // same memory backing s instead of making a heap-allocated copy. This is only 7 // valid if the returned slice is never mutated. 8 func ImmutableBytesFromString(s string) []byte { 9 b := unsafe.StringData(s) 10 return unsafe.Slice(b, len(s)) 11 } 12 13 // StringFromImmutableBytes is equivalent to string(bs), except that it uses 14 // the same memory backing bs instead of making a heap-allocated copy. This is 15 // only valid if bs is never mutated after StringFromImmutableBytes returns. 16 func StringFromImmutableBytes(bs []byte) string { 17 if len(bs) == 0 { 18 return "" 19 } 20 return unsafe.String(&bs[0], len(bs)) 21 }