Skip to content

Commit

Permalink
add method Sort in args (#505)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
xuecai authored and kirillDanshin committed Jan 4, 2019
1 parent 9793e28 commit c88be72
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
16 changes: 15 additions & 1 deletion args.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import (
"bytes"
"errors"
"io"
"sort"
"sync"

"github.com/valyala/bytebufferpool"
)

const (
argsNoValue = true
argsNoValue = true
argsHasValue = false
)

Expand Down Expand Up @@ -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++ {
Expand Down
8 changes: 8 additions & 0 deletions args_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fasthttp

import (
"bytes"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit c88be72

Please sign in to comment.