Added NameMapperProxy from kiwix/kiwix-desktop#714

The right place for NameMapperProxy introduced by kiwix/kiwix-desktop#714 is in
libkiwix (so that it can be reused in kiwix-serve).
This commit is contained in:
Veloman Yunkan 2021-11-22 21:08:01 +04:00
parent 4ccbdcb740
commit 8fffa59974
2 changed files with 62 additions and 0 deletions

View File

@ -22,6 +22,8 @@
#include <string>
#include <map>
#include <memory>
#include <mutex>
namespace kiwix
{
@ -54,6 +56,25 @@ class HumanReadableNameMapper : public NameMapper {
virtual std::string getIdForName(const std::string& name) const;
};
class NameMapperProxy : public NameMapper {
typedef std::shared_ptr<NameMapper> NameMapperHandle;
public:
explicit NameMapperProxy(Library& library);
virtual std::string getNameForId(const std::string& id) const;
virtual std::string getIdForName(const std::string& name) const;
void update();
private:
NameMapperHandle currentNameMapper() const;
private:
mutable std::mutex mutex;
Library& library;
NameMapperHandle nameMapper;
};
}
#endif

View File

@ -59,4 +59,45 @@ std::string HumanReadableNameMapper::getIdForName(const std::string& name) const
return m_nameToId.at(name);
}
////////////////////////////////////////////////////////////////////////////////
// NameMapperProxy
////////////////////////////////////////////////////////////////////////////////
NameMapperProxy::NameMapperProxy(Library& lib)
: library(lib)
{
update();
}
void NameMapperProxy::update()
{
const auto newNameMapper = new HumanReadableNameMapper(library, false);
std::lock_guard<std::mutex> lock(mutex);
nameMapper.reset(newNameMapper);
}
NameMapperProxy::NameMapperHandle
NameMapperProxy::currentNameMapper() const
{
// Return a copy of the handle to the current NameMapper object. It will
// ensure that the object survives any call to NameMapperProxy::update()
// made before the completion of any pending operation on that object.
std::lock_guard<std::mutex> lock(mutex);
return nameMapper;
}
std::string NameMapperProxy::getNameForId(const std::string& id) const
{
// Ensure that the current nameMapper object survives a concurrent call
// to NameMapperProxy::update()
return currentNameMapper()->getNameForId(id);
}
std::string NameMapperProxy::getIdForName(const std::string& name) const
{
// Ensure that the current nameMapper object survives a concurrent call
// to NameMapperProxy::update()
return currentNameMapper()->getIdForName(name);
}
}