mirror of
https://github.com/SerenityOS/serenity
synced 2024-11-05 17:46:52 +00:00
e0ab7763da
Using policy based design `SinglyLinkedList` and `SinglyLinkedListWithCount` can be combined into one class which takes a policy to determine how to keep track of the size of the list. The default policy is to use list iteration to count the items in the list each time. The `WithCount` form is a different policy which tracks the size, but comes with the overhead of storing the count and incrementing/decrementing on each modification. This model is extensible to have other forms of counting by implementing only a new policy instead of implementing a totally new type.
47 lines
940 B
C++
47 lines
940 B
C++
/*
|
|
* Copyright (c) 2022, the SerenityOS developers.
|
|
*
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include <AK/Types.h>
|
|
|
|
namespace AK {
|
|
|
|
struct DefaultSizeCalculationPolicy {
|
|
constexpr void increase_size(auto const&) { }
|
|
|
|
constexpr void decrease_size(auto const&) { }
|
|
|
|
constexpr void reset() { }
|
|
|
|
constexpr size_t size(auto const* head) const
|
|
{
|
|
size_t size = 0;
|
|
for (auto* node = head; node; node = node->next)
|
|
++size;
|
|
return size;
|
|
}
|
|
};
|
|
|
|
struct CountingSizeCalculationPolicy {
|
|
constexpr void increase_size(auto const&) { ++m_size; }
|
|
|
|
constexpr void decrease_size(auto const&) { --m_size; }
|
|
|
|
constexpr void reset() { m_size = 0; }
|
|
|
|
constexpr size_t size(auto const*) const { return m_size; }
|
|
|
|
private:
|
|
size_t m_size { 0 };
|
|
};
|
|
|
|
}
|
|
|
|
#ifdef USING_AK_GLOBALLY
|
|
using AK::CountingSizeCalculationPolicy;
|
|
using AK::DefaultSizeCalculationPolicy;
|
|
#endif
|