Skip to content

Commit 73dc5cc

Browse files
authored
Merge pull request #12 from jf-tech/inplace
add inPlace to ByteUnescape
2 parents bc8b129 + 650e267 commit 73dc5cc

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

strs/strs.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -294,21 +294,32 @@ func Unescape(s, esc string) string {
294294
return sb.String()
295295
}
296296

297-
// ByteUnescape unescapes a []byte sequence with an escape []byte sequence and
298-
// returns a new copy of the unescaped []byte.
299-
func ByteUnescape(b, esc []byte) []byte {
297+
// ByteUnescape unescapes a []byte sequence with an escape []byte sequence.
298+
// If 'inPlace' is true, the unescaping modification is taking place inside
299+
// the original 'b' and 'b' will be returned with length properly adjusted.
300+
// If 'inPlace' is false, the unescaping is taking place inside a new []byte,
301+
// the new []byte will be returned and the original 'b' is untouched.
302+
func ByteUnescape(b, esc []byte, inPlace bool) []byte {
300303
if b == nil {
301304
return nil
302305
}
303-
result := make([]byte, len(b))
306+
result := b
307+
if !inPlace {
308+
result = make([]byte, len(b))
309+
}
304310
count := 0
305311
copyToResult := func(src []byte) {
312+
// because unescaping is strictly shrinking the slice thus
313+
// this copy algo is safe when inPlace is true as well.
306314
for i := 0; i < len(src); i++ {
307315
result[count+i] = src[i]
308316
}
309317
count += len(src)
310318
}
311319
if len(esc) == 0 {
320+
if inPlace {
321+
return b
322+
}
312323
copyToResult(b)
313324
return result[:count]
314325
}

strs/strs_test.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,8 @@ func TestByteUnescape(t *testing.T) {
730730
},
731731
} {
732732
t.Run(test.name, func(t *testing.T) {
733-
assert.Equal(t, test.expected, ByteUnescape(test.input, test.esc))
733+
assert.Equal(t, test.expected, ByteUnescape(test.input, test.esc, false))
734+
assert.Equal(t, test.expected, ByteUnescape(test.input, test.esc, true))
734735
})
735736
}
736737
}
@@ -754,8 +755,9 @@ func BenchmarkUnescape(b *testing.B) {
754755

755756
// BenchmarkByteUnescape-8 500 2482229 ns/op 402211 B/op 1 allocs/op
756757
func BenchmarkByteUnescape(b *testing.B) {
757-
assert.Equal(b, benchmarkUnescapeResultBytes, ByteUnescape(benchmarkUnescapeInputBytes, benchmarkUnescapeDelimBytes))
758+
assert.Equal(b, benchmarkUnescapeResultBytes,
759+
ByteUnescape(benchmarkUnescapeInputBytes, benchmarkUnescapeDelimBytes, false))
758760
for i := 0; i < b.N; i++ {
759-
_ = ByteUnescape(benchmarkUnescapeInputBytes, benchmarkUnescapeDelimBytes)
761+
_ = ByteUnescape(benchmarkUnescapeInputBytes, benchmarkUnescapeDelimBytes, false)
760762
}
761763
}

0 commit comments

Comments
 (0)