New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add string and bytes buffer convert trick in README #1151
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure if it's useful to mention here. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think some people are wondering how it works, but if people want to know more details, they'll Google it. It's ok to delete. |
||
|
||
Note: | ||
This is an unsafe way, | ||
please make sure not to modify the bytes in the `[]byte` buffer if the result string still survives. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would like to see this warning bigger and bold as it's really important! It's not just a note. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Updated |
||
|
||
## Related projects | ||
|
||
* [fasthttp](https://github.com/fasthttp) - various useful | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.