mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-06-11 02:13:56 +09:00
AK: Add a simple Queue<T> class.
The underlying data structure is a singly-linked list of Vector<T>. We never shift any of the vector contents around, but we batch the memory allocations into 1000-element segments.
This commit is contained in:
parent
9443957c14
commit
c699d9d79d
Notes:
sideshowbarker
2024-07-19 13:36:11 +09:00
Author: https://github.com/awesomekling
Commit: c699d9d79d
4 changed files with 87 additions and 4 deletions
49
AK/Queue.h
Normal file
49
AK/Queue.h
Normal file
|
@ -0,0 +1,49 @@
|
|||
#pragma once
|
||||
|
||||
#include <AK/OwnPtr.h>
|
||||
#include <AK/SinglyLinkedList.h>
|
||||
#include <AK/Vector.h>
|
||||
|
||||
namespace AK {
|
||||
|
||||
template<typename T>
|
||||
class Queue {
|
||||
public:
|
||||
Queue() { }
|
||||
~Queue() { }
|
||||
|
||||
int size() const { return m_size; }
|
||||
bool is_empty() const { return m_size == 0; }
|
||||
|
||||
void enqueue(T&& value)
|
||||
{
|
||||
if (m_segments.is_empty() || m_segments.last()->size() >= segment_size)
|
||||
m_segments.append(make<Vector<T, segment_size>>());
|
||||
m_segments.last()->append(move(value));
|
||||
++m_size;
|
||||
}
|
||||
|
||||
T dequeue()
|
||||
{
|
||||
ASSERT(!is_empty());
|
||||
auto value = move((*m_segments.first())[m_index_into_first++]);
|
||||
if (m_index_into_first == segment_size) {
|
||||
m_segments.take_first();
|
||||
m_index_into_first = 0;
|
||||
}
|
||||
--m_size;
|
||||
return value;
|
||||
}
|
||||
|
||||
private:
|
||||
static const int segment_size = 1000;
|
||||
|
||||
SinglyLinkedList<OwnPtr<Vector<T, segment_size>>> m_segments;
|
||||
int m_index_into_first { 0 };
|
||||
int m_size { 0 };
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
using AK::Queue;
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue