From c88be72d77e6deede478719f77f7b83df75531e8 Mon Sep 17 00:00:00 2001 From: xuecai Date: Fri, 4 Jan 2019 23:38:56 +0800 Subject: [PATCH] add method Sort in args (#505) * add method StringSort QueryStringSort AppendBytesSort in args * simplify code * only Sort method * format * add method StringSort QueryStringSort AppendBytesSort in args * simplify code * only Sort method * format * merge and fix tests * change sort into generic by having the sort function * change sort into generic by having the sort function * change comment --- args.go | 16 +++++++++++++++- args_test.go | 8 ++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/args.go b/args.go index 8b67f903ab..dc1a73d3ab 100644 --- a/args.go +++ b/args.go @@ -4,13 +4,14 @@ import ( "bytes" "errors" "io" + "sort" "sync" "github.com/valyala/bytebufferpool" ) const ( - argsNoValue = true + argsNoValue = true argsHasValue = false ) @@ -115,6 +116,19 @@ func (a *Args) QueryString() []byte { return a.buf } +// Sort sorts Args by key and then value using 'f' as comparison function. +// +// For example args.Sort(bytes.Compare) +func (a *Args) Sort(f func(x, y []byte) int) { + sort.SliceStable(a.args, func(i, j int) bool { + n := f(a.args[i].key, a.args[j].key) + if n == 0 { + return f(a.args[i].value, a.args[j].value) == -1 + } + return n == -1 + }) +} + // AppendBytes appends query string to dst and returns the extended dst. func (a *Args) AppendBytes(dst []byte) []byte { for i, n := 0, len(a.args); i < n; i++ { diff --git a/args_test.go b/args_test.go index 2a5cb9a119..db44750b83 100644 --- a/args_test.go +++ b/args_test.go @@ -1,6 +1,7 @@ package fasthttp import ( + "bytes" "fmt" "reflect" "strings" @@ -48,6 +49,13 @@ func TestArgsAdd(t *testing.T) { t.Fatalf("unexpected result: %q. Expecting %q", s, expectedS) } + a.Sort(bytes.Compare) + ss := a.String() + expectedSS := "ba=23&foo=&foo&foo=1&foo=bar&foo=baz" + if ss != expectedSS { + t.Fatalf("unexpected result: %q. Expecting %q", ss, expectedSS) + } + var a1 Args a1.Parse(s) if a1.Len() != 6 {