Skip to content

Commit

Permalink
unique: not duplication implement cloneString
Browse files Browse the repository at this point in the history
Change-Id: I3af3bc01be3730172838a2fd4992e9db11cb6f37
  • Loading branch information
qiulaidongfeng committed Apr 28, 2024
1 parent 99ee616 commit f734722
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 23 deletions.
14 changes: 13 additions & 1 deletion src/internal/stringslite/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
// Tests for these functions are in the strings package.
package stringslite

import "internal/bytealg"
import (
"internal/bytealg"
"unsafe"
)

func HasPrefix(s, prefix string) bool {
return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
Expand Down Expand Up @@ -122,3 +125,12 @@ func CutSuffix(s, suffix string) (before string, found bool) {
}
return s[:len(s)-len(suffix)], true
}

func Clone(s string) string {
if len(s) == 0 {
return ""
}
b := make([]byte, len(s))
copy(b, s)
return unsafe.String(&b[0], len(b))
}
11 changes: 2 additions & 9 deletions src/strings/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@

package strings

import (
"unsafe"
)
import "internal/stringslite"

// Clone returns a fresh copy of s.
// It guarantees to make a copy of s into a new allocation,
Expand All @@ -19,10 +17,5 @@ import (
// For strings of length zero the string "" will be returned
// and no allocation is made.
func Clone(s string) string {
if len(s) == 0 {
return ""
}
b := make([]byte, len(s))
copy(b, s)
return unsafe.String(&b[0], len(b))
return stringslite.Clone(s)
}
15 changes: 2 additions & 13 deletions src/unique/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package unique

import (
"internal/abi"
"internal/stringslite"
"unsafe"
)

Expand All @@ -20,7 +21,7 @@ import (
func clone[T comparable](value T, seq *cloneSeq) T {
for _, offset := range seq.stringOffsets {
ps := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(&value)) + offset))
*ps = cloneString(*ps)
*ps = stringslite.Clone(*ps)
}
return value
}
Expand Down Expand Up @@ -86,15 +87,3 @@ func buildArrayCloneSeq(typ *abi.Type, seq *cloneSeq, baseOffset uintptr) {
offset = (offset + align - 1) &^ (align - 1)
}
}

// cloneString is a copy of strings.Clone, because we can't depend on the strings
// package here. Several packages that might make use of unique, like net, explicitly
// forbid depending on unicode, which strings depends on.
func cloneString(s string) string {
if len(s) == 0 {
return ""
}
b := make([]byte, len(s))
copy(b, s)
return unsafe.String(&b[0], len(b))
}

0 comments on commit f734722

Please sign in to comment.