/src/serenity/AK/SegmentedVector.h
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2023, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com> |
3 | | * |
4 | | * SPDX-License-Identifier: BSD-2-Clause |
5 | | */ |
6 | | |
7 | | #pragma once |
8 | | |
9 | | #include <AK/OwnPtr.h> |
10 | | #include <AK/Vector.h> |
11 | | |
12 | | namespace AK { |
13 | | |
14 | | template<typename T, int segment_size = 512> |
15 | | class SegmentedVector { |
16 | | private: |
17 | | using VisibleType = RemoveReference<T>; |
18 | | static constexpr bool contains_reference = IsLvalueReference<T>; |
19 | | |
20 | | public: |
21 | 0 | SegmentedVector() = default; |
22 | | |
23 | 0 | size_t size() const { return m_size; } |
24 | | bool is_empty() const { return m_size == 0; } |
25 | | |
26 | | using Iterator = SimpleIterator<SegmentedVector, VisibleType>; |
27 | | |
28 | 0 | Iterator begin() { return Iterator::begin(*this); } |
29 | 0 | Iterator end() { return Iterator::end(*this); } |
30 | | |
31 | | ALWAYS_INLINE VisibleType const& at(size_t i) const |
32 | | { |
33 | | VERIFY(i < m_size); |
34 | | auto segment_index = i / segment_size; |
35 | | auto index_in_segment = i % segment_size; |
36 | | return m_segments[segment_index]->at(index_in_segment); |
37 | | } |
38 | | |
39 | | ALWAYS_INLINE VisibleType& at(size_t i) |
40 | 0 | { |
41 | 0 | VERIFY(i < m_size); |
42 | 0 | auto segment_index = i / segment_size; |
43 | 0 | auto index_in_segment = i % segment_size; |
44 | 0 | return m_segments[segment_index]->at(index_in_segment); |
45 | 0 | } |
46 | | |
47 | | ALWAYS_INLINE VisibleType const& operator[](size_t i) const { return at(i); } |
48 | 0 | ALWAYS_INLINE VisibleType& operator[](size_t i) { return at(i); } |
49 | | |
50 | | void append(T&& value) |
51 | 0 | { |
52 | 0 | if (m_segments.is_empty() || m_segments.last()->size() >= segment_size) |
53 | 0 | m_segments.append(make<Vector<T, segment_size>>()); |
54 | |
|
55 | | if constexpr (contains_reference) { |
56 | | m_segments.last()->append(value); |
57 | 0 | } else { |
58 | 0 | m_segments.last()->append(move(value)); |
59 | 0 | } |
60 | 0 | ++m_size; |
61 | 0 | } |
62 | | |
63 | | private: |
64 | | Vector<NonnullOwnPtr<Vector<T, segment_size>>> m_segments; |
65 | | size_t m_size { 0 }; |
66 | | }; |
67 | | |
68 | | } |