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
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
Provenance
- Commit
982daeb- Tree
2544df1- Author
Andy Pan <panjf2000@gmail.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
ace6e4c
6 files changed+130 added−10 removed
modified:binding/form_mapping.go+3 added-2 removed
10 unmodified lines11 "strconv"12 "strings"13 "time"14 15+ "github.com/gin-gonic/gin/internal/bytesconv"16 "github.com/gin-gonic/gin/internal/json"17 )18 19 var errUnknownType = errors.New("unknown type")188 unmodified lines208 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 nil133 unmodified linesadded:internal/bytesconv/bytesconv_test.go+95 added
1+package bytesconv2+3+import (4+ "bytes"5+ "math/rand"6+ "strings"7+ "testing"8+ "time"9+)10+11+var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."12+var testBytes = []byte(testString)13+14+func rawBytesToStr(b []byte) string {15+ return string(b)16+}17+18+func rawStrToBytes(s string) []byte {19+ return []byte(s)20+}21+22+// go test -v23+24+func 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+}33+34+const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"35+const (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+)40+41+var src = rand.NewSource(time.Now().UnixNano())42+43+func 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+ }58+59+ return sb.String()60+}61+62+func 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+}70+71+// go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true72+73+func BenchmarkBytesConvBytesToStrRaw(b *testing.B) {74+ for i := 0; i < b.N; i++ {75+ rawBytesToStr(testBytes)76+ }77+}78+79+func BenchmarkBytesConvBytesToStr(b *testing.B) {80+ for i := 0; i < b.N; i++ {81+ BytesToString(testBytes)82+ }83+}84+85+func BenchmarkBytesConvStrToBytesRaw(b *testing.B) {86+ for i := 0; i < b.N; i++ {87+ rawStrToBytes(testString)88+ }89+}90+91+func BenchmarkBytesConvStrToBytes(b *testing.B) {92+ for i := 0; i < b.N; i++ {93+ StringToBytes(testString)94+ }95+}added:internal/bytesconv/bytesconv.go+19 added
1+package bytesconv2+3+import (4+ "reflect"5+ "unsafe"6+)7+8+// StringToBytes converts string to byte slice without a memory allocation.9+func 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+}15+16+// BytesToString converts byte slice to string without a memory allocation.17+func BytesToString(b []byte) string {18+ return *(*string)(unsafe.Pointer(&b))19+}modified:render/json.go+8 added-6 removed
8 unmodified lines9 "fmt"10 "html/template"11 "net/http"12 13+ "github.com/gin-gonic/gin/internal/bytesconv"14 "github.com/gin-gonic/gin/internal/json"15 )16 17 // JSON contains the given interface object.79 unmodified lines97 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 lines127 return err128 }129 130 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 lines161 return err162 }163 164 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 linesmodified:auth.go+3 added-1 removed
6 unmodified lines7 import (8 "encoding/base64"9 "net/http"10 "strconv"11+12+ "github.com/gin-gonic/gin/internal/bytesconv"13 )14 15 // AuthUserKey is the cookie name for user credential in basic auth.16 const AuthUserKey = "user"67 unmodified lines84 }85 86 func 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 lines12 "os"13 "path"14 "sync"15 16+ "github.com/gin-gonic/gin/internal/bytesconv"17 "github.com/gin-gonic/gin/render"18 )19 20 const defaultMultipartMemory = 32 << 20 // 32 MB456 unmodified lines477 req := c.Request478 rPath := req.URL.Path479 480 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 false15 unmodified lines