| 1 | // Copyright (C) 2016 Klaralvdalens Datakonsult AB (KDAB). |
|---|---|
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #include "stringtoint_p.h" |
| 5 | #include <QHash> |
| 6 | #include <mutex> |
| 7 | #include <shared_mutex> |
| 8 | #include <vector> |
| 9 | |
| 10 | QT_BEGIN_NAMESPACE |
| 11 | |
| 12 | namespace Qt3DRender { |
| 13 | |
| 14 | namespace Render { |
| 15 | |
| 16 | namespace { |
| 17 | |
| 18 | struct StringToIntCache |
| 19 | { |
| 20 | std::shared_mutex lock; |
| 21 | QHash<QString, int> map; |
| 22 | std::vector<QString> reverseMap; |
| 23 | |
| 24 | static StringToIntCache& instance() |
| 25 | { |
| 26 | static StringToIntCache c; |
| 27 | return c; |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | } // anonymous |
| 32 | |
| 33 | int StringToInt::lookupId(QLatin1String str) |
| 34 | { |
| 35 | // ### optimize me |
| 36 | return lookupId(str: QString(str)); |
| 37 | } |
| 38 | |
| 39 | int StringToInt::lookupId(const QString &str) |
| 40 | { |
| 41 | auto& cache = StringToIntCache::instance(); |
| 42 | int idx; |
| 43 | { |
| 44 | std::shared_lock readLocker(cache.lock); |
| 45 | idx = cache.map.value(key: str, defaultValue: -1); |
| 46 | } |
| 47 | |
| 48 | if (Q_UNLIKELY(idx < 0)) { |
| 49 | std::unique_lock writeLocker(cache.lock); |
| 50 | idx = cache.map.value(key: str, defaultValue: -1); |
| 51 | if (idx < 0) { |
| 52 | idx = int(cache.reverseMap.size()); |
| 53 | Q_ASSERT(size_t(cache.map.size()) == cache.reverseMap.size()); |
| 54 | cache.map.insert(key: str, value: idx); |
| 55 | cache.reverseMap.push_back(x: str); |
| 56 | } |
| 57 | } |
| 58 | return idx; |
| 59 | } |
| 60 | |
| 61 | QString StringToInt::lookupString(int idx) |
| 62 | { |
| 63 | auto& cache = StringToIntCache::instance(); |
| 64 | std::shared_lock readLocker(cache.lock); |
| 65 | if (Q_LIKELY(cache.reverseMap.size() > size_t(idx))) |
| 66 | return cache.reverseMap[idx]; |
| 67 | |
| 68 | return QString(); |
| 69 | } |
| 70 | |
| 71 | } // Render |
| 72 | |
| 73 | } // Qt3DRender |
| 74 | |
| 75 | QT_END_NAMESPACE |
| 76 |
