Skip to content

Commit b8d69af

Browse files
committed
stdlib: unsafe zero copy
Fixes golang-design#7
1 parent f51fde5 commit b8d69af

File tree

1 file changed

+4
-20
lines changed

1 file changed

+4
-20
lines changed

标准库/unsafe/如何实现字符串和byte切片的零拷贝转换.md

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,15 @@ type SliceHeader struct {
1515
}
1616
```
1717

18-
上面是反射包下的结构体,路径:src/reflect/value.go。只需要共享底层 []byte 数组就可以实现 `zero-copy`
18+
上面是反射包下的结构体,路径:src/reflect/value.go。只需要共享底层 Data 和 Len 就可以实现 `zero-copy`
1919

2020
```golang
2121
func string2bytes(s string) []byte {
22-
stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
23-
24-
bh := reflect.SliceHeader{
25-
Data: stringHeader.Data,
26-
Len: stringHeader.Len,
27-
Cap: stringHeader.Len,
28-
}
29-
30-
return *(*[]byte)(unsafe.Pointer(&bh))
22+
return *(*[]byte)(unsafe.Pointer(&s))
3123
}
32-
3324
func bytes2string(b []byte) string{
34-
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
35-
36-
sh := reflect.StringHeader{
37-
Data: sliceHeader.Data,
38-
Len: sliceHeader.Len,
39-
}
40-
41-
return *(*string)(unsafe.Pointer(&sh))
25+
return *(*string)(unsafe.Pointer(&b))
4226
}
4327
```
4428

45-
代码比较简单,不作详细解释。通过构造 slice header 和 string header,来完成 string 和 byte slice 之间的转换
29+
原理上是利用指针的强转,代码比较简单,不作详细解释。

0 commit comments

Comments
 (0)