1/*
2 This file is part of the KContacts framework.
3 SPDX-FileCopyrightText: 2021 Ahmad Samir <a.samirh78@gmail.com>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6*/
7
8#ifndef PARAMETERMAP_P_H
9#define PARAMETERMAP_P_H
10
11#include <QDataStream>
12#include <QMap>
13#include <QStringList>
14
15#include <algorithm>
16#include <vector>
17
18namespace KContacts
19{
20struct ParameterData {
21 QString param;
22 QStringList paramValues;
23
24 bool operator<(const ParameterData &other) const
25 {
26 return param < other.param;
27 }
28};
29
30class ParameterMap : public std::vector<ParameterData>
31{
32public:
33 inline const_iterator findParam(const QString &param) const
34 {
35 return std::find_if(first: cbegin(), last: cend(), pred: [&param](const ParameterData &info) {
36 return info.param == param;
37 });
38 }
39
40 inline iterator findParam(const QString &param)
41 {
42 return std::find_if(first: begin(), last: end(), pred: [&param](const ParameterData &info) {
43 return info.param == param;
44 });
45 }
46
47 /**
48 * Inserts @p newdata and keeps the vector sorted, the latter needs to
49 * be sorted for comparisons.
50 */
51 inline iterator insertParam(ParameterData &&newdata)
52 {
53 auto dIt = std::lower_bound(first: begin(), last: end(), val: newdata);
54 return insert(position: dIt, x: newdata);
55 }
56
57 inline QString toString() const
58 {
59 if (empty()) {
60 return {};
61 }
62
63 QString str;
64 for (const auto &[p, list] : *this) {
65 str += QStringLiteral("%1 %2").arg(args: p, args: list.join(sep: QLatin1Char(',')));
66 }
67
68 return QLatin1String(" parameters: ") + str + QLatin1Char('\n');
69 }
70
71 static ParameterMap fromQMap(const QMap<QString, QStringList> &params)
72 {
73 ParameterMap vec;
74 vec.reserve(n: params.size());
75 for (auto it = params.begin(), endIt = params.cend(); it != endIt; ++it) {
76 vec.push_back(x: {.param: it.key(), .paramValues: it.value()});
77 }
78 return vec;
79 }
80
81 inline QMap<QString, QStringList> toQMap() const
82 {
83 QMap<QString, QStringList> map;
84 for (const auto &[name, list] : *this) {
85 map.insert(key: name, value: list);
86 }
87 return map;
88 }
89};
90
91inline bool operator==(const ParameterData &a, const ParameterData &b)
92{
93 return std::tie(args: a.param, args: a.paramValues) == std::tie(args: b.param, args: b.paramValues);
94}
95
96inline QDataStream &operator<<(QDataStream &s, const ParameterMap &map)
97{
98 s << static_cast<quint32>(map.size());
99 for (const auto &[p, list] : map) {
100 s << p << list;
101 }
102 return s;
103}
104
105inline QDataStream &operator>>(QDataStream &s, ParameterMap &map)
106{
107 map.clear();
108 quint32 n;
109 s >> n;
110 for (quint32 i = 0; i < n; ++i) {
111 QString p;
112 QStringList lst;
113 s >> p >> lst;
114 if (s.status() != QDataStream::Ok) {
115 map.clear();
116 break;
117 }
118 map.push_back(x: {.param: p, .paramValues: lst});
119 }
120
121 return s;
122}
123}
124
125#endif
126

source code of kcontacts/src/parametermap_p.h