blob: 5bfa454dd035d5e4af3985182f14c48a6181b850 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/OwnPtr.h>
#include <AK/SinglyLinkedList.h>
#include <AK/Vector.h>
namespace AK {
template<typename T, int segment_size = 1000>
class Queue {
public:
Queue() = default;
~Queue() = default;
size_t size() const { return m_size; }
bool is_empty() const { return m_size == 0; }
template<typename U = T>
void enqueue(U&& value)
{
if (m_segments.is_empty() || m_segments.last()->size() >= segment_size)
m_segments.append(make<Vector<T, segment_size>>());
m_segments.last()->append(forward<U>(value));
++m_size;
}
T dequeue()
{
VERIFY(!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;
}
const T& head() const
{
VERIFY(!is_empty());
return (*m_segments.first())[m_index_into_first];
}
void clear()
{
m_segments.clear();
m_index_into_first = 0;
m_size = 0;
}
private:
SinglyLinkedList<OwnPtr<Vector<T, segment_size>>> m_segments;
size_t m_index_into_first { 0 };
size_t m_size { 0 };
};
}
using AK::Queue;
|