Skip to content
Myr

Use zero-copy approach to convert types between string and byte… (#2206)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Use zero-copy approach to convert types between string and byte slice * Rename argument to a eligible one Benchmark: BenchmarkBytesConvBytesToStrRaw-4 21003800 70.9 ns/op 96 B/op 1 allocs/op BenchmarkBytesConvBytesToStr-4 1000000000 0.333 ns/op 0 B/op 0 allocs/op BenchmarkBytesConvStrToBytesRaw-4 18478059 59.3 ns/op 96 B/op 1 allocs/op BenchmarkBytesConvStrToBytes-4 1000000000 0.373 ns/op 0 B/op 0 allocs/op

authored by Andy Pan · committed by Bo-Yi Wu · parent ace6e4c · Browse files · 6 files+130 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>

Diff stats

6 files+130 added−10 removed

  • other:+130 added−10 removed

6 files+130 added−10 removed

modified:binding/form_mapping.go+3 added-2 removed
10 unmodified lines
11 "strconv"12 "strings"13 "time"1415 "github.com/gin-gonic/gin/internal/bytesconv"16 "github.com/gin-gonic/gin/internal/json"17)1819var errUnknownType = errors.New("unknown type")
188 unmodified lines
208 switch value.Interface().(type) {209 case time.Time:210 return setTimeField(val, field, value)211 }211 return json.Unmarshal([]byte(val), value.Addr().Interface())212 return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())213 case reflect.Map:213 return json.Unmarshal([]byte(val), value.Addr().Interface())214 return json.Unmarshal(bytesconv.StringToBytes(val), value.Addr().Interface())215 default:216 return errUnknownType217 }218 return nil
133 unmodified lines
added:internal/bytesconv/bytesconv_test.go+95 added
1package bytesconv23import (4 "bytes"5 "math/rand"6 "strings"7 "testing"8 "time"9)1011var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."12var testBytes = []byte(testString)1314func rawBytesToStr(b []byte) string {15 return string(b)16}1718func rawStrToBytes(s string) []byte {19 return []byte(s)20}2122// go test -v2324func TestBytesToString(t *testing.T) {25 data := make([]byte, 1024)26 for i := 0; i < 100; i++ {27 rand.Read(data)28 if rawBytesToStr(data) != BytesToString(data) {29 t.Fatal("don't match")30 }31 }32}3334const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"35const (36 letterIdxBits = 6 // 6 bits to represent a letter index37 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits38 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits39)4041var src = rand.NewSource(time.Now().UnixNano())4243func RandStringBytesMaskImprSrcSB(n int) string {44 sb := strings.Builder{}45 sb.Grow(n)46 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!47 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {48 if remain == 0 {49 cache, remain = src.Int63(), letterIdxMax50 }51 if idx := int(cache & letterIdxMask); idx < len(letterBytes) {52 sb.WriteByte(letterBytes[idx])53 i--54 }55 cache >>= letterIdxBits56 remain--57 }5859 return sb.String()60}6162func TestStringToBytes(t *testing.T) {63 for i := 0; i < 100; i++ {64 s := RandStringBytesMaskImprSrcSB(64)65 if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) {66 t.Fatal("don't match")67 }68 }69}7071// go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true7273func BenchmarkBytesConvBytesToStrRaw(b *testing.B) {74 for i := 0; i < b.N; i++ {75 rawBytesToStr(testBytes)76 }77}7879func BenchmarkBytesConvBytesToStr(b *testing.B) {80 for i := 0; i < b.N; i++ {81 BytesToString(testBytes)82 }83}8485func BenchmarkBytesConvStrToBytesRaw(b *testing.B) {86 for i := 0; i < b.N; i++ {87 rawStrToBytes(testString)88 }89}9091func BenchmarkBytesConvStrToBytes(b *testing.B) {92 for i := 0; i < b.N; i++ {93 StringToBytes(testString)94 }95}
added:internal/bytesconv/bytesconv.go+19 added
1package bytesconv23import (4 "reflect"5 "unsafe"6)78// StringToBytes converts string to byte slice without a memory allocation.9func StringToBytes(s string) (b []byte) {10 sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))11 bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))12 bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len13 return b14}1516// BytesToString converts byte slice to string without a memory allocation.17func BytesToString(b []byte) string {18 return *(*string)(unsafe.Pointer(&b))19}
modified:render/json.go+8 added-6 removed
8 unmodified lines
9 "fmt"10 "html/template"11 "net/http"1213 "github.com/gin-gonic/gin/internal/bytesconv"14 "github.com/gin-gonic/gin/internal/json"15)1617// JSON contains the given interface object.
79 unmodified lines
97 if err != nil {98 return err99 }100 // if the jsonBytes is array values100 if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {101 _, err = w.Write([]byte(r.Prefix))101 if bytes.HasPrefix(jsonBytes, bytesconv.StringToBytes("[")) && bytes.HasSuffix(jsonBytes,102 bytesconv.StringToBytes("]")) {103 _, err = w.Write(bytesconv.StringToBytes(r.Prefix))104 if err != nil {105 return err106 }107 }
19 unmodified lines
127 return err128 }129130 callback := template.JSEscapeString(r.Callback)129 _, err = w.Write([]byte(callback))131 _, err = w.Write(bytesconv.StringToBytes(callback))132 if err != nil {133 return err134 }133 _, err = w.Write([]byte("("))135 _, err = w.Write(bytesconv.StringToBytes("("))136 if err != nil {137 return err138 }139 _, err = w.Write(ret)140 if err != nil {141 return err142 }141 _, err = w.Write([]byte(");"))143 _, err = w.Write(bytesconv.StringToBytes(");"))144 if err != nil {145 return err146 }147
13 unmodified lines
161 return err162 }163164 var buffer bytes.Buffer163 for _, r := range string(ret) {165 for _, r := range bytesconv.BytesToString(ret) {166 cvt := string(r)167 if r >= 128 {168 cvt = fmt.Sprintf("\\u%04x", int64(r))169 }
24 unmodified lines
modified:auth.go+3 added-1 removed
6 unmodified lines
7import (8 "encoding/base64"9 "net/http"10 "strconv"1112 "github.com/gin-gonic/gin/internal/bytesconv"13)1415// AuthUserKey is the cookie name for user credential in basic auth.16const AuthUserKey = "user"
67 unmodified lines
84}8586func authorizationHeader(user, password string) string {87 base := user + ":" + password86 return "Basic " + base64.StdEncoding.EncodeToString([]byte(base))88 return "Basic " + base64.StdEncoding.EncodeToString(bytesconv.StringToBytes(base))89}
modified:gin.go+2 added-1 removed
11 unmodified lines
12 "os"13 "path"14 "sync"1516 "github.com/gin-gonic/gin/internal/bytesconv"17 "github.com/gin-gonic/gin/render"18)1920const defaultMultipartMemory = 32 << 20 // 32 MB
456 unmodified lines
477 req := c.Request478 rPath := req.URL.Path479480 if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok {480 req.URL.Path = string(fixedPath)481 req.URL.Path = bytesconv.BytesToString(fixedPath)482 redirectRequest(c)483 return true484 }485 return false
15 unmodified lines