Skip to content

Commit

Permalink
Use old approach to convert bytes to strings
Browse files Browse the repository at this point in the history
  • Loading branch information
marselester committed May 6, 2023
1 parent cfacdda commit ab0b98d
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 32 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-go@v3
with:
go-version: '1.20'
go-version: 1.19
- uses: golangci/golangci-lint-action@v3
with:
version: v1.50
Expand Down
11 changes: 0 additions & 11 deletions btos_new.go

This file was deleted.

19 changes: 0 additions & 19 deletions btos_old.go

This file was deleted.

14 changes: 13 additions & 1 deletion decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/binary"
"io"
"reflect"
"unsafe"
)

type decoder struct {
Expand Down Expand Up @@ -331,7 +332,7 @@ func newStringConverter(capacity int) *stringConverter {

// stringConverter converts bytes to strings with less allocs.
// The idea is to accumulate bytes in a buffer with specified capacity
// and create strings with unsafe.String using bytes from a buffer.
// and create strings with unsafe package using bytes from a buffer.
// For example, 10 "fizz" strings written to a 40-byte buffer
// will result in 1 alloc instead of 10.
//
Expand Down Expand Up @@ -367,3 +368,14 @@ func (c *stringConverter) String(b []byte) string {
c.offset += n
return s
}

// toString converts a byte slice to a string without allocating.
// Starting from Go 1.20 you should use unsafe.String.
func toString(b []byte) string {
var s string
h := (*reflect.StringHeader)(unsafe.Pointer(&s))
h.Data = uintptr(unsafe.Pointer(&b[0]))
h.Len = len(b)

return s
}

0 comments on commit ab0b98d

Please sign in to comment.