blob: 5fa0825b633f2c4c17c57995dd1b53d372b81a57 (
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
/// Utilities for iterating over a collection or selection
/// of multiple items.
#pragma once
#include <QList>
#include <QVector>
#include "util/assert.h"
namespace mixxx {
/// A generic iterator interface.
///
/// The iterator needs to be resettable to allow repeated application.
template<typename T>
class ItemIterator {
public:
virtual ~ItemIterator() = default;
/// Resets the iterator to the first position before starting a
/// new iteration.
///
/// This operation should be invoked regardless
/// either if the iterator has been newly created or already
/// been used for an preceding iteration.
virtual void reset() = 0;
/// Returns a best-effort guess of the number of items that
/// are remaining for the iteration or std::nullopt if unknown.
virtual std::optional<int> estimateItemsRemaining() = 0;
/// Returns the next item or std::nullopt when done.
virtual std::optional<T> nextItem() = 0;
};
/// Generic class for iterating over an indexed Qt collection
/// of known size.
template<typename T>
class IndexedCollectionIterator final
: public virtual ItemIterator<typename T::value_type> {
public:
explicit IndexedCollectionIterator(
const T& itemCollection)
: m_itemCollection(itemCollection),
m_nextIndex(0) {
}
~IndexedCollectionIterator() override = default;
void reset() override {
m_nextIndex = 0;
}
std::optional<int> estimateItemsRemaining() override {
DEBUG_ASSERT(m_nextIndex <= m_itemCollection.size());
return std::make_optional(
m_itemCollection.size() - m_nextIndex);
}
std::optional<typename T::value_type> nextItem() override {
DEBUG_ASSERT(m_nextIndex <= m_itemCollection.size());
if (m_nextIndex < m_itemCollection.size()) {
return std::make_optional(m_itemCollection[m_nextIndex++]);
} else {
return std::nullopt;
}
}
private:
const T m_itemCollection;
int m_nextIndex;
};
/// Generic class for iterating over QList.
template<typename T>
using ListItemIterator = IndexedCollectionIterator<QList<T>>;
/// Generic class for iterating over QVector.
template<typename T>
using VectorItemIterator = IndexedCollectionIterator<QVector<T>>;
} // namespace mixxx
|