github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/util/string_helper.go (about) 1 // Copyright 2022 iLogtail Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package util 16 17 import ( 18 "reflect" 19 "unsafe" 20 ) 21 22 //nolint:gosec 23 func ZeroCopyBytesToString(b []byte) (s string) { 24 if b == nil { 25 return 26 } 27 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 28 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) 29 pstring.Data = pbytes.Data 30 pstring.Len = pbytes.Len 31 return 32 } 33 34 //nolint:gosec 35 func ZeroCopyStringToBytes(s string) (b []byte) { 36 if s == "" { 37 return 38 } 39 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 40 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) 41 pbytes.Data = pstring.Data 42 pbytes.Len = pstring.Len 43 pbytes.Cap = pstring.Len 44 return 45 } 46 47 func IsSafeString(str1, str2 string) bool { 48 slice1 := ZeroCopyStringToBytes(str1) 49 slice2 := ZeroCopyStringToBytes(str2) 50 isIn := func(bytes1, bytes2 []byte) bool { 51 for i := range bytes2 { 52 if &bytes2[i] == &bytes1[0] || &bytes2[i] == &bytes1[len(bytes1)-1] { 53 return true 54 } 55 } 56 return false 57 } 58 return !isIn(slice1, slice2) && !isIn(slice2, slice1) 59 }