mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-06-09 09:34:57 +09:00
AK: Combine SinglyLinkedList and SinglyLinkedListWithCount
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.
This commit is contained in:
parent
0105600120
commit
e0ab7763da
Notes:
sideshowbarker
2024-07-17 03:25:24 +09:00
Author: https://github.com/ldm5180
Commit: e0ab7763da
Pull-request: https://github.com/SerenityOS/serenity/pull/16575
Reviewed-by: https://github.com/ADKaster ✅
6 changed files with 183 additions and 156 deletions
47
AK/SinglyLinkedListSizePolicy.h
Normal file
47
AK/SinglyLinkedListSizePolicy.h
Normal file
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* 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
|
Loading…
Add table
Add a link
Reference in a new issue