github.com/cloudwego/kitex@v0.9.0/pkg/utils/strings.go (about) 1 /* 2 * Copyright 2023 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "strings" 21 "sync" 22 "unsafe" 23 ) 24 25 func StringDeepCopy(s string) string { 26 buf := []byte(s) 27 ns := (*string)(unsafe.Pointer(&buf)) 28 return *ns 29 } 30 31 // StringBuilder is a concurrently safe wrapper for strings.Builder. 32 type StringBuilder struct { 33 sync.Mutex 34 sb strings.Builder 35 } 36 37 // WithLocked encapsulates a concurrent-safe interface for batch operations on strings.Builder. 38 // Please note that you should avoid calling member functions of StringBuilder within the input 39 // function, as it may lead to program deadlock. 40 func (b *StringBuilder) WithLocked(f func(sb *strings.Builder) error) error { 41 b.Lock() 42 defer b.Unlock() 43 return f(&b.sb) 44 } 45 46 // RawStringBuilder returns the inner strings.Builder of StringBuilder. It allows users to perform 47 // lock-free operations in scenarios without concurrency issues, thereby improving performance. 48 func (b *StringBuilder) RawStringBuilder() *strings.Builder { 49 return &b.sb 50 } 51 52 func (b *StringBuilder) String() string { 53 b.Lock() 54 defer b.Unlock() 55 return b.sb.String() 56 } 57 58 func (b *StringBuilder) Len() int { 59 b.Lock() 60 defer b.Unlock() 61 return b.sb.Len() 62 } 63 64 func (b *StringBuilder) Cap() int { 65 b.Lock() 66 defer b.Unlock() 67 return b.sb.Cap() 68 } 69 70 func (b *StringBuilder) Reset() { 71 b.Lock() 72 defer b.Unlock() 73 b.sb.Reset() 74 } 75 76 func (b *StringBuilder) Grow(n int) { 77 b.Lock() 78 defer b.Unlock() 79 b.sb.Grow(n) 80 } 81 82 func (b *StringBuilder) Write(p []byte) (int, error) { 83 b.Lock() 84 defer b.Unlock() 85 return b.sb.Write(p) 86 } 87 88 func (b *StringBuilder) WriteByte(c byte) error { 89 b.Lock() 90 defer b.Unlock() 91 return b.sb.WriteByte(c) 92 } 93 94 func (b *StringBuilder) WriteRune(r rune) (int, error) { 95 b.Lock() 96 defer b.Unlock() 97 return b.sb.WriteRune(r) 98 } 99 100 func (b *StringBuilder) WriteString(s string) (int, error) { 101 b.Lock() 102 defer b.Unlock() 103 return b.sb.WriteString(s) 104 }