Skip to content

Commit

Permalink
Added NameMapperProxy from kiwix/kiwix-desktop#714
Browse files Browse the repository at this point in the history
The right place for NameMapperProxy introduced by
kiwix/kiwix-desktop#714 is in libkiwix (so that it can be reused in
kiwix-serve).
  • Loading branch information
veloman-yunkan committed Nov 20, 2021
1 parent 571e417 commit 833667e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions include/name_mapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

#include <string>
#include <map>
#include <memory>
#include <mutex>

namespace kiwix
{
Expand Down Expand Up @@ -54,7 +56,24 @@ class HumanReadableNameMapper : public NameMapper {
virtual std::string getIdForName(const std::string& name);
};

class NameMapperProxy : public kiwix::NameMapper {
typedef std::shared_ptr<kiwix::NameMapper> NameMapperHandle;
public:
explicit NameMapperProxy(kiwix::Library& library);

virtual std::string getNameForId(const std::string& id);
virtual std::string getIdForName(const std::string& name);

void update();

private:
NameMapperHandle currentNameMapper() const;

private:
mutable std::mutex mutex;
kiwix::Library& library;
NameMapperHandle nameMapper;
};

}

Expand Down
41 changes: 41 additions & 0 deletions src/name_mapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,45 @@ std::string HumanReadableNameMapper::getIdForName(const std::string& name) {
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)
{
// 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)
{
// Ensure that the current nameMapper object survives a concurrent call
// to NameMapperProxy::update()
return currentNameMapper()->getIdForName(name);
}

}

0 comments on commit 833667e

Please sign in to comment.