mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
fix: Fixed the issue of missing cap when StringToBytes returns result (#306)
Co-authored-by: 燕归来 <dylan@infinni.io>
This commit is contained in:
@@ -396,7 +396,10 @@ func RemoveNonPrintable(str string) string {
|
|||||||
// StringToBytes converts a string to byte slice without a memory allocation.
|
// StringToBytes converts a string to byte slice without a memory allocation.
|
||||||
// Play: https://go.dev/play/p/7OyFBrf9AxA
|
// Play: https://go.dev/play/p/7OyFBrf9AxA
|
||||||
func StringToBytes(str string) (b []byte) {
|
func StringToBytes(str string) (b []byte) {
|
||||||
return *(*[]byte)(unsafe.Pointer(&str))
|
return *(*[]byte)(unsafe.Pointer(&struct {
|
||||||
|
string
|
||||||
|
Cap int
|
||||||
|
}{str, len(str)}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// BytesToString converts a byte slice to string without a memory allocation.
|
// BytesToString converts a byte slice to string without a memory allocation.
|
||||||
|
|||||||
@@ -518,7 +518,8 @@ func TestStringToBytes(t *testing.T) {
|
|||||||
assert := internal.NewAssert(t, "TestStringToBytes")
|
assert := internal.NewAssert(t, "TestStringToBytes")
|
||||||
|
|
||||||
bytes := StringToBytes("abc")
|
bytes := StringToBytes("abc")
|
||||||
assert.Equal(bytes, []byte{'a', 'b', 'c'})
|
assert.Equal([]byte{'a', 'b', 'c'}, bytes)
|
||||||
|
assert.Equal(3, cap(bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestBytesToString(t *testing.T) {
|
func TestBytesToString(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user