all: remove unnecessary copying

Copying []byte to string should copy the data if necessary, as the
Go specification assures that strings are immutable.
This commit is contained in:
Hajime Hoshi 2022-11-11 00:28:45 +09:00
parent 14041c61c0
commit 303965e1a9
3 changed files with 3 additions and 13 deletions

View File

@ -280,13 +280,7 @@ func (s NSString) InitWithUTF8String(utf8 string) NSString {
} }
func (s NSString) String() string { func (s NSString) String() string {
// The lifetime of the underlying C string is shorter than s [1]. return string(unsafe.Slice((*byte)(unsafe.Pointer(s.Send(sel_UTF8String))), s.Send(sel_length)))
// Copy the bytes to ensure that the returned string's lifetime is unrelated to s.
// [1] https://developer.apple.com/documentation/foundation/nsstring/1411189-utf8string?language=objc
src := unsafe.Slice((*byte)(unsafe.Pointer(s.Send(sel_UTF8String))), s.Send(sel_length))
dst := make([]byte, len(src))
copy(dst, src)
return string(dst)
} }
type NSNotification struct { type NSNotification struct {

View File

@ -2293,9 +2293,7 @@ func (i *_ID3DBlob) Release() uint32 {
} }
func (i *_ID3DBlob) String() string { func (i *_ID3DBlob) String() string {
bs := make([]byte, int(i.GetBufferSize())) return string(unsafe.Slice((*byte)(unsafe.Pointer(i.GetBufferPointer())), i.GetBufferSize()))
copy(bs, unsafe.Slice((*byte)(unsafe.Pointer(i.GetBufferPointer())), i.GetBufferSize()))
return string(bs)
} }
type _IDXGIAdapter struct { type _IDXGIAdapter struct {

View File

@ -18,9 +18,7 @@ func GoStr(cstr *byte) string {
x := unsafe.Slice(cstr, 1e9) x := unsafe.Slice(cstr, 1e9)
for i, c := range x { for i, c := range x {
if c == 0 { if c == 0 {
str := make([]byte, i) return string(x[:i])
copy(str, x[:i])
return string(str)
} }
} }
return "" return ""