QCborMap: merge the operator[] methods into a template

Change-Id: I5e52dc5b093c43a3b678fffd16b6e7a123338178
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
This commit is contained in:
Thiago Macieira 2021-11-12 12:49:53 -08:00
parent 11ea172178
commit f1c305cbd2
2 changed files with 36 additions and 32 deletions

View File

@ -422,14 +422,7 @@ QList<QCborValue> QCborMap::keys() const
*/
QCborValueRef QCborMap::operator[](qint64 key)
{
auto it = find(key);
if (it == constEnd()) {
// insert element
detach(it.item.i + 2);
d->append(key);
d->append(Undefined{});
}
return { d.data(), it.item.i };
return QCborContainerPrivate::findOrAddMapKey(*this, key);
}
/*!
@ -549,14 +542,7 @@ QCborValueRef QCborMap::operator[](qint64 key)
*/
QCborValueRef QCborMap::operator[](QLatin1String key)
{
auto it = find(key);
if (it == constEnd()) {
// insert element
detach(it.item.i + 2);
d->append(key);
d->append(Undefined{});
}
return { d.data(), it.item.i };
return QCborContainerPrivate::findOrAddMapKey(*this, key);
}
/*!
@ -678,14 +664,7 @@ QCborValueRef QCborMap::operator[](QLatin1String key)
*/
QCborValueRef QCborMap::operator[](const QString & key)
{
auto it = find(key);
if (it == constEnd()) {
// insert element
detach(it.item.i + 2);
d->append(key);
d->append(Undefined{});
}
return { d.data(), it.item.i };
return QCborContainerPrivate::findOrAddMapKey(*this, qToStringViewIgnoringNull(key));
}
/*!
@ -803,14 +782,15 @@ QCborValueRef QCborMap::operator[](const QString & key)
*/
QCborValueRef QCborMap::operator[](const QCborValue &key)
{
auto it = find(key);
if (it == constEnd()) {
// insert element
detach(it.item.i + 2);
d->append(key);
d->append(Undefined{});
}
return { d.data(), it.item.i };
return QCborContainerPrivate::findOrAddMapKey<const QCborValue &>(*this, key);
}
template <typename KeyType> inline QCborValueRef
QCborContainerPrivate::findOrAddMapKey(QCborMap &map, KeyType key)
{
QCborValueRef result = findOrAddMapKey<KeyType>(map.d.data(), key);
map.d = result.d;
return result;
}
/*!

View File

@ -439,6 +439,30 @@ public:
}
return QCborValueRef{ this, i + 1 };
}
template <typename KeyType> static QCborValueRef
findOrAddMapKey(QCborContainerPrivate *container, KeyType key)
{
qsizetype size = 0;
qsizetype index = size + 1;
if (container) {
size = container->elements.size();
index = container->findCborMapKey<KeyType>(key).i; // returns size + 1 if not found
}
Q_ASSERT(index & 1);
Q_ASSERT((size & 1) == 0);
container = detach(container, qMax(index + 1, size));
Q_ASSERT(container);
Q_ASSERT((container->elements.size() & 1) == 0);
if (index >= size) {
container->append(key);
container->append(QCborValue());
}
Q_ASSERT(index < container->elements.size());
return { container, index };
}
template <typename KeyType> static QCborValueRef findOrAddMapKey(QCborMap &map, KeyType key);
#if QT_CONFIG(cborstreamreader)
void decodeValueFromCbor(QCborStreamReader &reader, int remainingStackDepth);