From 7b5cb77b95e2200cab14572519bd7dfdcc55fdeb Mon Sep 17 00:00:00 2001 From: pj Date: Tue, 30 Dec 2025 05:00:35 +1100 Subject: [PATCH] Add sortkeys (#2118) * added Args.SortKeys * add test for SortKeys * fix comment --- args.go | 9 +++++++++ args_test.go | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/args.go b/args.go index a2290a8..0bd7e0c 100644 --- a/args.go +++ b/args.go @@ -147,6 +147,15 @@ func (a *Args) Sort(f func(x, y []byte) int) { }) } +// SortKeys sorts Args by key only using 'f' as comparison function. +// +// For example args.SortKeys(bytes.Compare). +func (a *Args) SortKeys(f func(x, y []byte) int) { + sort.SliceStable(a.args, func(i, j int) bool { + return f(a.args[i].key, a.args[j].key) == -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 6d32245..1a63aad 100644 --- a/args_test.go +++ b/args_test.go @@ -101,6 +101,22 @@ func TestArgsAdd(t *testing.T) { } } +func TestArgsSortKeys(t *testing.T) { + t.Parallel() + + var a Args + a.Add("a", "789") + a.Add("b", "456") + a.Add("a", "123") + a.SortKeys(bytes.Compare) + + s := a.String() + expectedS := "a=789&a=123&b=456" + if s != expectedS { + t.Fatalf("unexpected result: %q. Expecting %q", s, expectedS) + } +} + func TestArgsAcquireReleaseSequential(t *testing.T) { testArgsAcquireRelease(t) }