|
| 1 | +// Copyright 2021 FerretDB Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package common |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "testing" |
| 20 | + |
| 21 | + "github.com/stretchr/testify/assert" |
| 22 | + "github.com/stretchr/testify/require" |
| 23 | + |
| 24 | + "github.com/FerretDB/FerretDB/internal/types" |
| 25 | + "github.com/FerretDB/FerretDB/internal/util/must" |
| 26 | +) |
| 27 | + |
| 28 | +func TestSortAndDeduplicateDistinctValues(t *testing.T) { |
| 29 | + t.Parallel() |
| 30 | + |
| 31 | + doc := must.NotFail(types.NewDocument("x", int32(1))) |
| 32 | + array := must.NotFail(types.NewArray("nested")) |
| 33 | + values := must.NotFail(types.NewArray( |
| 34 | + "b", int32(1), doc, "a", types.Null, array, |
| 35 | + "a", int64(1), doc.DeepCopy(), types.Null, array.DeepCopy(), |
| 36 | + )) |
| 37 | + |
| 38 | + actual := sortAndDeduplicateDistinctValues(values) |
| 39 | + require.Equal(t, 6, actual.Len()) |
| 40 | + |
| 41 | + expected := []any{types.Null, int32(1), "a", "b", doc, array} |
| 42 | + for _, value := range expected { |
| 43 | + matches := 0 |
| 44 | + for i := 0; i < actual.Len(); i++ { |
| 45 | + if types.Compare(must.NotFail(actual.Get(i)), value) == types.Equal { |
| 46 | + matches++ |
| 47 | + } |
| 48 | + } |
| 49 | + assert.Equal(t, 1, matches, "value %v must occur exactly once", value) |
| 50 | + } |
| 51 | + |
| 52 | + for i := 1; i < actual.Len(); i++ { |
| 53 | + assert.NotEqual(t, types.Greater, types.CompareOrderForSort( |
| 54 | + must.NotFail(actual.Get(i-1)), must.NotFail(actual.Get(i)), types.Ascending, |
| 55 | + )) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func BenchmarkSortAndDeduplicateDistinctValues(b *testing.B) { |
| 60 | + const values = 45640 |
| 61 | + input := make([]string, values) |
| 62 | + for i := range input { |
| 63 | + input[i] = fmt.Sprintf("%024d", values-i) |
| 64 | + } |
| 65 | + |
| 66 | + b.ReportAllocs() |
| 67 | + b.ResetTimer() |
| 68 | + for i := 0; i < b.N; i++ { |
| 69 | + array := types.MakeArray(values) |
| 70 | + for _, value := range input { |
| 71 | + array.Append(value) |
| 72 | + } |
| 73 | + if got := sortAndDeduplicateDistinctValues(array); got.Len() != values { |
| 74 | + b.Fatalf("got %d values", got.Len()) |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments