From c078a9d550cd904dd709aac600fe3cf479d99e16 Mon Sep 17 00:00:00 2001 From: ichx Date: Thu, 11 Nov 2021 05:14:55 +0800 Subject: [PATCH] Add string and bytes buffer convert trick in README (#1151) * Add string and bytes buffer convert trick in README * Update README.md --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 59d0dd0bbf..c11d9cef14 100644 --- a/README.md +++ b/README.md @@ -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