subsurface/core/gettextfromc.cpp
Berthold Stoeger db0dd54c37 Localization: make cache thread safe and robust against use-after-free
The old trGettext() was not thread-safe and the returned C-strings
could be freed in the case of empty translations strings. Therefore:

1) Introduce a mutex protecting access to the cache.

2) Never change existing entries, even if the translation string is empty.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
2018-06-24 20:31:14 +02:00

17 lines
445 B
C++

// SPDX-License-Identifier: GPL-2.0
#include "gettextfromc.h"
#include <QHash>
#include <QMutex>
static QHash<QByteArray, QByteArray> translationCache;
static QMutex lock;
extern "C" const char *trGettext(const char *text)
{
QByteArray key(text);
QMutexLocker l(&lock);
auto it = translationCache.find(key);
if (it == translationCache.end())
it = translationCache.insert(key, gettextFromC::tr(text).toUtf8());
return it->constData();
}