Skip to content

Commit

Permalink
Add tests to lib/support/SortUtils.h (#32421)
Browse files Browse the repository at this point in the history
* Add tests to lib/support/SortUtils.h

- SortUtils.h has no tests. While it is apparently trivial,
  we should never have code that has no tests
- BubbleSort could crash (never-ending loop due to integer overflow)
  when input size was < 2. Its use is removed and replaced by InsertionSort
  which is known to be faster on average. A better solution is to move
  to using STL sorts in the future, but this requires analysis of flash
  costs and STL usage, given lambdas are used with sorts many places.

Fixes #32420

Testing done:
- Added missing unit tests.
- All integration tests still pass.

* Restyled by clang-format

* Fix build error on Android

* Add constness to operator==

---------

Co-authored-by: Restyled.io <[email protected]>
Co-authored-by: Andrei Litvin <[email protected]>
  • Loading branch information
3 people authored and pull[bot] committed Jun 5, 2024
1 parent 22e84f2 commit 2357644
Show file tree
Hide file tree
Showing 6 changed files with 178 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SortUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/RuntimeOptionsProvider.h>
Expand Down
14 changes: 7 additions & 7 deletions src/lib/dnssd/IPAddressSorter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace IPAddressSorter {

void Sort(Inet::IPAddress * addresses, size_t count, Inet::InterfaceId interfaceId)
{
Sorting::BubbleSort(addresses, count, [interfaceId](const Inet::IPAddress & a, const Inet::IPAddress & b) -> bool {
Sorting::InsertionSort(addresses, count, [interfaceId](const Inet::IPAddress & a, const Inet::IPAddress & b) -> bool {
auto scoreA = to_underlying(ScoreIpAddress(a, interfaceId));
auto scoreB = to_underlying(ScoreIpAddress(b, interfaceId));
return scoreA > scoreB;
Expand All @@ -33,12 +33,12 @@ void Sort(Inet::IPAddress * addresses, size_t count, Inet::InterfaceId interface

void Sort(const Span<Inet::IPAddress> & addresses, Inet::InterfaceId interfaceId)
{
Sorting::BubbleSort(addresses.begin(), addresses.size(),
[interfaceId](const Inet::IPAddress & a, const Inet::IPAddress & b) -> bool {
auto scoreA = to_underlying(ScoreIpAddress(a, interfaceId));
auto scoreB = to_underlying(ScoreIpAddress(b, interfaceId));
return scoreA > scoreB;
});
Sorting::InsertionSort(addresses.data(), addresses.size(),
[interfaceId](const Inet::IPAddress & a, const Inet::IPAddress & b) -> bool {
auto scoreA = to_underlying(ScoreIpAddress(a, interfaceId));
auto scoreB = to_underlying(ScoreIpAddress(b, interfaceId));
return scoreA > scoreB;
});
}

IpScore ScoreIpAddress(const Inet::IPAddress & ip, Inet::InterfaceId interfaceId)
Expand Down
40 changes: 0 additions & 40 deletions src/lib/support/SortUtils.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,46 +26,6 @@
namespace chip {
namespace Sorting {

/**
*
* Impements the bubble sort algorithm to sort an array
* of items of size 'n'.
*
* T should be swappable using std::swap (i.e implements Swappable).
*
* The provided comparison function SHALL have the following signature:
*
* bool Compare(const T& a, const T& b);
*
* If a is deemed less than (i.e is ordered before) b, return true.
* Else, return false.
*
* This is a stable sort.
*
* NOTE: This has a worst case time complexity of O(n^2). This
* is well-suited for small arrays where the time trade-off is
* acceptable compared to the lower flash cost for the simple sorting
* implementation.
*
*/
template <typename T, typename CompareFunc>
void BubbleSort(T * items, size_t n, CompareFunc f)
{
for (size_t i = 0; i < (n - 1); i++)
{
for (size_t j = 0; j < (n - i - 1); j++)
{
const T & a = items[j + 1];
const T & b = items[j];

if (f(a, b))
{
std::swap(items[j], items[j + 1]);
}
}
}
}

/**
*
* Impements the insertion sort algorithm to sort an array
Expand Down
1 change: 1 addition & 0 deletions src/lib/support/tests/BUILD.gn
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ chip_test_suite_using_nltest("tests") {
"TestSafeString.cpp",
"TestScoped.cpp",
"TestScopedBuffer.cpp",
"TestSorting.cpp",
"TestSpan.cpp",
"TestStateMachine.cpp",
"TestStaticSupportSmartPtr.cpp",
Expand Down
169 changes: 169 additions & 0 deletions src/lib/support/tests/TestSorting.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/*
*
* Copyright (c) 2024 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <algorithm>
#include <array>
#include <stdio.h>

#include <lib/support/SortUtils.h>
#include <lib/support/Span.h>

#include <lib/support/UnitTestRegistration.h>
#include <nlunit-test.h>

using namespace chip;
using namespace chip::Sorting;

namespace {

struct Datum
{
// Key is the element that takes part in sorting.
int key;
// The associated data is constructed to detect stable sort.
int associated_data;

bool operator==(const Datum & other) const
{
return (this == &other) || ((this->key == other.key) && (this->associated_data == other.associated_data));
}
};

class Sorter
{
public:
virtual ~Sorter() = default;

void Reset() { m_compare_count = 0; }

size_t compare_count() const { return m_compare_count; }

virtual void Sort(chip::Span<Datum> data) = 0;

protected:
size_t m_compare_count = 0;
};

class InsertionSorter : public Sorter
{
public:
void Sort(chip::Span<Datum> data)
{
InsertionSort(data.data(), data.size(), [&](const Datum & a, const Datum & b) -> bool {
++m_compare_count;
return a.key < b.key;
});
}
};

void DoBasicSortTest(nlTestSuite * inSuite, Sorter & sorter)
{
Span<Datum> empty_to_sort;
Span<Datum> empty_expected;

std::array<Datum, 1> single_entry_to_sort{ { { 1, 100 } } };
std::array<Datum, 1> single_entry_expected{ { { 1, 100 } } };

std::array<Datum, 2> two_entries_to_sort{ { { 2, 200 }, { 1, 100 } } };
std::array<Datum, 2> two_entries_expected{ { { 1, 100 }, { 2, 200 } } };

std::array<Datum, 20> random_order_to_sort{ { { 1, 100 }, { 10, 1000 }, { 2, 200 }, { 13, 1300 }, { 4, 400 },
{ 8, 800 }, { 10, 1001 }, { 6, 600 }, { 7, 700 }, { 7, 701 },
{ 6, 601 }, { 6, 602 }, { 6, 603 }, { 8, 801 }, { 14, 1400 },
{ 6, 604 }, { 10, 1002 }, { 12, 1200 }, { 4, 401 }, { 2, 201 } } };

std::array<Datum, 20> random_order_expected{ { { 1, 100 }, { 2, 200 }, { 2, 201 }, { 4, 400 }, { 4, 401 },
{ 6, 600 }, { 6, 601 }, { 6, 602 }, { 6, 603 }, { 6, 604 },
{ 7, 700 }, { 7, 701 }, { 8, 800 }, { 8, 801 }, { 10, 1000 },
{ 10, 1001 }, { 10, 1002 }, { 12, 1200 }, { 13, 1300 }, { 14, 1400 } } };

std::array<Datum, 20> reverse_order_to_sort{ { { 20, 2000 }, { 19, 1900 }, { 18, 1800 }, { 17, 1700 }, { 16, 1600 },
{ 15, 1500 }, { 14, 1400 }, { 13, 1300 }, { 12, 1200 }, { 11, 1100 },
{ 10, 1000 }, { 9, 900 }, { 8, 800 }, { 7, 700 }, { 6, 600 },
{ 5, 500 }, { 4, 400 }, { 3, 300 }, { 2, 200 }, { 1, 100 } } };

std::array<Datum, 20> reverse_order_expected{ { { 1, 100 }, { 2, 200 }, { 3, 300 }, { 4, 400 }, { 5, 500 },
{ 6, 600 }, { 7, 700 }, { 8, 800 }, { 9, 900 }, { 10, 1000 },
{ 11, 1100 }, { 12, 1200 }, { 13, 1300 }, { 14, 1400 }, { 15, 1500 },
{ 16, 1600 }, { 17, 1700 }, { 18, 1800 }, { 19, 1900 }, { 20, 2000 } } };

std::array<Span<Datum>, 5> inputs = { { empty_to_sort, Span<Datum>(single_entry_to_sort), Span<Datum>(two_entries_to_sort),
Span<Datum>(random_order_to_sort), Span<Datum>(reverse_order_to_sort) } };
std::array<Span<Datum>, 5> expected_outs = { { empty_expected, Span<Datum>(single_entry_expected),
Span<Datum>(two_entries_expected), Span<Datum>(random_order_expected),
Span<Datum>(reverse_order_expected) } };

for (size_t case_idx = 0; case_idx < inputs.size(); ++case_idx)
{
printf("Case index: %d\n", static_cast<int>(case_idx));
auto & to_sort = inputs[case_idx];
const auto & expected = expected_outs[case_idx];

sorter.Sort(to_sort);
NL_TEST_ASSERT(inSuite, to_sort.data_equal(expected));
if (!to_sort.data_equal(expected))
{
for (size_t idx = 0; idx < to_sort.size(); ++idx)
{
Datum sorted_item = to_sort[idx];
Datum expected_item = expected[idx];
printf("Index: %d, got { %d, %d }, expected { %d, %d }\n", static_cast<int>(idx), sorted_item.key,
sorted_item.associated_data, expected_item.key, expected_item.associated_data);
}
}
NL_TEST_ASSERT(inSuite, sorter.compare_count() <= (to_sort.size() * to_sort.size()));
printf("Compare counts: %d\n", static_cast<int>(sorter.compare_count()));
sorter.Reset();
}
}

void TestBasicSort(nlTestSuite * inSuite, void * inContext)
{
printf("Testing insertion sorter.\n");
InsertionSorter insertion_sorter;
DoBasicSortTest(inSuite, insertion_sorter);
}

// clang-format off
static const nlTest sTests[] =
{
NL_TEST_DEF("Basic sort tests for custom sort utilities", TestBasicSort),
NL_TEST_SENTINEL()
};
// clang-format on

} // namespace

int TestSortUtils()
{
// clang-format off
nlTestSuite theSuite =
{
"Test for SortUtils",
&sTests[0],
nullptr,
nullptr
};
// clang-format on

nlTestRunner(&theSuite, nullptr);

return (nlTestRunnerStats(&theSuite));
}

CHIP_REGISTER_TEST_SUITE(TestSortUtils)
2 changes: 1 addition & 1 deletion src/transport/SecureSessionTable.h
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class SecureSessionTable
template <typename CompareFunc>
void Sort(CompareFunc func)
{
Sorting::BubbleSort(mSessionList.begin(), mSessionList.size(), func);
Sorting::InsertionSort(mSessionList.begin(), mSessionList.size(), func);
}

const ScopedNodeId & GetSessionEvictionHint() const { return mSessionEvictionHint; }
Expand Down

0 comments on commit 2357644

Please sign in to comment.