Skip to content

Commit

Permalink
Add string and bytes buffer convert trick in README (#1151)
Browse files Browse the repository at this point in the history
* Add string and bytes buffer convert trick in README

* Update README.md
  • Loading branch information
ichxxx committed Nov 10, 2021
1 parent 3ff6aaa commit c078a9d
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Expand Up @@ -485,6 +485,27 @@ statusCode, body, err := fasthttp.Get(nil, "http://google.com/")
uintBuf := fasthttp.AppendUint(nil, 1234)
```

* String and `[]byte` buffers may converted without memory allocations
```go
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

func s2b(s string) (b []byte) {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
return b
}
```

### Warning:
This is an **unsafe** way, the result string and `[]byte` buffer share the same bytes.

**Please make sure not to modify the bytes in the `[]byte` buffer if the string still survives!**

## Related projects

* [fasthttp](https://github.com/fasthttp) - various useful
Expand Down

0 comments on commit c078a9d

Please sign in to comment.