bytesconv_test.go
This file
Path
internal/bytesconv/bytesconv_test.go
99 lines · 2.2 KiB · Go
Last changed by
Not known.
History of this fileTake it
1// Copyright 2020 Gin Core Team. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package bytesconv67import (8 "bytes"9 "math/rand"10 "strings"11 "testing"12 "time"13)1415var testString = "Albert Einstein: Logic will get you from A to B. Imagination will take you everywhere."16var testBytes = []byte(testString)1718func rawBytesToStr(b []byte) string {19 return string(b)20}2122func rawStrToBytes(s string) []byte {23 return []byte(s)24}2526// go test -v2728func TestBytesToString(t *testing.T) {29 data := make([]byte, 1024)30 for i := 0; i < 100; i++ {31 rand.Read(data)32 if rawBytesToStr(data) != BytesToString(data) {33 t.Fatal("don't match")34 }35 }36}3738const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"39const (40 letterIdxBits = 6 // 6 bits to represent a letter index41 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits42 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits43)4445var src = rand.NewSource(time.Now().UnixNano())4647func RandStringBytesMaskImprSrcSB(n int) string {48 sb := strings.Builder{}49 sb.Grow(n)50 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters!51 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {52 if remain == 0 {53 cache, remain = src.Int63(), letterIdxMax54 }55 if idx := int(cache & letterIdxMask); idx < len(letterBytes) {56 sb.WriteByte(letterBytes[idx])57 i--58 }59 cache >>= letterIdxBits60 remain--61 }6263 return sb.String()64}6566func TestStringToBytes(t *testing.T) {67 for i := 0; i < 100; i++ {68 s := RandStringBytesMaskImprSrcSB(64)69 if !bytes.Equal(rawStrToBytes(s), StringToBytes(s)) {70 t.Fatal("don't match")71 }72 }73}7475// go test -v -run=none -bench=^BenchmarkBytesConv -benchmem=true7677func BenchmarkBytesConvBytesToStrRaw(b *testing.B) {78 for i := 0; i < b.N; i++ {79 rawBytesToStr(testBytes)80 }81}8283func BenchmarkBytesConvBytesToStr(b *testing.B) {84 for i := 0; i < b.N; i++ {85 BytesToString(testBytes)86 }87}8889func BenchmarkBytesConvStrToBytesRaw(b *testing.B) {90 for i := 0; i < b.N; i++ {91 rawStrToBytes(testString)92 }93}9495func BenchmarkBytesConvStrToBytes(b *testing.B) {96 for i := 0; i < b.N; i++ {97 StringToBytes(testString)98 }99}