Skip to content
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

Remove some functions that have the same effect as the bytes package #2387

Merged
merged 1 commit into from
May 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Remove some functions that have the same effect as the bytes package
  • Loading branch information
bestgopher committed May 23, 2020
commit 411f58e44651625a062014b577d0858114bd0aea
42 changes: 9 additions & 33 deletions tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ package gin
import (
"bytes"
"net/url"
"reflect"
"strings"
"unicode"
"unicode/utf8"
"unsafe"

"github.com/gin-gonic/gin/internal/bytesconv"
)

var (
Expand Down Expand Up @@ -80,36 +80,12 @@ func longestCommonPrefix(a, b string) int {
return i
}

// bytesToStr converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func bytesToStr(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

// strToBytes converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func strToBytes(s string) (b []byte) {
/* #nosec G103 */
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
/* #nosec G103 */
sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return b
}

func countParams(path string) uint16 {
var n uint
s := strToBytes(path)
n += uint(bytes.Count(s, strColon))
n += uint(bytes.Count(s, strStar))
return uint16(n)
var n uint16
s := bytesconv.StringToBytes(path)
n += uint16(bytes.Count(s, strColon))
n += uint16(bytes.Count(s, strStar))
return n
}

type nodeType uint8
Expand Down Expand Up @@ -192,7 +168,7 @@ walk:

n.children = []*node{&child}
// []byte for proper unicode char conversion, see #65
n.indices = bytesToStr([]byte{n.path[i]})
n.indices = bytesconv.BytesToString([]byte{n.path[i]})
n.path = path[:i]
n.handlers = nil
n.wildChild = false
Expand Down Expand Up @@ -252,7 +228,7 @@ walk:
// Otherwise insert it
if c != ':' && c != '*' {
// []byte for proper unicode char conversion, see #65
n.indices += bytesToStr([]byte{c})
n.indices += bytesconv.BytesToString([]byte{c})
child := &node{
fullPath: fullPath,
}
Expand Down