mirror of
https://github.com/gofiber/fiber.git
synced 2025-02-19 13:47:54 +00:00
Merge pull request #774 from Fenny/master
👂 uncomment internal benchmarks
This commit is contained in:
commit
b96cbff310
2
app.go
2
app.go
@ -25,7 +25,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/colorable"
|
||||
"github.com/gofiber/fiber/v2/internal/isatty"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
@ -20,7 +20,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
"github.com/valyala/fasthttp/fasthttputil"
|
||||
)
|
||||
|
2
ctx.go
2
ctx.go
@ -22,7 +22,7 @@ import (
|
||||
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
||||
"github.com/gofiber/fiber/v2/internal/encoding/json"
|
||||
"github.com/gofiber/fiber/v2/internal/schema"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -25,7 +25,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
3
go.mod
3
go.mod
@ -3,6 +3,7 @@ module github.com/gofiber/fiber/v2
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.11.0 // indirect
|
||||
github.com/valyala/fasthttp v1.16.0
|
||||
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980
|
||||
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009
|
||||
)
|
||||
|
5
go.sum
5
go.sum
@ -1,8 +1,9 @@
|
||||
github.com/andybalholm/brotli v1.0.0 h1:7UCwP93aiSfvWpapti8g88vVVGp2qqtGyePsSuDafo4=
|
||||
github.com/andybalholm/brotli v1.0.0/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
|
||||
github.com/gofiber/fiber v1.14.6 h1:QRUPvPmr8ijQuGo1MgupHBn8E+wW0IKqiOvIZPtV70o=
|
||||
github.com/klauspost/compress v1.10.7 h1:7rix8v8GpI3ZBb0nSozFRgbtXKv+hOe+qfEpZqybrAg=
|
||||
github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
github.com/klauspost/compress v1.11.0 h1:wJbzvpYMVGG9iTI9VxpnNZfd4DzMPoCWze3GgSqz8yg=
|
||||
github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.16.0 h1:9zAqOYLl8Tuy3E5R6ckzGDJ1g8+pw15oQp2iL9Jl6gQ=
|
||||
@ -18,5 +19,7 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20u
|
||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y=
|
||||
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009 h1:W0lCpv29Hv0UaM1LXb9QlBHLNP8UFfcKjblhVCWftOM=
|
||||
golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
@ -19,7 +19,7 @@ import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -9,7 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -1,32 +1,27 @@
|
||||
package bytebufferpool
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
// func BenchmarkByteBufferWrite(b *testing.B) {
|
||||
// s := []byte("foobarbaz")
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var buf ByteBuffer
|
||||
// for pb.Next() {
|
||||
// for i := 0; i < 100; i++ {
|
||||
// buf.Write(s)
|
||||
// }
|
||||
// buf.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkByteBufferWrite(b *testing.B) {
|
||||
s := []byte("foobarbaz")
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var buf ByteBuffer
|
||||
for pb.Next() {
|
||||
for i := 0; i < 100; i++ {
|
||||
buf.Write(s)
|
||||
}
|
||||
buf.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkBytesBufferWrite(b *testing.B) {
|
||||
s := []byte("foobarbaz")
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var buf bytes.Buffer
|
||||
for pb.Next() {
|
||||
for i := 0; i < 100; i++ {
|
||||
buf.Write(s)
|
||||
}
|
||||
buf.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkBytesBufferWrite(b *testing.B) {
|
||||
// s := []byte("foobarbaz")
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var buf bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// for i := 0; i < 100; i++ {
|
||||
// buf.Write(s)
|
||||
// }
|
||||
// buf.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
@ -13,14 +13,8 @@ package json
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type codeResponse struct {
|
||||
@ -80,295 +74,295 @@ func codeInit() {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCodeEncoder(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
if codeJSON == nil {
|
||||
b.StopTimer()
|
||||
codeInit()
|
||||
b.StartTimer()
|
||||
}
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
enc := NewEncoder(ioutil.Discard)
|
||||
for pb.Next() {
|
||||
if err := enc.Encode(&codeStruct); err != nil {
|
||||
b.Fatal("Encode:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.SetBytes(int64(len(codeJSON)))
|
||||
}
|
||||
// func BenchmarkCodeEncoder(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// if codeJSON == nil {
|
||||
// b.StopTimer()
|
||||
// codeInit()
|
||||
// b.StartTimer()
|
||||
// }
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// enc := NewEncoder(ioutil.Discard)
|
||||
// for pb.Next() {
|
||||
// if err := enc.Encode(&codeStruct); err != nil {
|
||||
// b.Fatal("Encode:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// b.SetBytes(int64(len(codeJSON)))
|
||||
// }
|
||||
|
||||
func BenchmarkCodeMarshal(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
if codeJSON == nil {
|
||||
b.StopTimer()
|
||||
codeInit()
|
||||
b.StartTimer()
|
||||
}
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
if _, err := Marshal(&codeStruct); err != nil {
|
||||
b.Fatal("Marshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.SetBytes(int64(len(codeJSON)))
|
||||
}
|
||||
// func BenchmarkCodeMarshal(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// if codeJSON == nil {
|
||||
// b.StopTimer()
|
||||
// codeInit()
|
||||
// b.StartTimer()
|
||||
// }
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// if _, err := Marshal(&codeStruct); err != nil {
|
||||
// b.Fatal("Marshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// b.SetBytes(int64(len(codeJSON)))
|
||||
// }
|
||||
|
||||
func benchMarshalBytes(n int) func(*testing.B) {
|
||||
sample := []byte("hello world")
|
||||
// Use a struct pointer, to avoid an allocation when passing it as an
|
||||
// interface parameter to Marshal.
|
||||
v := &struct {
|
||||
Bytes []byte
|
||||
}{
|
||||
bytes.Repeat(sample, (n/len(sample))+1)[:n],
|
||||
}
|
||||
return func(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
if _, err := Marshal(v); err != nil {
|
||||
b.Fatal("Marshal:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// func benchMarshalBytes(n int) func(*testing.B) {
|
||||
// sample := []byte("hello world")
|
||||
// // Use a struct pointer, to avoid an allocation when passing it as an
|
||||
// // interface parameter to Marshal.
|
||||
// v := &struct {
|
||||
// Bytes []byte
|
||||
// }{
|
||||
// bytes.Repeat(sample, (n/len(sample))+1)[:n],
|
||||
// }
|
||||
// return func(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if _, err := Marshal(v); err != nil {
|
||||
// b.Fatal("Marshal:", err)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkMarshalBytes(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
// 32 fits within encodeState.scratch.
|
||||
b.Run("32", benchMarshalBytes(32))
|
||||
// 256 doesn't fit in encodeState.scratch, but is small enough to
|
||||
// allocate and avoid the slower base64.NewEncoder.
|
||||
b.Run("256", benchMarshalBytes(256))
|
||||
// 4096 is large enough that we want to avoid allocating for it.
|
||||
b.Run("4096", benchMarshalBytes(4096))
|
||||
}
|
||||
// func BenchmarkMarshalBytes(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// // 32 fits within encodeState.scratch.
|
||||
// b.Run("32", benchMarshalBytes(32))
|
||||
// // 256 doesn't fit in encodeState.scratch, but is small enough to
|
||||
// // allocate and avoid the slower base64.NewEncoder.
|
||||
// b.Run("256", benchMarshalBytes(256))
|
||||
// // 4096 is large enough that we want to avoid allocating for it.
|
||||
// b.Run("4096", benchMarshalBytes(4096))
|
||||
// }
|
||||
|
||||
func BenchmarkCodeDecoder(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
if codeJSON == nil {
|
||||
b.StopTimer()
|
||||
codeInit()
|
||||
b.StartTimer()
|
||||
}
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var buf bytes.Buffer
|
||||
dec := NewDecoder(&buf)
|
||||
var r codeResponse
|
||||
for pb.Next() {
|
||||
buf.Write(codeJSON)
|
||||
// hide EOF
|
||||
buf.WriteByte('\n')
|
||||
buf.WriteByte('\n')
|
||||
buf.WriteByte('\n')
|
||||
if err := dec.Decode(&r); err != nil {
|
||||
b.Fatal("Decode:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.SetBytes(int64(len(codeJSON)))
|
||||
}
|
||||
// func BenchmarkCodeDecoder(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// if codeJSON == nil {
|
||||
// b.StopTimer()
|
||||
// codeInit()
|
||||
// b.StartTimer()
|
||||
// }
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var buf bytes.Buffer
|
||||
// dec := NewDecoder(&buf)
|
||||
// var r codeResponse
|
||||
// for pb.Next() {
|
||||
// buf.Write(codeJSON)
|
||||
// // hide EOF
|
||||
// buf.WriteByte('\n')
|
||||
// buf.WriteByte('\n')
|
||||
// buf.WriteByte('\n')
|
||||
// if err := dec.Decode(&r); err != nil {
|
||||
// b.Fatal("Decode:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// b.SetBytes(int64(len(codeJSON)))
|
||||
// }
|
||||
|
||||
func BenchmarkUnicodeDecoder(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
j := []byte(`"\uD83D\uDE01"`)
|
||||
b.SetBytes(int64(len(j)))
|
||||
r := bytes.NewReader(j)
|
||||
dec := NewDecoder(r)
|
||||
var out string
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := dec.Decode(&out); err != nil {
|
||||
b.Fatal("Decode:", err)
|
||||
}
|
||||
r.Seek(0, 0)
|
||||
}
|
||||
}
|
||||
// func BenchmarkUnicodeDecoder(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// j := []byte(`"\uD83D\uDE01"`)
|
||||
// b.SetBytes(int64(len(j)))
|
||||
// r := bytes.NewReader(j)
|
||||
// dec := NewDecoder(r)
|
||||
// var out string
|
||||
// b.ResetTimer()
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if err := dec.Decode(&out); err != nil {
|
||||
// b.Fatal("Decode:", err)
|
||||
// }
|
||||
// r.Seek(0, 0)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkDecoderStream(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
b.StopTimer()
|
||||
var buf bytes.Buffer
|
||||
dec := NewDecoder(&buf)
|
||||
buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
|
||||
var x interface{}
|
||||
if err := dec.Decode(&x); err != nil {
|
||||
b.Fatal("Decode:", err)
|
||||
}
|
||||
ones := strings.Repeat(" 1\n", 300000) + "\n\n\n"
|
||||
b.StartTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if i%300000 == 0 {
|
||||
buf.WriteString(ones)
|
||||
}
|
||||
x = nil
|
||||
if err := dec.Decode(&x); err != nil || x != 1.0 {
|
||||
b.Fatalf("Decode: %v after %d", err, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
// func BenchmarkDecoderStream(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// b.StopTimer()
|
||||
// var buf bytes.Buffer
|
||||
// dec := NewDecoder(&buf)
|
||||
// buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n")
|
||||
// var x interface{}
|
||||
// if err := dec.Decode(&x); err != nil {
|
||||
// b.Fatal("Decode:", err)
|
||||
// }
|
||||
// ones := strings.Repeat(" 1\n", 300000) + "\n\n\n"
|
||||
// b.StartTimer()
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if i%300000 == 0 {
|
||||
// buf.WriteString(ones)
|
||||
// }
|
||||
// x = nil
|
||||
// if err := dec.Decode(&x); err != nil || x != 1.0 {
|
||||
// b.Fatalf("Decode: %v after %d", err, i)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkCodeUnmarshal(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
if codeJSON == nil {
|
||||
b.StopTimer()
|
||||
codeInit()
|
||||
b.StartTimer()
|
||||
}
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
var r codeResponse
|
||||
if err := Unmarshal(codeJSON, &r); err != nil {
|
||||
b.Fatal("Unmarshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.SetBytes(int64(len(codeJSON)))
|
||||
}
|
||||
// func BenchmarkCodeUnmarshal(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// if codeJSON == nil {
|
||||
// b.StopTimer()
|
||||
// codeInit()
|
||||
// b.StartTimer()
|
||||
// }
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// var r codeResponse
|
||||
// if err := Unmarshal(codeJSON, &r); err != nil {
|
||||
// b.Fatal("Unmarshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// b.SetBytes(int64(len(codeJSON)))
|
||||
// }
|
||||
|
||||
func BenchmarkCodeUnmarshalReuse(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
if codeJSON == nil {
|
||||
b.StopTimer()
|
||||
codeInit()
|
||||
b.StartTimer()
|
||||
}
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var r codeResponse
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(codeJSON, &r); err != nil {
|
||||
b.Fatal("Unmarshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
b.SetBytes(int64(len(codeJSON)))
|
||||
}
|
||||
// func BenchmarkCodeUnmarshalReuse(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// if codeJSON == nil {
|
||||
// b.StopTimer()
|
||||
// codeInit()
|
||||
// b.StartTimer()
|
||||
// }
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var r codeResponse
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(codeJSON, &r); err != nil {
|
||||
// b.Fatal("Unmarshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// b.SetBytes(int64(len(codeJSON)))
|
||||
// }
|
||||
|
||||
func BenchmarkUnmarshalString(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
data := []byte(`"hello, world"`)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var s string
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(data, &s); err != nil {
|
||||
b.Fatal("Unmarshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkUnmarshalString(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// data := []byte(`"hello, world"`)
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var s string
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(data, &s); err != nil {
|
||||
// b.Fatal("Unmarshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkUnmarshalFloat64(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
data := []byte(`3.14`)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var f float64
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(data, &f); err != nil {
|
||||
b.Fatal("Unmarshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkUnmarshalFloat64(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// data := []byte(`3.14`)
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var f float64
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(data, &f); err != nil {
|
||||
// b.Fatal("Unmarshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkUnmarshalInt64(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
data := []byte(`3`)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var x int64
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(data, &x); err != nil {
|
||||
b.Fatal("Unmarshal:", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkUnmarshalInt64(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// data := []byte(`3`)
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var x int64
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(data, &x); err != nil {
|
||||
// b.Fatal("Unmarshal:", err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkIssue10335(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
j := []byte(`{"a":{ }}`)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var s struct{}
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(j, &s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkIssue10335(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// j := []byte(`{"a":{ }}`)
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var s struct{}
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(j, &s); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkUnmapped(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var s struct{}
|
||||
for pb.Next() {
|
||||
if err := Unmarshal(j, &s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkUnmapped(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var s struct{}
|
||||
// for pb.Next() {
|
||||
// if err := Unmarshal(j, &s); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkTypeFieldsCache(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
var maxTypes int = 1e6
|
||||
if testenv.Builder() != "" {
|
||||
maxTypes = 1e3 // restrict cache sizes on builders
|
||||
}
|
||||
// func BenchmarkTypeFieldsCache(b *testing.B) {
|
||||
// b.ReportAllocs()
|
||||
// var maxTypes int = 1e6
|
||||
// if testenv.Builder() != "" {
|
||||
// maxTypes = 1e3 // restrict cache sizes on builders
|
||||
// }
|
||||
|
||||
// Dynamically generate many new types.
|
||||
types := make([]reflect.Type, maxTypes)
|
||||
fs := []reflect.StructField{{
|
||||
Type: reflect.TypeOf(""),
|
||||
Index: []int{0},
|
||||
}}
|
||||
for i := range types {
|
||||
fs[0].Name = fmt.Sprintf("TypeFieldsCache%d", i)
|
||||
types[i] = reflect.StructOf(fs)
|
||||
}
|
||||
// // Dynamically generate many new types.
|
||||
// types := make([]reflect.Type, maxTypes)
|
||||
// fs := []reflect.StructField{{
|
||||
// Type: reflect.TypeOf(""),
|
||||
// Index: []int{0},
|
||||
// }}
|
||||
// for i := range types {
|
||||
// fs[0].Name = fmt.Sprintf("TypeFieldsCache%d", i)
|
||||
// types[i] = reflect.StructOf(fs)
|
||||
// }
|
||||
|
||||
// clearClear clears the cache. Other JSON operations, must not be running.
|
||||
clearCache := func() {
|
||||
fieldCache = sync.Map{}
|
||||
}
|
||||
// // clearClear clears the cache. Other JSON operations, must not be running.
|
||||
// clearCache := func() {
|
||||
// fieldCache = sync.Map{}
|
||||
// }
|
||||
|
||||
// MissTypes tests the performance of repeated cache misses.
|
||||
// This measures the time to rebuild a cache of size nt.
|
||||
for nt := 1; nt <= maxTypes; nt *= 10 {
|
||||
ts := types[:nt]
|
||||
b.Run(fmt.Sprintf("MissTypes%d", nt), func(b *testing.B) {
|
||||
nc := runtime.GOMAXPROCS(0)
|
||||
for i := 0; i < b.N; i++ {
|
||||
clearCache()
|
||||
var wg sync.WaitGroup
|
||||
for j := 0; j < nc; j++ {
|
||||
wg.Add(1)
|
||||
go func(j int) {
|
||||
for _, t := range ts[(j*len(ts))/nc : ((j+1)*len(ts))/nc] {
|
||||
cachedTypeFields(t)
|
||||
}
|
||||
wg.Done()
|
||||
}(j)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
})
|
||||
}
|
||||
// // MissTypes tests the performance of repeated cache misses.
|
||||
// // This measures the time to rebuild a cache of size nt.
|
||||
// for nt := 1; nt <= maxTypes; nt *= 10 {
|
||||
// ts := types[:nt]
|
||||
// b.Run(fmt.Sprintf("MissTypes%d", nt), func(b *testing.B) {
|
||||
// nc := runtime.GOMAXPROCS(0)
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// clearCache()
|
||||
// var wg sync.WaitGroup
|
||||
// for j := 0; j < nc; j++ {
|
||||
// wg.Add(1)
|
||||
// go func(j int) {
|
||||
// for _, t := range ts[(j*len(ts))/nc : ((j+1)*len(ts))/nc] {
|
||||
// cachedTypeFields(t)
|
||||
// }
|
||||
// wg.Done()
|
||||
// }(j)
|
||||
// }
|
||||
// wg.Wait()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
// HitTypes tests the performance of repeated cache hits.
|
||||
// This measures the average time of each cache lookup.
|
||||
for nt := 1; nt <= maxTypes; nt *= 10 {
|
||||
// Pre-warm a cache of size nt.
|
||||
clearCache()
|
||||
for _, t := range types[:nt] {
|
||||
cachedTypeFields(t)
|
||||
}
|
||||
b.Run(fmt.Sprintf("HitTypes%d", nt), func(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
cachedTypeFields(types[0])
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
// // HitTypes tests the performance of repeated cache hits.
|
||||
// // This measures the average time of each cache lookup.
|
||||
// for nt := 1; nt <= maxTypes; nt *= 10 {
|
||||
// // Pre-warm a cache of size nt.
|
||||
// clearCache()
|
||||
// for _, t := range types[:nt] {
|
||||
// cachedTypeFields(t)
|
||||
// }
|
||||
// b.Run(fmt.Sprintf("HitTypes%d", nt), func(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// cachedTypeFields(types[0])
|
||||
// }
|
||||
// })
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
@ -113,17 +113,17 @@ func TestNumberIsValid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNumberIsValid(b *testing.B) {
|
||||
s := "-61657.61667E+61673"
|
||||
for i := 0; i < b.N; i++ {
|
||||
isValidNumber(s)
|
||||
}
|
||||
}
|
||||
// func BenchmarkNumberIsValid(b *testing.B) {
|
||||
// s := "-61657.61667E+61673"
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// isValidNumber(s)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkNumberIsValidRegexp(b *testing.B) {
|
||||
var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`)
|
||||
s := "-61657.61667E+61673"
|
||||
for i := 0; i < b.N; i++ {
|
||||
jsonNumberRegexp.MatchString(s)
|
||||
}
|
||||
}
|
||||
// func BenchmarkNumberIsValidRegexp(b *testing.B) {
|
||||
// var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`)
|
||||
// s := "-61657.61667E+61673"
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// jsonNumberRegexp.MatchString(s)
|
||||
// }
|
||||
// }
|
||||
|
@ -470,47 +470,47 @@ func newValue(model interface{}) reflect.Value {
|
||||
return reflect.New(reflect.TypeOf(model))
|
||||
}
|
||||
|
||||
func BenchmarkMarshal(b *testing.B) {
|
||||
j := make([]byte, 0, 128*1024)
|
||||
// func BenchmarkMarshal(b *testing.B) {
|
||||
// j := make([]byte, 0, 128*1024)
|
||||
|
||||
for _, v := range testValues {
|
||||
b.Run(testName(v), func(b *testing.B) {
|
||||
if marshal == nil {
|
||||
return
|
||||
}
|
||||
// for _, v := range testValues {
|
||||
// b.Run(testName(v), func(b *testing.B) {
|
||||
// if marshal == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
for i := 0; i != b.N; i++ {
|
||||
j, _ = marshal(j[:0], v)
|
||||
}
|
||||
// for i := 0; i != b.N; i++ {
|
||||
// j, _ = marshal(j[:0], v)
|
||||
// }
|
||||
|
||||
b.SetBytes(int64(len(j)))
|
||||
})
|
||||
}
|
||||
}
|
||||
// b.SetBytes(int64(len(j)))
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkUnmarshal(b *testing.B) {
|
||||
for _, v := range testValues {
|
||||
b.Run(testName(v), func(b *testing.B) {
|
||||
if unmarshal == nil {
|
||||
return
|
||||
}
|
||||
// func BenchmarkUnmarshal(b *testing.B) {
|
||||
// for _, v := range testValues {
|
||||
// b.Run(testName(v), func(b *testing.B) {
|
||||
// if unmarshal == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
x := v
|
||||
if d, ok := x.(time.Duration); ok {
|
||||
x = duration(d)
|
||||
}
|
||||
// x := v
|
||||
// if d, ok := x.(time.Duration); ok {
|
||||
// x = duration(d)
|
||||
// }
|
||||
|
||||
j, _ := json.Marshal(x)
|
||||
x = newValue(v).Interface()
|
||||
// j, _ := json.Marshal(x)
|
||||
// x = newValue(v).Interface()
|
||||
|
||||
for i := 0; i != b.N; i++ {
|
||||
unmarshal(j, x)
|
||||
}
|
||||
// for i := 0; i != b.N; i++ {
|
||||
// unmarshal(j, x)
|
||||
// }
|
||||
|
||||
b.SetBytes(int64(len(j)))
|
||||
})
|
||||
}
|
||||
}
|
||||
// b.SetBytes(int64(len(j)))
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
||||
type buffer struct{ data []byte }
|
||||
|
||||
@ -1178,28 +1178,28 @@ func TestUnmarshalFuzzBugs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkEasyjsonUnmarshalSmallStruct(b *testing.B) {
|
||||
type Hashtag struct {
|
||||
Indices []int `json:"indices"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
// func BenchmarkEasyjsonUnmarshalSmallStruct(b *testing.B) {
|
||||
// type Hashtag struct {
|
||||
// Indices []int `json:"indices"`
|
||||
// Text string `json:"text"`
|
||||
// }
|
||||
|
||||
//easyjson:json
|
||||
type Entities struct {
|
||||
Hashtags []Hashtag `json:"hashtags"`
|
||||
Urls []*string `json:"urls"`
|
||||
UserMentions []*string `json:"user_mentions"`
|
||||
}
|
||||
// //easyjson:json
|
||||
// type Entities struct {
|
||||
// Hashtags []Hashtag `json:"hashtags"`
|
||||
// Urls []*string `json:"urls"`
|
||||
// UserMentions []*string `json:"user_mentions"`
|
||||
// }
|
||||
|
||||
var json = []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`)
|
||||
// var json = []byte(`{"hashtags":[{"indices":[5, 10],"text":"some-text"}],"urls":[],"user_mentions":[]}`)
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
var value Entities
|
||||
if err := Unmarshal(json, &value); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// var value Entities
|
||||
// if err := Unmarshal(json, &value); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
type testMarshaller struct {
|
||||
v string
|
||||
|
@ -1,7 +1,6 @@
|
||||
package json
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@ -82,93 +81,93 @@ func TestAppendToLower(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseString(b *testing.B) {
|
||||
s := []byte(`"__segment_internal"`)
|
||||
// func BenchmarkParseString(b *testing.B) {
|
||||
// s := []byte(`"__segment_internal"`)
|
||||
|
||||
for i := 0; i != b.N; i++ {
|
||||
parseString(s)
|
||||
}
|
||||
}
|
||||
// for i := 0; i != b.N; i++ {
|
||||
// parseString(s)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkToLower(b *testing.B) {
|
||||
s := []byte("someFieldWithALongName")
|
||||
// func BenchmarkToLower(b *testing.B) {
|
||||
// s := []byte("someFieldWithALongName")
|
||||
|
||||
for i := 0; i != b.N; i++ {
|
||||
bytes.ToLower(s)
|
||||
}
|
||||
}
|
||||
// for i := 0; i != b.N; i++ {
|
||||
// bytes.ToLower(s)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkAppendToLower(b *testing.B) {
|
||||
a := []byte(nil)
|
||||
s := []byte("someFieldWithALongName")
|
||||
// func BenchmarkAppendToLower(b *testing.B) {
|
||||
// a := []byte(nil)
|
||||
// s := []byte("someFieldWithALongName")
|
||||
|
||||
for i := 0; i != b.N; i++ {
|
||||
a = appendToLower(a[:0], s)
|
||||
}
|
||||
}
|
||||
// for i := 0; i != b.N; i++ {
|
||||
// a = appendToLower(a[:0], s)
|
||||
// }
|
||||
// }
|
||||
|
||||
var benchmarkHasPrefixString = []byte("some random string")
|
||||
var benchmarkHasPrefixResult = false
|
||||
// var benchmarkHasPrefixString = []byte("some random string")
|
||||
// var benchmarkHasPrefixResult = false
|
||||
|
||||
func BenchmarkHasPrefix(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
benchmarkHasPrefixResult = hasPrefix(benchmarkHasPrefixString, "null")
|
||||
}
|
||||
}
|
||||
// func BenchmarkHasPrefix(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// benchmarkHasPrefixResult = hasPrefix(benchmarkHasPrefixString, "null")
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkHasNullPrefix(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
benchmarkHasPrefixResult = hasNullPrefix(benchmarkHasPrefixString)
|
||||
}
|
||||
}
|
||||
// func BenchmarkHasNullPrefix(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// benchmarkHasPrefixResult = hasNullPrefix(benchmarkHasPrefixString)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkHasTruePrefix(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
benchmarkHasPrefixResult = hasTruePrefix(benchmarkHasPrefixString)
|
||||
}
|
||||
}
|
||||
// func BenchmarkHasTruePrefix(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// benchmarkHasPrefixResult = hasTruePrefix(benchmarkHasPrefixString)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkHasFalsePrefix(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
benchmarkHasPrefixResult = hasFalsePrefix(benchmarkHasPrefixString)
|
||||
}
|
||||
}
|
||||
// func BenchmarkHasFalsePrefix(b *testing.B) {
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// benchmarkHasPrefixResult = hasFalsePrefix(benchmarkHasPrefixString)
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkParseStringEscapeNone(b *testing.B) {
|
||||
var j = []byte(`"` + strings.Repeat(`a`, 1000) + `"`)
|
||||
var s string
|
||||
b.SetBytes(int64(len(j)))
|
||||
// func BenchmarkParseStringEscapeNone(b *testing.B) {
|
||||
// var j = []byte(`"` + strings.Repeat(`a`, 1000) + `"`)
|
||||
// var s string
|
||||
// b.SetBytes(int64(len(j)))
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := Unmarshal(j, &s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
s = ""
|
||||
}
|
||||
}
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if err := Unmarshal(j, &s); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// s = ""
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkParseStringEscapeOne(b *testing.B) {
|
||||
var j = []byte(`"` + strings.Repeat(`a`, 998) + `\n"`)
|
||||
var s string
|
||||
b.SetBytes(int64(len(j)))
|
||||
// func BenchmarkParseStringEscapeOne(b *testing.B) {
|
||||
// var j = []byte(`"` + strings.Repeat(`a`, 998) + `\n"`)
|
||||
// var s string
|
||||
// b.SetBytes(int64(len(j)))
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := Unmarshal(j, &s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
s = ""
|
||||
}
|
||||
}
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if err := Unmarshal(j, &s); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// s = ""
|
||||
// }
|
||||
// }
|
||||
|
||||
func BenchmarkParseStringEscapeAll(b *testing.B) {
|
||||
var j = []byte(`"` + strings.Repeat(`\`, 1000) + `"`)
|
||||
var s string
|
||||
b.SetBytes(int64(len(j)))
|
||||
// func BenchmarkParseStringEscapeAll(b *testing.B) {
|
||||
// var j = []byte(`"` + strings.Repeat(`\`, 1000) + `"`)
|
||||
// var s string
|
||||
// b.SetBytes(int64(len(j)))
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := Unmarshal(j, &s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
s = ""
|
||||
}
|
||||
}
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// if err := Unmarshal(j, &s); err != nil {
|
||||
// b.Fatal(err)
|
||||
// }
|
||||
// s = ""
|
||||
// }
|
||||
// }
|
||||
|
@ -185,103 +185,103 @@ func TestTokenizer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkTokenizer(b *testing.B) {
|
||||
values := []struct {
|
||||
scenario string
|
||||
payload []byte
|
||||
}{
|
||||
{
|
||||
scenario: "null",
|
||||
payload: []byte(`null`),
|
||||
},
|
||||
// func BenchmarkTokenizer(b *testing.B) {
|
||||
// values := []struct {
|
||||
// scenario string
|
||||
// payload []byte
|
||||
// }{
|
||||
// {
|
||||
// scenario: "null",
|
||||
// payload: []byte(`null`),
|
||||
// },
|
||||
|
||||
{
|
||||
scenario: "true",
|
||||
payload: []byte(`true`),
|
||||
},
|
||||
// {
|
||||
// scenario: "true",
|
||||
// payload: []byte(`true`),
|
||||
// },
|
||||
|
||||
{
|
||||
scenario: "false",
|
||||
payload: []byte(`false`),
|
||||
},
|
||||
// {
|
||||
// scenario: "false",
|
||||
// payload: []byte(`false`),
|
||||
// },
|
||||
|
||||
{
|
||||
scenario: "number",
|
||||
payload: []byte(`-1.23456789`),
|
||||
},
|
||||
// {
|
||||
// scenario: "number",
|
||||
// payload: []byte(`-1.23456789`),
|
||||
// },
|
||||
|
||||
{
|
||||
scenario: "string",
|
||||
payload: []byte(`"1234567890"`),
|
||||
},
|
||||
// {
|
||||
// scenario: "string",
|
||||
// payload: []byte(`"1234567890"`),
|
||||
// },
|
||||
|
||||
{
|
||||
scenario: "object",
|
||||
payload: []byte(`{
|
||||
"timestamp": "2019-01-09T18:59:57.456Z",
|
||||
"channel": "server",
|
||||
"type": "track",
|
||||
"event": "Test",
|
||||
"userId": "test-user-whatever",
|
||||
"messageId": "test-message-whatever",
|
||||
"integrations": {
|
||||
"whatever": {
|
||||
"debugMode": false
|
||||
},
|
||||
"myIntegration": {
|
||||
"debugMode": true
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"trait1": 1,
|
||||
"trait2": "test",
|
||||
"trait3": true
|
||||
},
|
||||
"settings": {
|
||||
"apiKey": "1234567890",
|
||||
"debugMode": false,
|
||||
"directChannels": [
|
||||
"server",
|
||||
"client"
|
||||
],
|
||||
"endpoint": "https://somewhere.com/v1/integrations/segment"
|
||||
}
|
||||
}`),
|
||||
},
|
||||
}
|
||||
// {
|
||||
// scenario: "object",
|
||||
// payload: []byte(`{
|
||||
// "timestamp": "2019-01-09T18:59:57.456Z",
|
||||
// "channel": "server",
|
||||
// "type": "track",
|
||||
// "event": "Test",
|
||||
// "userId": "test-user-whatever",
|
||||
// "messageId": "test-message-whatever",
|
||||
// "integrations": {
|
||||
// "whatever": {
|
||||
// "debugMode": false
|
||||
// },
|
||||
// "myIntegration": {
|
||||
// "debugMode": true
|
||||
// }
|
||||
// },
|
||||
// "properties": {
|
||||
// "trait1": 1,
|
||||
// "trait2": "test",
|
||||
// "trait3": true
|
||||
// },
|
||||
// "settings": {
|
||||
// "apiKey": "1234567890",
|
||||
// "debugMode": false,
|
||||
// "directChannels": [
|
||||
// "server",
|
||||
// "client"
|
||||
// ],
|
||||
// "endpoint": "https://somewhere.com/v1/integrations/segment"
|
||||
// }
|
||||
// }`),
|
||||
// },
|
||||
// }
|
||||
|
||||
benchmarks := []struct {
|
||||
scenario string
|
||||
function func(*testing.B, []byte)
|
||||
}{
|
||||
{
|
||||
scenario: "github.com/segmentio/encoding/json",
|
||||
function: func(b *testing.B, json []byte) {
|
||||
t := NewTokenizer(nil)
|
||||
// benchmarks := []struct {
|
||||
// scenario string
|
||||
// function func(*testing.B, []byte)
|
||||
// }{
|
||||
// {
|
||||
// scenario: "github.com/segmentio/encoding/json",
|
||||
// function: func(b *testing.B, json []byte) {
|
||||
// t := NewTokenizer(nil)
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
t.Reset(json)
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// t.Reset(json)
|
||||
|
||||
for t.Next() {
|
||||
// Does nothing other than iterating over each token to measure the
|
||||
// CPU and memory footprint.
|
||||
}
|
||||
// for t.Next() {
|
||||
// // Does nothing other than iterating over each token to measure the
|
||||
// // CPU and memory footprint.
|
||||
// }
|
||||
|
||||
if t.Err != nil {
|
||||
b.Error(t.Err)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
// if t.Err != nil {
|
||||
// b.Error(t.Err)
|
||||
// }
|
||||
// }
|
||||
// },
|
||||
// },
|
||||
// }
|
||||
|
||||
for _, bechmark := range benchmarks {
|
||||
b.Run(bechmark.scenario, func(b *testing.B) {
|
||||
for _, value := range values {
|
||||
b.Run(value.scenario, func(b *testing.B) {
|
||||
bechmark.function(b, value.payload)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
// for _, bechmark := range benchmarks {
|
||||
// b.Run(bechmark.scenario, func(b *testing.B) {
|
||||
// for _, value := range values {
|
||||
// b.Run(value.scenario, func(b *testing.B) {
|
||||
// bechmark.function(b, value.payload)
|
||||
// })
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
@ -1,312 +1,302 @@
|
||||
package fasttemplate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"text/template"
|
||||
)
|
||||
// var (
|
||||
// source = "http://{{uid}}.foo.bar.com/?cb={{cb}}{{width}}&width={{width}}&height={{height}}&timeout={{timeout}}&uid={{uid}}&subid={{subid}}&ref={{ref}}&empty={{empty}}"
|
||||
// result = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty="
|
||||
// resultEscaped = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http%3A%2F%2Fgoogle.com%2Faaa%2Fbbb%2Fccc&empty="
|
||||
// resultStd = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty={{empty}}"
|
||||
// resultTextTemplate = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty=<no value>"
|
||||
|
||||
var (
|
||||
source = "http://{{uid}}.foo.bar.com/?cb={{cb}}{{width}}&width={{width}}&height={{height}}&timeout={{timeout}}&uid={{uid}}&subid={{subid}}&ref={{ref}}&empty={{empty}}"
|
||||
result = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty="
|
||||
resultEscaped = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http%3A%2F%2Fgoogle.com%2Faaa%2Fbbb%2Fccc&empty="
|
||||
resultStd = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty={{empty}}"
|
||||
resultTextTemplate = "http://aaasdf.foo.bar.com/?cb=12341232&width=1232&height=123&timeout=123123&uid=aaasdf&subid=asdfds&ref=http://google.com/aaa/bbb/ccc&empty=<no value>"
|
||||
// resultBytes = []byte(result)
|
||||
// resultEscapedBytes = []byte(resultEscaped)
|
||||
// resultStdBytes = []byte(resultStd)
|
||||
// resultTextTemplateBytes = []byte(resultTextTemplate)
|
||||
|
||||
resultBytes = []byte(result)
|
||||
resultEscapedBytes = []byte(resultEscaped)
|
||||
resultStdBytes = []byte(resultStd)
|
||||
resultTextTemplateBytes = []byte(resultTextTemplate)
|
||||
// m = map[string]interface{}{
|
||||
// "cb": []byte("1234"),
|
||||
// "width": []byte("1232"),
|
||||
// "height": []byte("123"),
|
||||
// "timeout": []byte("123123"),
|
||||
// "uid": []byte("aaasdf"),
|
||||
// "subid": []byte("asdfds"),
|
||||
// "ref": []byte("http://google.com/aaa/bbb/ccc"),
|
||||
// }
|
||||
// )
|
||||
|
||||
m = map[string]interface{}{
|
||||
"cb": []byte("1234"),
|
||||
"width": []byte("1232"),
|
||||
"height": []byte("123"),
|
||||
"timeout": []byte("123123"),
|
||||
"uid": []byte("aaasdf"),
|
||||
"subid": []byte("asdfds"),
|
||||
"ref": []byte("http://google.com/aaa/bbb/ccc"),
|
||||
}
|
||||
)
|
||||
// func map2slice(m map[string]interface{}) []string {
|
||||
// var a []string
|
||||
// for k, v := range m {
|
||||
// a = append(a, "{{"+k+"}}", string(v.([]byte)))
|
||||
// }
|
||||
// return a
|
||||
// }
|
||||
|
||||
func map2slice(m map[string]interface{}) []string {
|
||||
var a []string
|
||||
for k, v := range m {
|
||||
a = append(a, "{{"+k+"}}", string(v.([]byte)))
|
||||
}
|
||||
return a
|
||||
}
|
||||
// func BenchmarkFmtFprintf(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// fmt.Fprintf(&w,
|
||||
// "http://%[5]s.foo.bar.com/?cb=%[1]s%[2]s&width=%[2]s&height=%[3]s&timeout=%[4]s&uid=%[5]s&subid=%[6]s&ref=%[7]s&empty=",
|
||||
// m["cb"], m["width"], m["height"], m["timeout"], m["uid"], m["subid"], m["ref"])
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultBytes) {
|
||||
// b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkFmtFprintf(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
fmt.Fprintf(&w,
|
||||
"http://%[5]s.foo.bar.com/?cb=%[1]s%[2]s&width=%[2]s&height=%[3]s&timeout=%[4]s&uid=%[5]s&subid=%[6]s&ref=%[7]s&empty=",
|
||||
m["cb"], m["width"], m["height"], m["timeout"], m["uid"], m["subid"], m["ref"])
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultBytes) {
|
||||
b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkStringsReplace(b *testing.B) {
|
||||
// mSlice := map2slice(m)
|
||||
|
||||
func BenchmarkStringsReplace(b *testing.B) {
|
||||
mSlice := map2slice(m)
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// x := source
|
||||
// for i := 0; i < len(mSlice); i += 2 {
|
||||
// x = strings.Replace(x, mSlice[i], mSlice[i+1], -1)
|
||||
// }
|
||||
// if x != resultStd {
|
||||
// b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
x := source
|
||||
for i := 0; i < len(mSlice); i += 2 {
|
||||
x = strings.Replace(x, mSlice[i], mSlice[i+1], -1)
|
||||
}
|
||||
if x != resultStd {
|
||||
b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkStringsReplacer(b *testing.B) {
|
||||
// mSlice := map2slice(m)
|
||||
|
||||
func BenchmarkStringsReplacer(b *testing.B) {
|
||||
mSlice := map2slice(m)
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// r := strings.NewReplacer(mSlice...)
|
||||
// x := r.Replace(source)
|
||||
// if x != resultStd {
|
||||
// b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
r := strings.NewReplacer(mSlice...)
|
||||
x := r.Replace(source)
|
||||
if x != resultStd {
|
||||
b.Fatalf("Unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkTextTemplate(b *testing.B) {
|
||||
// s := strings.Replace(source, "{{", "{{.", -1)
|
||||
// t, err := template.New("test").Parse(s)
|
||||
// if err != nil {
|
||||
// b.Fatalf("Error when parsing template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkTextTemplate(b *testing.B) {
|
||||
s := strings.Replace(source, "{{", "{{.", -1)
|
||||
t, err := template.New("test").Parse(s)
|
||||
if err != nil {
|
||||
b.Fatalf("Error when parsing template: %s", err)
|
||||
}
|
||||
// mm := make(map[string]string)
|
||||
// for k, v := range m {
|
||||
// mm[k] = string(v.([]byte))
|
||||
// }
|
||||
|
||||
mm := make(map[string]string)
|
||||
for k, v := range m {
|
||||
mm[k] = string(v.([]byte))
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// if err := t.Execute(&w, mm); err != nil {
|
||||
// b.Fatalf("error when executing template: %s", err)
|
||||
// }
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultTextTemplateBytes) {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultTextTemplateBytes)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
if err := t.Execute(&w, mm); err != nil {
|
||||
b.Fatalf("error when executing template: %s", err)
|
||||
}
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultTextTemplateBytes) {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultTextTemplateBytes)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteFunc(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteFunc(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// if _, err := t.ExecuteFunc(&w, testTagFunc); err != nil {
|
||||
// b.Fatalf("unexpected error: %s", err)
|
||||
// }
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultBytes) {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultBytes)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
if _, err := t.ExecuteFunc(&w, testTagFunc); err != nil {
|
||||
b.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultBytes) {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultBytes)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecute(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecute(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// if _, err := t.Execute(&w, m); err != nil {
|
||||
// b.Fatalf("unexpected error: %s", err)
|
||||
// }
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultBytes) {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultBytes)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
if _, err := t.Execute(&w, m); err != nil {
|
||||
b.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultBytes) {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultBytes)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteStd(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteStd(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// if _, err := t.ExecuteStd(&w, m); err != nil {
|
||||
// b.Fatalf("unexpected error: %s", err)
|
||||
// }
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultStdBytes) {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultStdBytes)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
if _, err := t.ExecuteStd(&w, m); err != nil {
|
||||
b.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultStdBytes) {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultStdBytes)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteFuncString(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteFuncString(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// x := t.ExecuteFuncString(testTagFunc)
|
||||
// if x != result {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
x := t.ExecuteFuncString(testTagFunc)
|
||||
if x != result {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteString(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteString(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// x := t.ExecuteString(m)
|
||||
// if x != result {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
x := t.ExecuteString(m)
|
||||
if x != result {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, result)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteStringStd(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteStringStd(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// x := t.ExecuteStringStd(m)
|
||||
// if x != resultStd {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
x := t.ExecuteStringStd(m)
|
||||
if x != resultStd {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultStd)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkFastTemplateExecuteTagFunc(b *testing.B) {
|
||||
// t, err := NewTemplate(source, "{{", "}}")
|
||||
// if err != nil {
|
||||
// b.Fatalf("error in template: %s", err)
|
||||
// }
|
||||
|
||||
func BenchmarkFastTemplateExecuteTagFunc(b *testing.B) {
|
||||
t, err := NewTemplate(source, "{{", "}}")
|
||||
if err != nil {
|
||||
b.Fatalf("error in template: %s", err)
|
||||
}
|
||||
// mm := make(map[string]interface{})
|
||||
// for k, v := range m {
|
||||
// if k == "ref" {
|
||||
// vv := v.([]byte)
|
||||
// v = TagFunc(func(w io.Writer, tag string) (int, error) { return w.Write([]byte(url.QueryEscape(string(vv)))) })
|
||||
// }
|
||||
// mm[k] = v
|
||||
// }
|
||||
|
||||
mm := make(map[string]interface{})
|
||||
for k, v := range m {
|
||||
if k == "ref" {
|
||||
vv := v.([]byte)
|
||||
v = TagFunc(func(w io.Writer, tag string) (int, error) { return w.Write([]byte(url.QueryEscape(string(vv)))) })
|
||||
}
|
||||
mm[k] = v
|
||||
}
|
||||
// b.ResetTimer()
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// if _, err := t.Execute(&w, mm); err != nil {
|
||||
// b.Fatalf("unexpected error: %s", err)
|
||||
// }
|
||||
// x := w.Bytes()
|
||||
// if !bytes.Equal(x, resultEscapedBytes) {
|
||||
// b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultEscapedBytes)
|
||||
// }
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
if _, err := t.Execute(&w, mm); err != nil {
|
||||
b.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
x := w.Bytes()
|
||||
if !bytes.Equal(x, resultEscapedBytes) {
|
||||
b.Fatalf("unexpected result\n%q\nExpected\n%q\n", x, resultEscapedBytes)
|
||||
}
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkNewTemplate(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// for pb.Next() {
|
||||
// _ = New(source, "{{", "}}")
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkNewTemplate(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
_ = New(source, "{{", "}}")
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkTemplateReset(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// t := New(source, "{{", "}}")
|
||||
// for pb.Next() {
|
||||
// t.Reset(source, "{{", "}}")
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkTemplateReset(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
t := New(source, "{{", "}}")
|
||||
for pb.Next() {
|
||||
t.Reset(source, "{{", "}}")
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkTemplateResetExecuteFunc(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// t := New(source, "{{", "}}")
|
||||
// var w bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// t.Reset(source, "{{", "}}")
|
||||
// t.ExecuteFunc(&w, testTagFunc)
|
||||
// w.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkTemplateResetExecuteFunc(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
t := New(source, "{{", "}}")
|
||||
var w bytes.Buffer
|
||||
for pb.Next() {
|
||||
t.Reset(source, "{{", "}}")
|
||||
t.ExecuteFunc(&w, testTagFunc)
|
||||
w.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
// func BenchmarkExecuteFunc(b *testing.B) {
|
||||
// b.RunParallel(func(pb *testing.PB) {
|
||||
// var bb bytes.Buffer
|
||||
// for pb.Next() {
|
||||
// ExecuteFunc(source, "{{", "}}", &bb, testTagFunc)
|
||||
// bb.Reset()
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
|
||||
func BenchmarkExecuteFunc(b *testing.B) {
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
var bb bytes.Buffer
|
||||
for pb.Next() {
|
||||
ExecuteFunc(source, "{{", "}}", &bb, testTagFunc)
|
||||
bb.Reset()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func testTagFunc(w io.Writer, tag string) (int, error) {
|
||||
if t, ok := m[tag]; ok {
|
||||
return w.Write(t.([]byte))
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
// func testTagFunc(w io.Writer, tag string) (int, error) {
|
||||
// if t, ok := m[tag]; ok {
|
||||
// return w.Write(t.([]byte))
|
||||
// }
|
||||
// return 0, nil
|
||||
// }
|
||||
|
@ -389,34 +389,34 @@ func TestAll(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkAll(b *testing.B) {
|
||||
v := map[string][]string{
|
||||
"f1": {"1"},
|
||||
"f2": {"2"},
|
||||
"f3": {"31", "32"},
|
||||
"f4": {"41", "42"},
|
||||
"f5": {"51", "52"},
|
||||
"f6": {"61", "62"},
|
||||
"f7.f1": {"71", "72"},
|
||||
"f8.f8.f7.f1": {"81", "82"},
|
||||
"f9": {"9"},
|
||||
"f10.0.f10.0.f6": {"101", "102"},
|
||||
"f10.0.f10.1.f6": {"103", "104"},
|
||||
"f11.0.f11.0.f6": {"111", "112"},
|
||||
"f11.0.f11.1.f6": {"113", "114"},
|
||||
"f12.0.f12.0.f6": {"121", "122"},
|
||||
"f12.0.f12.1.f6": {"123", "124"},
|
||||
"f13.0.f13.0.f6": {"131", "132"},
|
||||
"f13.0.f13.1.f6": {"133", "134"},
|
||||
}
|
||||
// func BenchmarkAll(b *testing.B) {
|
||||
// v := map[string][]string{
|
||||
// "f1": {"1"},
|
||||
// "f2": {"2"},
|
||||
// "f3": {"31", "32"},
|
||||
// "f4": {"41", "42"},
|
||||
// "f5": {"51", "52"},
|
||||
// "f6": {"61", "62"},
|
||||
// "f7.f1": {"71", "72"},
|
||||
// "f8.f8.f7.f1": {"81", "82"},
|
||||
// "f9": {"9"},
|
||||
// "f10.0.f10.0.f6": {"101", "102"},
|
||||
// "f10.0.f10.1.f6": {"103", "104"},
|
||||
// "f11.0.f11.0.f6": {"111", "112"},
|
||||
// "f11.0.f11.1.f6": {"113", "114"},
|
||||
// "f12.0.f12.0.f6": {"121", "122"},
|
||||
// "f12.0.f12.1.f6": {"123", "124"},
|
||||
// "f13.0.f13.0.f6": {"131", "132"},
|
||||
// "f13.0.f13.1.f6": {"133", "134"},
|
||||
// }
|
||||
|
||||
b.ResetTimer()
|
||||
// b.ResetTimer()
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
s := &S1{}
|
||||
_ = NewDecoder().Decode(s, v)
|
||||
}
|
||||
}
|
||||
// for i := 0; i < b.N; i++ {
|
||||
// s := &S1{}
|
||||
// _ = NewDecoder().Decode(s, v)
|
||||
// }
|
||||
// }
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// Config defines the config for middleware.
|
||||
|
@ -9,7 +9,7 @@ import (
|
||||
b64 "encoding/base64"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
func Test_Middleware_BasicAuth(t *testing.T) {
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
var filedata []byte
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// Config defines the config for middleware.
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -run Test_FileSystem
|
||||
|
@ -9,7 +9,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/valyala/fasthttp"
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -run Test_Logger
|
||||
|
@ -8,7 +8,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -run Test_Proxy_Empty_Host
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -run Test_Recover
|
||||
|
@ -2,7 +2,7 @@ package requestid
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// Config defines the config for middleware.
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -run Test_RequestID
|
||||
|
2
path.go
2
path.go
@ -10,7 +10,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// routeParser holds the path segments and param names
|
||||
|
@ -8,7 +8,7 @@ import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
// go test -race -run Test_Path_parseRoute
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
)
|
||||
|
||||
func Test_App_Prefork_Child_Process(t *testing.T) {
|
||||
|
@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
@ -13,7 +13,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2/internal/utils"
|
||||
"github.com/gofiber/fiber/v2/utils"
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
|
505
utils/utils.go
Normal file
505
utils/utils.go
Normal file
@ -0,0 +1,505 @@
|
||||
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
|
||||
// 🤖 Github Repository: https://github.com/gofiber/fiber
|
||||
// 📌 API Documentation: https://docs.gofiber.io
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"text/tabwriter"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const toLowerTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
|
||||
const toUpperTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
|
||||
|
||||
// Copyright © 2014, Roger Peppe
|
||||
// github.com/rogpeppe/fastuuid
|
||||
// All rights reserved.
|
||||
|
||||
var uuidSeed [24]byte
|
||||
var uuidCounter uint64
|
||||
|
||||
func UUID() string {
|
||||
// Setup seed & counter once
|
||||
if uuidCounter <= 0 {
|
||||
if _, err := rand.Read(uuidSeed[:]); err != nil {
|
||||
return "00000000-0000-0000-0000-000000000000"
|
||||
}
|
||||
uuidCounter = binary.LittleEndian.Uint64(uuidSeed[:8])
|
||||
}
|
||||
// first 8 bytes differ, taking a slice of the first 16 bytes
|
||||
x := atomic.AddUint64(&uuidCounter, 1)
|
||||
uuid := uuidSeed
|
||||
binary.LittleEndian.PutUint64(uuid[:8], x)
|
||||
uuid[6], uuid[9] = uuid[9], uuid[6]
|
||||
|
||||
// RFC4122 v4
|
||||
uuid[6] = (uuid[6] & 0x0f) | 0x40
|
||||
uuid[8] = uuid[8]&0x3f | 0x80
|
||||
|
||||
// create UUID representation of the first 128 bits
|
||||
b := make([]byte, 36)
|
||||
hex.Encode(b[0:8], uuid[0:4])
|
||||
b[8] = '-'
|
||||
hex.Encode(b[9:13], uuid[4:6])
|
||||
b[13] = '-'
|
||||
hex.Encode(b[14:18], uuid[6:8])
|
||||
b[18] = '-'
|
||||
hex.Encode(b[19:23], uuid[8:10])
|
||||
b[23] = '-'
|
||||
hex.Encode(b[24:], uuid[10:16])
|
||||
|
||||
return GetString(b)
|
||||
}
|
||||
|
||||
// Returns function name
|
||||
func FunctionName(fn interface{}) string {
|
||||
t := reflect.ValueOf(fn).Type()
|
||||
if t.Kind() == reflect.Func {
|
||||
return runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
|
||||
}
|
||||
return t.String()
|
||||
}
|
||||
|
||||
// ToLower is the equivalent of strings.ToLower
|
||||
func ToLower(b string) string {
|
||||
var res = make([]byte, len(b))
|
||||
copy(res, b)
|
||||
for i := 0; i < len(res); i++ {
|
||||
res[i] = toLowerTable[res[i]]
|
||||
}
|
||||
|
||||
return GetString(res)
|
||||
}
|
||||
|
||||
// ToLowerBytes is the equivalent of bytes.ToLower
|
||||
func ToLowerBytes(b []byte) []byte {
|
||||
for i := 0; i < len(b); i++ {
|
||||
b[i] = toLowerTable[b[i]]
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// ToUpper is the equivalent of strings.ToUpper
|
||||
func ToUpper(b string) string {
|
||||
var res = make([]byte, len(b))
|
||||
copy(res, b)
|
||||
for i := 0; i < len(res); i++ {
|
||||
res[i] = toUpperTable[res[i]]
|
||||
}
|
||||
|
||||
return GetString(res)
|
||||
}
|
||||
|
||||
// ToUpperBytes is the equivalent of bytes.ToUpper
|
||||
func ToUpperBytes(b []byte) []byte {
|
||||
for i := 0; i < len(b); i++ {
|
||||
b[i] = toUpperTable[b[i]]
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// TrimRight is the equivalent of strings.TrimRight
|
||||
func TrimRight(s string, cutset byte) string {
|
||||
lenStr := len(s)
|
||||
for lenStr > 0 && s[lenStr-1] == cutset {
|
||||
lenStr--
|
||||
}
|
||||
return s[:lenStr]
|
||||
}
|
||||
|
||||
// TrimRightBytes is the equivalent of bytes.TrimRight
|
||||
func TrimRightBytes(b []byte, cutset byte) []byte {
|
||||
lenStr := len(b)
|
||||
for lenStr > 0 && b[lenStr-1] == cutset {
|
||||
lenStr--
|
||||
}
|
||||
return b[:lenStr]
|
||||
}
|
||||
|
||||
// TrimLeft is the equivalent of strings.TrimLeft
|
||||
func TrimLeft(s string, cutset byte) string {
|
||||
lenStr, start := len(s), 0
|
||||
for start < lenStr && s[start] == cutset {
|
||||
start++
|
||||
}
|
||||
return s[start:]
|
||||
}
|
||||
|
||||
// TrimLeftBytes is the equivalent of bytes.TrimLeft
|
||||
func TrimLeftBytes(b []byte, cutset byte) []byte {
|
||||
lenStr, start := len(b), 0
|
||||
for start < lenStr && b[start] == cutset {
|
||||
start++
|
||||
}
|
||||
return b[start:]
|
||||
}
|
||||
|
||||
// Trim is the equivalent of strings.Trim
|
||||
func Trim(s string, cutset byte) string {
|
||||
i, j := 0, len(s)-1
|
||||
for ; i < j; i++ {
|
||||
if s[i] != cutset {
|
||||
break
|
||||
}
|
||||
}
|
||||
for ; i < j; j-- {
|
||||
if s[j] != cutset {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return s[i : j+1]
|
||||
}
|
||||
|
||||
// TrimBytes is the equivalent of bytes.Trim
|
||||
func TrimBytes(b []byte, cutset byte) []byte {
|
||||
i, j := 0, len(b)-1
|
||||
for ; i < j; i++ {
|
||||
if b[i] != cutset {
|
||||
break
|
||||
}
|
||||
}
|
||||
for ; i < j; j-- {
|
||||
if b[j] != cutset {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return b[i : j+1]
|
||||
}
|
||||
|
||||
// EqualFold the equivalent of bytes.EqualFold
|
||||
func EqualsFold(b, s []byte) (equals bool) {
|
||||
n := len(b)
|
||||
equals = n == len(s)
|
||||
if equals {
|
||||
for i := 0; i < n; i++ {
|
||||
if equals = b[i]|0x20 == s[i]|0x20; !equals {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// #nosec G103
|
||||
// GetString returns a string pointer without allocation
|
||||
func GetString(b []byte) string {
|
||||
return *(*string)(unsafe.Pointer(&b))
|
||||
}
|
||||
|
||||
// #nosec G103
|
||||
// GetBytes returns a byte pointer without allocation
|
||||
func GetBytes(s string) (bs []byte) {
|
||||
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
|
||||
bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
|
||||
bh.Data = sh.Data
|
||||
bh.Len = sh.Len
|
||||
bh.Cap = sh.Len
|
||||
return
|
||||
}
|
||||
|
||||
// ImmutableString copies a string to make it immutable
|
||||
func ImmutableString(s string) string {
|
||||
return string(GetBytes(s))
|
||||
}
|
||||
|
||||
// AssertEqual checks if values are equal
|
||||
func AssertEqual(t testing.TB, expected interface{}, actual interface{}, description ...string) {
|
||||
if reflect.DeepEqual(expected, actual) {
|
||||
return
|
||||
}
|
||||
var aType = "<nil>"
|
||||
var bType = "<nil>"
|
||||
if reflect.ValueOf(expected).IsValid() {
|
||||
aType = reflect.TypeOf(expected).Name()
|
||||
}
|
||||
if reflect.ValueOf(actual).IsValid() {
|
||||
bType = reflect.TypeOf(actual).Name()
|
||||
}
|
||||
|
||||
testName := "AssertEqual"
|
||||
if t != nil {
|
||||
testName = t.Name()
|
||||
}
|
||||
|
||||
_, file, line, _ := runtime.Caller(1)
|
||||
|
||||
var buf bytes.Buffer
|
||||
w := tabwriter.NewWriter(&buf, 0, 0, 5, ' ', 0)
|
||||
fmt.Fprintf(w, "\nTest:\t%s", testName)
|
||||
fmt.Fprintf(w, "\nTrace:\t%s:%d", filepath.Base(file), line)
|
||||
fmt.Fprintf(w, "\nError:\tNot equal")
|
||||
fmt.Fprintf(w, "\nExpect:\t%v\t[%s]", expected, aType)
|
||||
fmt.Fprintf(w, "\nResult:\t%v\t[%s]", actual, bType)
|
||||
|
||||
if len(description) > 0 {
|
||||
fmt.Fprintf(w, "\nDescription:\t%s", description[0])
|
||||
}
|
||||
|
||||
result := ""
|
||||
if err := w.Flush(); err != nil {
|
||||
result = err.Error()
|
||||
} else {
|
||||
result = buf.String()
|
||||
}
|
||||
if t != nil {
|
||||
t.Fatal(result)
|
||||
} else {
|
||||
log.Fatal(result)
|
||||
}
|
||||
}
|
||||
|
||||
const MIMEOctetStream = "application/octet-stream"
|
||||
|
||||
// GetMIME returns the content-type of a file extension
|
||||
func GetMIME(extension string) (mime string) {
|
||||
if len(extension) == 0 {
|
||||
return mime
|
||||
}
|
||||
if extension[0] == '.' {
|
||||
mime = mimeExtensions[extension[1:]]
|
||||
} else {
|
||||
mime = mimeExtensions[extension]
|
||||
}
|
||||
if len(mime) == 0 {
|
||||
return MIMEOctetStream
|
||||
}
|
||||
return mime
|
||||
}
|
||||
|
||||
// GetTrimmedParam trims the ':' & '?' from a string
|
||||
func GetTrimmedParam(param string) string {
|
||||
start := 0
|
||||
end := len(param)
|
||||
|
||||
if param[start] != ':' { // is not a param
|
||||
return param
|
||||
}
|
||||
start++
|
||||
if param[end-1] == '?' { // is ?
|
||||
end--
|
||||
}
|
||||
|
||||
return param[start:end]
|
||||
}
|
||||
|
||||
// GetCharPos ...
|
||||
func GetCharPos(s string, char byte, matchCount int) int {
|
||||
if matchCount == 0 {
|
||||
matchCount = 1
|
||||
}
|
||||
endPos, pos := 0, -2
|
||||
for matchCount > 0 && pos != -1 {
|
||||
if pos > -1 {
|
||||
s = s[pos+1:]
|
||||
endPos++
|
||||
}
|
||||
pos = strings.IndexByte(s, char)
|
||||
endPos += pos
|
||||
matchCount--
|
||||
}
|
||||
return endPos
|
||||
}
|
||||
|
||||
// limits for HTTP statuscodes
|
||||
const (
|
||||
statusMessageMin = 100
|
||||
statusMessageMax = 511
|
||||
)
|
||||
|
||||
// StatusMessage returns the correct message for the provided HTTP statuscode
|
||||
func StatusMessage(status int) string {
|
||||
if status < statusMessageMin || status > statusMessageMax {
|
||||
return ""
|
||||
}
|
||||
return statusMessage[status]
|
||||
}
|
||||
|
||||
// HTTP status codes were copied from net/http.
|
||||
var statusMessage = []string{
|
||||
100: "Continue",
|
||||
101: "Switching Protocols",
|
||||
102: "Processing",
|
||||
103: "Early Hints",
|
||||
200: "OK",
|
||||
201: "Created",
|
||||
202: "Accepted",
|
||||
203: "Non-Authoritative Information",
|
||||
204: "No Content",
|
||||
205: "Reset Content",
|
||||
206: "Partial Content",
|
||||
207: "Multi-Status",
|
||||
208: "Already Reported",
|
||||
226: "IM Used",
|
||||
300: "Multiple Choices",
|
||||
301: "Moved Permanently",
|
||||
302: "Found",
|
||||
303: "See Other",
|
||||
304: "Not Modified",
|
||||
305: "Use Proxy",
|
||||
306: "Switch Proxy",
|
||||
307: "Temporary Redirect",
|
||||
308: "Permanent Redirect",
|
||||
400: "Bad Request",
|
||||
401: "Unauthorized",
|
||||
402: "Payment Required",
|
||||
403: "Forbidden",
|
||||
404: "Not Found",
|
||||
405: "Method Not Allowed",
|
||||
406: "Not Acceptable",
|
||||
407: "Proxy Authentication Required",
|
||||
408: "Request Timeout",
|
||||
409: "Conflict",
|
||||
410: "Gone",
|
||||
411: "Length Required",
|
||||
412: "Precondition Failed",
|
||||
413: "Request Entity Too Large",
|
||||
414: "Request URI Too Long",
|
||||
415: "Unsupported Media Type",
|
||||
416: "Requested Range Not Satisfiable",
|
||||
417: "Expectation Failed",
|
||||
418: "I'm a teapot",
|
||||
421: "Misdirected Request",
|
||||
422: "Unprocessable Entity",
|
||||
423: "Locked",
|
||||
424: "Failed Dependency",
|
||||
426: "Upgrade Required",
|
||||
428: "Precondition Required",
|
||||
429: "Too Many Requests",
|
||||
431: "Request Header Fields Too Large",
|
||||
451: "Unavailable For Legal Reasons",
|
||||
500: "Internal Server Error",
|
||||
501: "Not Implemented",
|
||||
502: "Bad Gateway",
|
||||
503: "Service Unavailable",
|
||||
504: "Gateway Timeout",
|
||||
505: "HTTP Version Not Supported",
|
||||
506: "Variant Also Negotiates",
|
||||
507: "Insufficient Storage",
|
||||
508: "Loop Detected",
|
||||
510: "Not Extended",
|
||||
511: "Network Authentication Required",
|
||||
}
|
||||
|
||||
// MIME types were copied from https://github.com/nginx/nginx/blob/master/conf/mime.types
|
||||
var mimeExtensions = map[string]string{
|
||||
"html": "text/html",
|
||||
"htm": "text/html",
|
||||
"shtml": "text/html",
|
||||
"css": "text/css",
|
||||
"gif": "image/gif",
|
||||
"jpeg": "image/jpeg",
|
||||
"jpg": "image/jpeg",
|
||||
"xml": "application/xml",
|
||||
"js": "application/javascript",
|
||||
"atom": "application/atom+xml",
|
||||
"rss": "application/rss+xml",
|
||||
"mml": "text/mathml",
|
||||
"txt": "text/plain",
|
||||
"jad": "text/vnd.sun.j2me.app-descriptor",
|
||||
"wml": "text/vnd.wap.wml",
|
||||
"htc": "text/x-component",
|
||||
"png": "image/png",
|
||||
"svg": "image/svg+xml",
|
||||
"svgz": "image/svg+xml",
|
||||
"tif": "image/tiff",
|
||||
"tiff": "image/tiff",
|
||||
"wbmp": "image/vnd.wap.wbmp",
|
||||
"webp": "image/webp",
|
||||
"ico": "image/x-icon",
|
||||
"jng": "image/x-jng",
|
||||
"bmp": "image/x-ms-bmp",
|
||||
"woff": "font/woff",
|
||||
"woff2": "font/woff2",
|
||||
"jar": "application/java-archive",
|
||||
"war": "application/java-archive",
|
||||
"ear": "application/java-archive",
|
||||
"json": "application/json",
|
||||
"hqx": "application/mac-binhex40",
|
||||
"doc": "application/msword",
|
||||
"pdf": "application/pdf",
|
||||
"ps": "application/postscript",
|
||||
"eps": "application/postscript",
|
||||
"ai": "application/postscript",
|
||||
"rtf": "application/rtf",
|
||||
"m3u8": "application/vnd.apple.mpegurl",
|
||||
"kml": "application/vnd.google-earth.kml+xml",
|
||||
"kmz": "application/vnd.google-earth.kmz",
|
||||
"xls": "application/vnd.ms-excel",
|
||||
"eot": "application/vnd.ms-fontobject",
|
||||
"ppt": "application/vnd.ms-powerpoint",
|
||||
"odg": "application/vnd.oasis.opendocument.graphics",
|
||||
"odp": "application/vnd.oasis.opendocument.presentation",
|
||||
"ods": "application/vnd.oasis.opendocument.spreadsheet",
|
||||
"odt": "application/vnd.oasis.opendocument.text",
|
||||
"wmlc": "application/vnd.wap.wmlc",
|
||||
"7z": "application/x-7z-compressed",
|
||||
"cco": "application/x-cocoa",
|
||||
"jardiff": "application/x-java-archive-diff",
|
||||
"jnlp": "application/x-java-jnlp-file",
|
||||
"run": "application/x-makeself",
|
||||
"pl": "application/x-perl",
|
||||
"pm": "application/x-perl",
|
||||
"prc": "application/x-pilot",
|
||||
"pdb": "application/x-pilot",
|
||||
"rar": "application/x-rar-compressed",
|
||||
"rpm": "application/x-redhat-package-manager",
|
||||
"sea": "application/x-sea",
|
||||
"swf": "application/x-shockwave-flash",
|
||||
"sit": "application/x-stuffit",
|
||||
"tcl": "application/x-tcl",
|
||||
"tk": "application/x-tcl",
|
||||
"der": "application/x-x509-ca-cert",
|
||||
"pem": "application/x-x509-ca-cert",
|
||||
"crt": "application/x-x509-ca-cert",
|
||||
"xpi": "application/x-xpinstall",
|
||||
"xhtml": "application/xhtml+xml",
|
||||
"xspf": "application/xspf+xml",
|
||||
"zip": "application/zip",
|
||||
"bin": "application/octet-stream",
|
||||
"exe": "application/octet-stream",
|
||||
"dll": "application/octet-stream",
|
||||
"deb": "application/octet-stream",
|
||||
"dmg": "application/octet-stream",
|
||||
"iso": "application/octet-stream",
|
||||
"img": "application/octet-stream",
|
||||
"msi": "application/octet-stream",
|
||||
"msp": "application/octet-stream",
|
||||
"msm": "application/octet-stream",
|
||||
"mid": "audio/midi",
|
||||
"midi": "audio/midi",
|
||||
"kar": "audio/midi",
|
||||
"mp3": "audio/mpeg",
|
||||
"ogg": "audio/ogg",
|
||||
"m4a": "audio/x-m4a",
|
||||
"ra": "audio/x-realaudio",
|
||||
"3gpp": "video/3gpp",
|
||||
"3gp": "video/3gpp",
|
||||
"ts": "video/mp2t",
|
||||
"mp4": "video/mp4",
|
||||
"mpeg": "video/mpeg",
|
||||
"mpg": "video/mpeg",
|
||||
"mov": "video/quicktime",
|
||||
"webm": "video/webm",
|
||||
"flv": "video/x-flv",
|
||||
"m4v": "video/x-m4v",
|
||||
"mng": "video/x-mng",
|
||||
"asx": "video/x-ms-asf",
|
||||
"asf": "video/x-ms-asf",
|
||||
"wmv": "video/x-ms-wmv",
|
||||
"avi": "video/x-msvideo",
|
||||
}
|
502
utils/utils_test.go
Normal file
502
utils/utils_test.go
Normal file
@ -0,0 +1,502 @@
|
||||
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
|
||||
// 🤖 Github Repository: https://github.com/gofiber/fiber
|
||||
// 📌 API Documentation: https://docs.gofiber.io
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_Utils_FunctionName(t *testing.T) {
|
||||
t.Parallel()
|
||||
AssertEqual(t, "github.com/gofiber/fiber/v2/utils.Test_Utils_UUID", FunctionName(Test_Utils_UUID))
|
||||
|
||||
AssertEqual(t, "github.com/gofiber/fiber/v2/utils.Test_Utils_FunctionName.func1", FunctionName(func() {}))
|
||||
|
||||
var dummyint = 20
|
||||
AssertEqual(t, "int", FunctionName(dummyint))
|
||||
}
|
||||
|
||||
func Test_Utils_UUID(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := UUID()
|
||||
AssertEqual(t, 36, len(res))
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=Benchmark_UUID -benchmem -count=2
|
||||
|
||||
func Benchmark_UUID(b *testing.B) {
|
||||
var res string
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = UUID()
|
||||
}
|
||||
AssertEqual(b, 36, len(res))
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
rnd := make([]byte, 16)
|
||||
_, _ = rand.Read(rnd)
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = fmt.Sprintf("%x-%x-%x-%x-%x", rnd[0:4], rnd[4:6], rnd[6:8], rnd[8:10], rnd[10:])
|
||||
}
|
||||
AssertEqual(b, 36, len(res))
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_ToUpper(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := ToUpper("/my/name/is/:param/*")
|
||||
AssertEqual(t, "/MY/NAME/IS/:PARAM/*", res)
|
||||
}
|
||||
|
||||
func Benchmark_ToUpper(b *testing.B) {
|
||||
var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
||||
var res string
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = ToUpper(path)
|
||||
}
|
||||
AssertEqual(b, "/REPOS/GOFIBER/FIBER/ISSUES/187643/COMMENTS", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.ToUpper(path)
|
||||
}
|
||||
AssertEqual(b, "/REPOS/GOFIBER/FIBER/ISSUES/187643/COMMENTS", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_ToLower(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := ToLower("/MY/NAME/IS/:PARAM/*")
|
||||
AssertEqual(t, "/my/name/is/:param/*", res)
|
||||
res = ToLower("/MY1/NAME/IS/:PARAM/*")
|
||||
AssertEqual(t, "/my1/name/is/:param/*", res)
|
||||
res = ToLower("/MY2/NAME/IS/:PARAM/*")
|
||||
AssertEqual(t, "/my2/name/is/:param/*", res)
|
||||
res = ToLower("/MY3/NAME/IS/:PARAM/*")
|
||||
AssertEqual(t, "/my3/name/is/:param/*", res)
|
||||
res = ToLower("/MY4/NAME/IS/:PARAM/*")
|
||||
AssertEqual(t, "/my4/name/is/:param/*", res)
|
||||
}
|
||||
|
||||
func Benchmark_ToLower(b *testing.B) {
|
||||
var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
||||
var res string
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = ToLower(path)
|
||||
}
|
||||
AssertEqual(b, "/repos/gofiber/fiber/issues/187643/comments", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.ToLower(path)
|
||||
}
|
||||
AssertEqual(b, "/repos/gofiber/fiber/issues/187643/comments", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_ToLowerBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := ToLowerBytes([]byte("/MY/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, bytes.Equal([]byte("/my/name/is/:param/*"), res))
|
||||
res = ToLowerBytes([]byte("/MY1/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, bytes.Equal([]byte("/my1/name/is/:param/*"), res))
|
||||
res = ToLowerBytes([]byte("/MY2/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, bytes.Equal([]byte("/my2/name/is/:param/*"), res))
|
||||
res = ToLowerBytes([]byte("/MY3/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, bytes.Equal([]byte("/my3/name/is/:param/*"), res))
|
||||
res = ToLowerBytes([]byte("/MY4/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, bytes.Equal([]byte("/my4/name/is/:param/*"), res))
|
||||
}
|
||||
|
||||
func Benchmark_ToLowerBytes(b *testing.B) {
|
||||
var path = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts")
|
||||
var res []byte
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = ToLowerBytes(path)
|
||||
}
|
||||
AssertEqual(b, bytes.EqualFold(GetBytes("/repos/gofiber/fiber/issues/187643/comments"), res), true)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = bytes.ToLower(path)
|
||||
}
|
||||
AssertEqual(b, bytes.EqualFold(GetBytes("/repos/gofiber/fiber/issues/187643/comments"), res), true)
|
||||
})
|
||||
}
|
||||
|
||||
func Benchmark_EqualFolds(b *testing.B) {
|
||||
var left = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts")
|
||||
var right = []byte("/RePos/goFiber/Fiber/issues/187643/COMMENTS")
|
||||
var res bool
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = EqualsFold(left, right)
|
||||
}
|
||||
AssertEqual(b, true, res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = bytes.EqualFold(left, right)
|
||||
}
|
||||
AssertEqual(b, true, res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_EqualsFold(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := EqualsFold([]byte("/MY/NAME/IS/:PARAM/*"), []byte("/my/name/is/:param/*"))
|
||||
AssertEqual(t, true, res)
|
||||
res = EqualsFold([]byte("/MY1/NAME/IS/:PARAM/*"), []byte("/MY1/NAME/IS/:PARAM/*"))
|
||||
AssertEqual(t, true, res)
|
||||
res = EqualsFold([]byte("/my2/name/is/:param/*"), []byte("/my2/name"))
|
||||
AssertEqual(t, false, res)
|
||||
res = EqualsFold([]byte("/dddddd"), []byte("eeeeee"))
|
||||
AssertEqual(t, false, res)
|
||||
res = EqualsFold([]byte("/MY3/NAME/IS/:PARAM/*"), []byte("/my3/name/is/:param/*"))
|
||||
AssertEqual(t, true, res)
|
||||
res = EqualsFold([]byte("/MY4/NAME/IS/:PARAM/*"), []byte("/my4/nAME/IS/:param/*"))
|
||||
AssertEqual(t, true, res)
|
||||
}
|
||||
|
||||
func Test_Utils_TrimRight(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := TrimRight("/test//////", '/')
|
||||
AssertEqual(t, "/test", res)
|
||||
|
||||
res = TrimRight("/test", '/')
|
||||
AssertEqual(t, "/test", res)
|
||||
}
|
||||
func Benchmark_TrimRight(b *testing.B) {
|
||||
var res string
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = TrimRight("foobar ", ' ')
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.TrimRight("foobar ", " ")
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_TrimLeft(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := TrimLeft("////test/", '/')
|
||||
AssertEqual(t, "test/", res)
|
||||
|
||||
res = TrimLeft("test/", '/')
|
||||
AssertEqual(t, "test/", res)
|
||||
}
|
||||
func Benchmark_TrimLeft(b *testing.B) {
|
||||
var res string
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = TrimLeft(" foobar", ' ')
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.TrimLeft(" foobar", " ")
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
}
|
||||
func Test_Utils_Trim(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := Trim(" test ", ' ')
|
||||
AssertEqual(t, "test", res)
|
||||
|
||||
res = Trim("test", ' ')
|
||||
AssertEqual(t, "test", res)
|
||||
|
||||
res = Trim(".test", '.')
|
||||
AssertEqual(t, "test", res)
|
||||
}
|
||||
|
||||
func Benchmark_Trim(b *testing.B) {
|
||||
var res string
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = Trim(" foobar ", ' ')
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.Trim(" foobar ", " ")
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
b.Run("default.trimspace", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = strings.TrimSpace(" foobar ")
|
||||
}
|
||||
AssertEqual(b, "foobar", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_TrimRightBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := TrimRightBytes([]byte("/test//////"), '/')
|
||||
AssertEqual(t, []byte("/test"), res)
|
||||
|
||||
res = TrimRightBytes([]byte("/test"), '/')
|
||||
AssertEqual(t, []byte("/test"), res)
|
||||
}
|
||||
|
||||
func Benchmark_TrimRightBytes(b *testing.B) {
|
||||
var res []byte
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = TrimRightBytes([]byte("foobar "), ' ')
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = bytes.TrimRight([]byte("foobar "), " ")
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_TrimLeftBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := TrimLeftBytes([]byte("////test/"), '/')
|
||||
AssertEqual(t, []byte("test/"), res)
|
||||
|
||||
res = TrimLeftBytes([]byte("test/"), '/')
|
||||
AssertEqual(t, []byte("test/"), res)
|
||||
}
|
||||
func Benchmark_TrimLeftBytes(b *testing.B) {
|
||||
var res []byte
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = TrimLeftBytes([]byte(" foobar"), ' ')
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = bytes.TrimLeft([]byte(" foobar"), " ")
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
}
|
||||
func Test_Utils_TrimBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := TrimBytes([]byte(" test "), ' ')
|
||||
AssertEqual(t, []byte("test"), res)
|
||||
|
||||
res = TrimBytes([]byte("test"), ' ')
|
||||
AssertEqual(t, []byte("test"), res)
|
||||
|
||||
res = TrimBytes([]byte(".test"), '.')
|
||||
AssertEqual(t, []byte("test"), res)
|
||||
}
|
||||
func Benchmark_TrimBytes(b *testing.B) {
|
||||
var res []byte
|
||||
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = TrimBytes([]byte(" foobar "), ' ')
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = bytes.Trim([]byte(" foobar "), " ")
|
||||
}
|
||||
AssertEqual(b, []byte("foobar"), res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_GetCharPos(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := GetCharPos("/foo/bar/foobar/test", '/', 3)
|
||||
AssertEqual(t, 8, res)
|
||||
res = GetCharPos("foo/bar/foobar/test", '/', 3)
|
||||
AssertEqual(t, 14, res)
|
||||
res = GetCharPos("foo/bar/foobar/test", '/', 1)
|
||||
AssertEqual(t, 3, res)
|
||||
res = GetCharPos("foo/bar/foobar/test", 'f', 2)
|
||||
AssertEqual(t, 8, res)
|
||||
res = GetCharPos("foo/bar/foobar/test", 'f', 0)
|
||||
AssertEqual(t, 0, res)
|
||||
}
|
||||
|
||||
func Test_Utils_GetTrimmedParam(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := GetTrimmedParam("*")
|
||||
AssertEqual(t, "*", res)
|
||||
res = GetTrimmedParam(":param")
|
||||
AssertEqual(t, "param", res)
|
||||
res = GetTrimmedParam(":param1?")
|
||||
AssertEqual(t, "param1", res)
|
||||
res = GetTrimmedParam("noParam")
|
||||
AssertEqual(t, "noParam", res)
|
||||
}
|
||||
|
||||
func Test_Utils_GetString(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := GetString([]byte("Hello, World!"))
|
||||
AssertEqual(t, "Hello, World!", res)
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=GetString -benchmem -count=2
|
||||
|
||||
func Benchmark_GetString(b *testing.B) {
|
||||
var hello = []byte("Hello, World!")
|
||||
var res string
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = GetString(hello)
|
||||
}
|
||||
AssertEqual(b, "Hello, World!", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = string(hello)
|
||||
}
|
||||
AssertEqual(b, "Hello, World!", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_GetBytes(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := GetBytes("Hello, World!")
|
||||
AssertEqual(t, []byte("Hello, World!"), res)
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=GetBytes -benchmem -count=4
|
||||
|
||||
func Benchmark_GetBytes(b *testing.B) {
|
||||
var hello = "Hello, World!"
|
||||
var res []byte
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = GetBytes(hello)
|
||||
}
|
||||
AssertEqual(b, []byte("Hello, World!"), res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = []byte(hello)
|
||||
}
|
||||
AssertEqual(b, []byte("Hello, World!"), res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_ImmutableString(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := ImmutableString("Hello, World!")
|
||||
AssertEqual(t, "Hello, World!", res)
|
||||
}
|
||||
|
||||
func Test_Utils_GetMIME(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := GetMIME(".json")
|
||||
AssertEqual(t, "application/json", res)
|
||||
|
||||
res = GetMIME(".xml")
|
||||
AssertEqual(t, "application/xml", res)
|
||||
|
||||
res = GetMIME("xml")
|
||||
AssertEqual(t, "application/xml", res)
|
||||
|
||||
res = GetMIME("unknown")
|
||||
AssertEqual(t, MIMEOctetStream, res)
|
||||
// empty case
|
||||
res = GetMIME("")
|
||||
AssertEqual(t, "", res)
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=Benchmark_GetMIME -benchmem -count=2
|
||||
func Benchmark_GetMIME(b *testing.B) {
|
||||
var res string
|
||||
b.Run("fiber", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = GetMIME(".xml")
|
||||
res = GetMIME(".txt")
|
||||
res = GetMIME(".png")
|
||||
res = GetMIME(".exe")
|
||||
res = GetMIME(".json")
|
||||
}
|
||||
AssertEqual(b, "application/json", res)
|
||||
})
|
||||
b.Run("default", func(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = mime.TypeByExtension(".xml")
|
||||
res = mime.TypeByExtension(".txt")
|
||||
res = mime.TypeByExtension(".png")
|
||||
res = mime.TypeByExtension(".exe")
|
||||
res = mime.TypeByExtension(".json")
|
||||
}
|
||||
AssertEqual(b, "application/json", res)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Utils_StatusMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
res := StatusMessage(204)
|
||||
AssertEqual(t, "No Content", res)
|
||||
|
||||
res = StatusMessage(404)
|
||||
AssertEqual(t, "Not Found", res)
|
||||
|
||||
res = StatusMessage(426)
|
||||
AssertEqual(t, "Upgrade Required", res)
|
||||
|
||||
res = StatusMessage(511)
|
||||
AssertEqual(t, "Network Authentication Required", res)
|
||||
|
||||
res = StatusMessage(1337)
|
||||
AssertEqual(t, "", res)
|
||||
|
||||
res = StatusMessage(-1)
|
||||
AssertEqual(t, "", res)
|
||||
|
||||
res = StatusMessage(0)
|
||||
AssertEqual(t, "", res)
|
||||
|
||||
res = StatusMessage(600)
|
||||
AssertEqual(t, "", res)
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=Benchmark_StatusMessage -benchmem -count=4
|
||||
func Benchmark_StatusMessage(b *testing.B) {
|
||||
var res string
|
||||
for n := 0; n < b.N; n++ {
|
||||
res = StatusMessage(http.StatusNotExtended)
|
||||
}
|
||||
AssertEqual(b, "Not Extended", res)
|
||||
}
|
||||
|
||||
func Test_Utils_AssertEqual(t *testing.T) {
|
||||
t.Parallel()
|
||||
AssertEqual(nil, []string{}, []string{})
|
||||
AssertEqual(t, []string{}, []string{})
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user