From 6bc120d7c0e85f578a38d9d7947d16363c66facd Mon Sep 17 00:00:00 2001 From: ichxxx Date: Tue, 9 Nov 2021 17:20:07 +0800 Subject: [PATCH 1/2] Add string and bytes buffer convert trick in README --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index 59d0dd0bbf..57fb5ff536 100644 --- a/README.md +++ b/README.md @@ -485,6 +485,28 @@ statusCode, body, err := fasthttp.Get(nil, "http://google.com/") uintBuf := fasthttp.AppendUint(nil, 1234) ``` +* String and `[]byte` buffer may converts wihtout memory allocation +```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 +} +``` +The underlying structure of `[]byte` buffer has only one `Len` field more than String. +So, we can construct one directly from the other. + +Note: +This is an unsafe way, +please make sure not to modify the bytes in the `[]byte` buffer if the result string still survives. + ## Related projects * [fasthttp](https://github.com/fasthttp) - various useful From 2662b742ebe412ec607b9db9aea8be336dbbae04 Mon Sep 17 00:00:00 2001 From: ichxxx Date: Wed, 10 Nov 2021 11:07:00 +0800 Subject: [PATCH 2/2] Update README.md --- README.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 57fb5ff536..c11d9cef14 100644 --- a/README.md +++ b/README.md @@ -485,7 +485,7 @@ statusCode, body, err := fasthttp.Get(nil, "http://google.com/") uintBuf := fasthttp.AppendUint(nil, 1234) ``` -* String and `[]byte` buffer may converts wihtout memory allocation +* String and `[]byte` buffers may converted without memory allocations ```go func b2s(b []byte) string { return *(*string)(unsafe.Pointer(&b)) @@ -500,12 +500,11 @@ func s2b(s string) (b []byte) { return b } ``` -The underlying structure of `[]byte` buffer has only one `Len` field more than String. -So, we can construct one directly from the other. -Note: -This is an unsafe way, -please make sure not to modify the bytes in the `[]byte` buffer if the result string still survives. +### 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