swift
Loading...
Searching...
No Matches
dictionary.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#ifndef SWIFT_MISC_DICTIONARY_H
7#define SWIFT_MISC_DICTIONARY_H
8
9#include <algorithm>
10#include <initializer_list>
11#include <type_traits>
12#include <utility>
13
14#include <QDBusArgument>
15#include <QHash>
16#include <QJsonArray>
17#include <QJsonObject>
18#include <QJsonValue>
19#include <QJsonValueRef>
20#include <QMap>
21#include <QString>
22#include <QtGlobal>
23
24#include "misc/containerbase.h"
25#include "misc/iterator.h"
26#include "misc/jsonexception.h"
31#include "misc/predicates.h"
32#include "misc/range.h"
33#include "misc/typetraits.h"
34
35namespace swift::misc
36{
37 namespace private_ns
38 {
40 template <bool KeySupportsQHash /* = true */, bool KeySupportsQMap>
41 struct TAssociativityTraits
42 {
43 template <class Key, class Value>
44 using DefaultType = QHash<Key, Value>;
45 };
46 template <>
47 struct TAssociativityTraits<false, true>
48 {
49 template <class Key, class Value>
50 using DefaultType = QMap<Key, Value>;
51 };
52 template <>
53 struct TAssociativityTraits<false, false>
54 {
55 template <class Key, class>
56 struct DefaultType
57 {
58 static_assert(std::is_void_v<Key>, "Key does not support either QHash or QMap");
59 };
60 };
62 } // namespace private_ns
63
67 template <typename K, typename V>
69 typename private_ns::TAssociativityTraits<TModelsQHashKey<K>::value,
70 TModelsQMapKey<K>::value>::template DefaultType<K, V>;
71
75 template <class Key, class Value, template <class...> class Impl = TDefaultAssociativeType>
77 public mixin::DBusOperators<CDictionary<Key, Value, Impl>>,
78 public mixin::DataStreamOperators<CDictionary<Key, Value, Impl>>,
79 public mixin::JsonOperators<CDictionary<Key, Value, Impl>>,
80 public mixin::String<CDictionary<Key, Value, Impl>>
81 {
83 friend int compare(const CDictionary &a, const CDictionary &b)
84 {
85 if (a.m_impl.size() < b.m_impl.size())
86 {
87 return -1;
88 }
89 if (a.m_impl.size() > b.m_impl.size())
90 {
91 return 1;
92 }
93 return 0;
94 }
95
96 public:
98 using impl_type = Impl<Key, Value>;
99
101 using key_type = Key;
102
104 using value_type = Value;
105
107 using reference = Value &;
108
110 using const_reference = Value &;
111
113 using size_type = typename Impl<Key, Value>::size_type;
114
116 using iterator = typename Impl<Key, Value>::iterator;
117
119 using const_iterator = typename Impl<Key, Value>::const_iterator;
120
123 template <class Predicate>
124 CDictionary findKeyBy(Predicate p) const
125 {
126 CDictionary result = *this;
127 for (auto it = result.begin(); it != result.end();)
128 {
129 if (!p(it.key()))
130 {
131 it = result.erase(it);
132 }
133 else
134 {
135 ++it;
136 }
137 }
138 return result;
139 }
140
143 template <class... Pairs>
144 CDictionary findKeyBy(Pairs... pairs) const
145 {
147 }
148
150 template <class Predicate>
151 CDictionary findValueBy(Predicate p) const
152 {
153 CDictionary result = *this;
154 for (auto it = result.begin(); it != result.end();)
155 {
156 if (!p(it.value()))
157 {
158 it = result.erase(it);
159 }
160 else
161 {
162 ++it;
163 }
164 }
165 return result;
166 }
167
170 template <class... Pairs>
171 CDictionary findValueBy(Pairs... pairs) const
172 {
174 }
175
177 template <class Predicate>
178 bool containsByKey(Predicate p) const
179 {
180 auto keys = m_impl.keys();
181 return std::any_of(keys.cbegin(), keys.cend(), p);
182 }
183
185 template <class MembFunc, class ReturnValue>
186 bool containsByKey(MembFunc membFunc, ReturnValue returnValue) const
187 {
188 return containsByKey(swift::misc::predicates::MemberEqual(membFunc, returnValue));
189 }
190
192 template <class Predicate>
193 bool containsByValue(Predicate p) const
194 {
195 return std::any_of(m_impl.cbegin(), m_impl.cend(), p);
196 }
197
199 template <class MembFunc, class ReturnValue>
200 bool containsByValue(MembFunc membFunc, ReturnValue returnValue) const
201 {
202 return containsByValue(swift::misc::predicates::MemberEqual(membFunc, returnValue));
203 }
204
206 template <class Predicate>
207 void removeByKeyIf(Predicate p)
208 {
209 for (auto it = m_impl.begin(); it != m_impl.end();)
210 {
211 if (p(it.key()))
212 {
213 it = m_impl.erase(it);
214 }
215 else
216 {
217 ++it;
218 }
219 }
220 }
221
223 template <class Predicate>
224 void removeByValueIf(Predicate p)
225 {
226 for (auto it = m_impl.begin(); it != m_impl.end();)
227 {
228 if (p(it.value()))
229 {
230 it = m_impl.erase(it);
231 }
232 else
233 {
234 ++it;
235 }
236 }
237 }
238
240 template <class MembFunc, class ReturnValue>
241 void removeByKeyIf(MembFunc membFunc, ReturnValue returnValue)
242 {
244 }
245
247 template <class MembFunc, class ReturnValue>
248 void removeByValueIf(MembFunc membFunc, ReturnValue returnValue)
249 {
251 }
252
254 void removeDuplicates(const CDictionary &other)
255 {
256 for (auto it = begin(); it != end();)
257 {
258 auto it2 = other.find(it.key());
259 if (it2 != other.end() && it.value() == it2.value())
260 {
261 it = erase(it);
262 }
263 else
264 {
265 ++it;
266 }
267 }
268 }
269
272 {
273 QJsonArray array;
274 QJsonObject json;
275
276 for (auto it = m_impl.cbegin(); it != m_impl.cend(); ++it)
277 {
278 array << it.key() << it.value();
279 }
280 json.insert("associativecontainerbase", array);
281 return json;
282 }
283
285 void convertFromJson(const QJsonObject &json)
286 {
287 QJsonValue value = json.value("associativecontainerbase");
288 if (value.isUndefined())
289 {
290 throw CJsonException("Missing 'associativecontainerbase'");
291 }
292 QJsonArray array = value.toArray();
293 int index = 0;
294 for (auto it = array.begin(); it != array.end(); ++it)
295 {
296 QJsonValueRef jsonKey = (*it);
297 ++it;
298 if (it == array.end())
299 {
300 qWarning("Odd number of elements in CDictionary::convertFromJson");
301 return;
302 }
303 QJsonValueRef jsonValue = (*it);
304 Key key;
305 Value val;
306 {
307 CJsonScope scope("associativecontainerbase", 2 * index);
308 Q_UNUSED(scope);
309 jsonKey >> key;
310 }
311 {
312 CJsonScope scope("associativecontainerbase", 2 * index++ + 1);
313 Q_UNUSED(scope);
314 jsonValue >> val;
315 }
316 m_impl.insert(std::move(key), std::move(val));
317 }
318 }
319
321 CDictionary() = default;
322
324 CDictionary(std::initializer_list<std::pair<Key, Value>> il) : m_impl(il) {}
325
327 CDictionary(const CDictionary &) = default;
328
330 CDictionary(CDictionary &&other) noexcept : m_impl(std::move(other.m_impl)) {}
331
333 ~CDictionary() = default;
334
336 iterator begin() { return m_impl.begin(); }
337
339 const_iterator begin() const { return m_impl.begin(); }
340
342 const_iterator cbegin() const { return m_impl.cbegin(); }
343
345 iterator end() { return m_impl.end(); }
346
348 const_iterator end() const { return m_impl.end(); }
349
351 const_iterator cend() const { return m_impl.cend(); }
352
354 auto keyBegin() const { return m_impl.keyBegin(); }
355
357 auto keyEnd() const { return m_impl.keyEnd(); }
358
360 auto keyValueBegin() { return m_impl.keyValueBegin(); }
361
363 auto keyValueEnd() { return m_impl.keyValueEnd(); }
364
366 auto keyValueBegin() const { return m_impl.keyValueBegin(); }
367
369 auto constKeyValueBegin() const { return m_impl.constKeyValueBegin(); }
370
372 auto keyValueEnd() const { return m_impl.keyValueEnd(); }
373
375 auto constKeyValueEnd() const { return m_impl.constKeyValueEnd(); }
376
378 void clear() { m_impl.clear(); }
379
381 const_iterator constBegin() const { return m_impl.constBegin(); }
382
384 const_iterator constEnd() const { return m_impl.constEnd(); }
385
388 const_iterator constFind(const Key &key) const { return m_impl.constFind(key); }
389
392 const_iterator find(const Key &key) const { return m_impl.find(key); }
393
396 iterator find(const Key &key) { return m_impl.find(key); }
397
399 bool contains(const Key &key) const { return m_impl.contains(key); }
400
402 int count(const Key &key) const { return m_impl.count(key); }
403
405 int count() const { return m_impl.count(); }
406
408 bool empty() const { return m_impl.empty(); }
409
411 iterator erase(iterator pos) { return m_impl.erase(pos); }
412
414 iterator insert(const Key &key, const Value &value) { return m_impl.insert(key, value); }
415
417 void insert(const CDictionary &other)
418 {
419 for (auto i = other.cbegin(); i != other.cend(); ++i)
420 {
421 insert(i.key(), i.value());
422 }
423 }
424
426 bool isEmpty() const { return m_impl.isEmpty(); }
427
429 const Key key(const Value &value) const { return m_impl.key(value); }
430
432 const Key key(const Value &value, const Key &defaultKey) const { return m_impl.key(value, defaultKey); }
433
435 auto keys() const { return makeRange(keyBegin(), keyEnd()); }
436
438 int remove(const Key &key) { return m_impl.remove(key); }
439
441 int size() const { return m_impl.size(); }
442
444 void swap(CDictionary &other) noexcept { m_impl.swap(other.m_impl); }
445
447 const Value value(const Key &key) const { return m_impl.value(key); }
448
450 const Value value(const Key &key, const Value &defaultValue) const { return m_impl.value(key, defaultValue); }
451
454
457 {
458 m_impl = other.m_impl;
459 return *this;
460 }
461
464 {
465 m_impl = std::move(other.m_impl);
466 return *this;
467 }
468
470 friend impl_type &implementationOf(CDictionary &dict) { return dict.m_impl; }
471
473 friend const impl_type &implementationOf(const CDictionary &dict) { return dict.m_impl; }
474
477 Value &operator[](const Key &key) { return m_impl[key]; }
478
480 const Value operator[](const Key &key) const { return m_impl[key]; }
481
483 friend bool operator==(const CDictionary &a, const CDictionary &b) { return a.m_impl == b.m_impl; }
484
486 friend bool operator!=(const CDictionary &a, const CDictionary &b) { return !(a == b); }
487
489 QString convertToQString(bool i18n = false) const
490 {
491 QString str;
492 for (auto it = m_impl.cbegin(); it != m_impl.end(); ++it)
493 {
494 str += "{";
495 str +=
496 CContainerHelper::stringify(it.key(), i18n) + "," + CContainerHelper::stringify(it.value(), i18n);
497 str += "}";
498 }
499 return "{" + str + "}";
500 }
501
502 public:
504 void marshallToDbus(QDBusArgument &argument) const { argument << m_impl; }
505
507 void unmarshallFromDbus(const QDBusArgument &argument) { argument >> m_impl; }
508
510 void marshalToDataStream(QDataStream &stream) const { stream << m_impl; }
511
513 void unmarshalFromDataStream(QDataStream &stream) { stream >> m_impl; }
514
515 private:
516 Impl<Key, Value> m_impl;
517 };
518
522 template <class Key, class Value>
524 {
525 return dict;
526 }
527
531 template <class Key, class Value>
533 {
534 return dict;
535 }
536
540 template <class Map1, class Map2, class F>
541 void forEachIntersection(const Map1 &map1, const Map2 &map2, F functor)
542 {
543 static_assert(std::is_same_v<typename Map1::key_type, typename Map2::key_type>,
544 "Maps must have the same key type");
545 if (map1.empty() || map2.empty())
546 {
547 return;
548 }
549 auto it1 = implementationOf(map1).lowerBound(map2.cbegin().key());
550 auto end1 = implementationOf(map1).upperBound(std::prev(map2.cend()).key());
551 auto it2 = implementationOf(map2).lowerBound(map1.cbegin().key());
552 auto end2 = implementationOf(map2).upperBound(std::prev(map1.cend()).key());
553 while (it1 != end1 && it2 != end2)
554 {
555 if (it1.key() < it2.key())
556 {
557 ++it1;
558 }
559 else if (it2.key() < it1.key())
560 {
561 ++it2;
562 }
563 else
564 {
565 functor(it1.key(), it1.value(), it2);
566 ++it1;
567 ++it2;
568 }
569 }
570 }
571} // namespace swift::misc
572
573#endif // SWIFT_MISC_DICTIONARY_H
static QString stringify(const U &obj, bool i18n)
Stringify value object.
int count(const Key &key) const
Returns the number of items with key.
Definition dictionary.h:402
void removeByKeyIf(Predicate p)
Remove elements for which a given predicate for value returns true.
Definition dictionary.h:207
CDictionary findValueBy(Predicate p) const
Return a copy containing only those elements for which a given predicate returns true.
Definition dictionary.h:151
void clear()
Removes all items from the dictionary.
Definition dictionary.h:378
const QString value(const QString &key) const
Definition dictionary.h:447
friend impl_type & implementationOf(CDictionary &dict)
Return reference to the internal implementation object.
Definition dictionary.h:470
CDictionary & operator=(const CDictionary &other)
Copy assignment.
Definition dictionary.h:456
typename QMap< QString, QString >::iterator iterator
Definition dictionary.h:116
~CDictionary()=default
Destructor.
void marshalToDataStream(QDataStream &stream) const
Marshal a value to a QDataStream.
Definition dictionary.h:510
const_iterator constEnd() const
Returns const iterator at the end of the dictionary.
Definition dictionary.h:384
CDictionary findValueBy(Pairs... pairs) const
Return a copy containing only those elements which value matches a particular pair.
Definition dictionary.h:171
CRange< const_iterator > values() const
Return a range of all values (does not allocate a temporary container).
Definition dictionary.h:453
auto keyEnd() const
Returns const iterator for iterating over keys.
Definition dictionary.h:357
friend const impl_type & implementationOf(const CDictionary &dict)
Return reference to the internal implementation object.
Definition dictionary.h:473
void convertFromJson(const QJsonObject &json)
Assign from JSON object.
Definition dictionary.h:285
friend bool operator==(const CDictionary &a, const CDictionary &b)
Test for equality.
Definition dictionary.h:483
void unmarshallFromDbus(const QDBusArgument &argument)
Unmarshall without begin/endStructure, for when composed within another object.
Definition dictionary.h:507
void marshallToDbus(QDBusArgument &argument) const
Marshall without begin/endStructure, for when composed within another object.
Definition dictionary.h:504
const_iterator end() const
Returns const iterator at the end of the dictionary.
Definition dictionary.h:348
int size() const
Returns the number of items in the hash.
Definition dictionary.h:441
const_iterator constBegin() const
Returns const iterator at the beginning of the dictionary.
Definition dictionary.h:381
friend int compare(const CDictionary &a, const CDictionary &b)
Return negative, zero, or positive if a is less than, equal to, or greater than b.
Definition dictionary.h:83
QJsonObject toJson() const
Cast to JSON object.
Definition dictionary.h:271
auto constKeyValueBegin() const
Returns const iterator for iterating over keys and values together.
Definition dictionary.h:369
auto keyValueBegin()
Returns iterator for iterating over keys and values together.
Definition dictionary.h:360
void insert(const CDictionary &other)
Insert all items of other dictionary into this dictionary.
Definition dictionary.h:417
Value & operator[](const Key &key)
Access an element by its key.
Definition dictionary.h:477
CDictionary findKeyBy(Pairs... pairs) const
Return a copy containing only those elements which key matches a particular pair.
Definition dictionary.h:144
auto keyValueBegin() const
Returns const iterator for iterating over keys and values together.
Definition dictionary.h:366
void removeDuplicates(const CDictionary &other)
Remove elements for which the same key/value pair is present in an other dictionary.
Definition dictionary.h:254
void removeByValueIf(MembFunc membFunc, ReturnValue returnValue)
Remove elements for which value matches a particular pair.
Definition dictionary.h:248
const Value value(const Key &key, const Value &defaultValue) const
Returns the value associated with the key or if key is not found defaultValue.
Definition dictionary.h:450
QString convertToQString(bool i18n=false) const
Cast as QString.
Definition dictionary.h:489
CDictionary findKeyBy(Predicate p) const
Return a copy containing only those elements for which the dictionary keys return true for a given pr...
Definition dictionary.h:124
const_iterator constFind(const Key &key) const
Returns an const iterator pointing to the item with the key.
Definition dictionary.h:388
auto keyValueEnd() const
Returns const iterator for iterating over keys and values together.
Definition dictionary.h:372
CDictionary(std::initializer_list< std::pair< Key, Value > > il)
Initializer list constructor.
Definition dictionary.h:324
iterator end()
Returns iterator at the end of the dictionary.
Definition dictionary.h:345
bool containsByValue(MembFunc membFunc, ReturnValue returnValue) const
Return true if there is an element which value matches a given pair.
Definition dictionary.h:200
const_iterator find(const Key &key) const
Returns an const iterator pointing to the item with the key.
Definition dictionary.h:392
auto keyBegin() const
Returns const iterator for iterating over keys.
Definition dictionary.h:354
int remove(const Key &key)
Remove all items with key from the dictionary.
Definition dictionary.h:438
friend bool operator!=(const CDictionary &a, const CDictionary &b)
Test for inequality.
Definition dictionary.h:486
const_iterator cbegin() const
Returns const iterator at the beginning of the dictionary.
Definition dictionary.h:342
bool isEmpty() const
Returns true if dictionary is empty.
Definition dictionary.h:426
auto keyValueEnd()
Returns iterator for iterating over keys and values together.
Definition dictionary.h:363
const_iterator begin() const
Returns const iterator at the beginning of the dictionary.
Definition dictionary.h:339
CDictionary(CDictionary &&other) noexcept
Move constructor.
Definition dictionary.h:330
auto constKeyValueEnd() const
Returns const iterator for iterating over keys and values together.
Definition dictionary.h:375
iterator insert(const Key &key, const Value &value)
Insert new item with key and value.
Definition dictionary.h:414
void removeByValueIf(Predicate p)
Remove elements for which a given predicate for key returns true.
Definition dictionary.h:224
bool empty() const
Returns true if the.
Definition dictionary.h:408
const Value operator[](const Key &key) const
Access an element by its key.
Definition dictionary.h:480
typename QMap< QString, QString >::const_iterator const_iterator
Definition dictionary.h:119
void unmarshalFromDataStream(QDataStream &stream)
Unmarshal a value from a QDataStream.
Definition dictionary.h:513
iterator find(const Key &key)
Returns an iterator pointing to the item with the key.
Definition dictionary.h:396
CDictionary & operator=(CDictionary &&other) noexcept
Move assignment.
Definition dictionary.h:463
bool contains(const Key &key) const
Returns true if dictionary contains an item with key, otherwise false.
Definition dictionary.h:399
const QString key(const QString &value) const
Definition dictionary.h:429
bool containsByValue(Predicate p) const
Return true if there is an element for which a given predicate returns true.
Definition dictionary.h:193
typename QMap< QString, QString >::size_type size_type
Definition dictionary.h:113
const_iterator cend() const
Returns const iterator at the end of the dictionary.
Definition dictionary.h:351
iterator erase(iterator pos)
Removes the key/value pair iterator is currently pointing to and returns an iterator to the next item...
Definition dictionary.h:411
void removeByKeyIf(MembFunc membFunc, ReturnValue returnValue)
Remove elements for which key matches a particular pair.
Definition dictionary.h:241
CDictionary(const CDictionary &)=default
Copy constructor.
int count() const
Returns the size of the dictionary.
Definition dictionary.h:405
CDictionary()=default
Default constructor.
bool containsByKey(Predicate p) const
Return true if there is an element for which a given predicate returns true.
Definition dictionary.h:178
const Key key(const Value &value, const Key &defaultKey) const
Return key assigned to value or if key is not found defaultKey.
Definition dictionary.h:432
bool containsByKey(MembFunc membFunc, ReturnValue returnValue) const
Return true if there is an element which key matches a given pair.
Definition dictionary.h:186
void swap(CDictionary &other) noexcept
Swaps hash other with this hash. This operation is very fast and never fails.
Definition dictionary.h:444
iterator begin()
Returns iterator at the beginning of the dictionary.
Definition dictionary.h:336
Thrown when a convertFromJson method encounters an unrecoverable error in JSON data.
Pseudo-RAII pattern that tracks the current JSON value being converted.
A range is a conceptual container which does not contain any elements of its own, but is constructed ...
Definition range.h:199
CRTP class template which will generate marshalling operators for a derived class with its own marsha...
Definition mixindbus.h:39
CRTP class template to generate non-member QDataStream streaming operators.
CRTP class template which will generate marshalling operators for a derived class with its own marsha...
Definition mixinjson.h:37
CRTP class template from which a derived class can inherit string streaming operations.
Definition mixinstring.h:29
auto MemberEqual(Ts... vs)
Predicate which tests whether some member functions return some values.
Definition predicates.h:26
Free functions in swift::misc.
auto makeRange(I begin, I2 end) -> CRange< I >
Returns a CRange constructed from begin and end iterators of deduced types.
Definition range.h:328
typename private_ns::TAssociativityTraits< TModelsQHashKey< K >::value, TModelsQMapKey< K >::value >::template DefaultType< K, V > TDefaultAssociativeType
Trait to select the appropriate default associative container type depending on what the key type sup...
Definition dictionary.h:68
void forEachIntersection(const Map1 &map1, const Map2 &map2, F functor)
Call a functor for each {key,value1,value2} triple in the keywise intersection of two maps.
Definition dictionary.h:541
QMap< Key, Value > & implementationOf(QMap< Key, Value > &dict)
Identity function for API consistency with CDictionary::implementationOf.
Definition dictionary.h:523
QJsonArray::iterator begin()
QJsonArray::iterator end()
QJsonObject::iterator insert(QLatin1StringView key, const QJsonValue &value)
QMap< Key, T >::iterator lowerBound(const Key &key)
Trait to detect whether a class T can be used as a key in a QMap.
Definition typetraits.h:109