| 1 | // Copyright (C) 2018 Crimson AS <info@crimson.no> |
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | // |
| 5 | // W A R N I N G |
| 6 | // ------------- |
| 7 | // |
| 8 | // This file is not part of the Qt API. It exists purely as an |
| 9 | // implementation detail. This header file may change from version to |
| 10 | // version without notice, or even be removed. |
| 11 | // |
| 12 | // We mean it. |
| 13 | // |
| 14 | |
| 15 | #ifndef QV4ESTABLE_P_H |
| 16 | #define QV4ESTABLE_P_H |
| 17 | |
| 18 | #include <vector> |
| 19 | #include <limits> |
| 20 | |
| 21 | #include <QtCore/q20vector.h> |
| 22 | |
| 23 | #include "qv4value_p.h" |
| 24 | |
| 25 | class tst_qv4estable; |
| 26 | |
| 27 | QT_BEGIN_NAMESPACE |
| 28 | |
| 29 | namespace QV4 { |
| 30 | |
| 31 | class Q_AUTOTEST_EXPORT ESTable |
| 32 | { |
| 33 | public: |
| 34 | // Can be used to observe changes in the position of the element at index pivot by registering an instance |
| 35 | // with `observeShifts`. |
| 36 | // This is used by implementations of `forEach`, for `ESTable` |
| 37 | // backed collections, to respect the correct order of iteration |
| 38 | // in the face of a `callbackFn` that mutates the collection |
| 39 | // itself. |
| 40 | struct ShiftObserver { |
| 41 | static constexpr uint OUT_OF_TABLE = std::numeric_limits<uint>::max(); |
| 42 | |
| 43 | uint pivot = 0; |
| 44 | |
| 45 | void next() { |
| 46 | pivot = pivot == OUT_OF_TABLE ? 0 : pivot + 1; |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | public: |
| 51 | ESTable(); |
| 52 | ~ESTable(); |
| 53 | |
| 54 | void markObjects(MarkStack *s, bool isWeakMap); |
| 55 | void clear(); |
| 56 | void set(const Value &k, const Value &v); |
| 57 | bool has(const Value &k) const; |
| 58 | ReturnedValue get(const Value &k, bool *hasValue = nullptr) const; |
| 59 | bool remove(const Value &k); |
| 60 | uint size() const; |
| 61 | void iterate(uint idx, Value *k, Value *v); |
| 62 | |
| 63 | void removeUnmarkedKeys(); |
| 64 | |
| 65 | inline void observeShifts(ShiftObserver& observer) { |
| 66 | if (std::find(first: m_observers.cbegin(), last: m_observers.cend(), val: &observer) == m_observers.cend()) |
| 67 | m_observers.push_back(x: &observer); |
| 68 | } |
| 69 | inline void stopObservingShifts(ShiftObserver& observer) { |
| 70 | q20::erase(c&: m_observers, value: &observer); |
| 71 | } |
| 72 | |
| 73 | private: |
| 74 | friend class ::tst_qv4estable; |
| 75 | |
| 76 | Value *m_keys = nullptr; |
| 77 | Value *m_values = nullptr; |
| 78 | uint m_size = 0; |
| 79 | uint m_capacity = 0; |
| 80 | |
| 81 | std::vector<ShiftObserver*> m_observers; |
| 82 | }; |
| 83 | |
| 84 | } // namespace QV4 |
| 85 | |
| 86 | QT_END_NAMESPACE |
| 87 | |
| 88 | #endif |
| 89 | |