Library got a yet unused mutex

Introducing a mutex in `Library` necessitates manually implementing the
move constructor and assignment operator. It's better to still delegate
that work to the compiler to eliminate any possibility of bugs when new
data members are added to `Library`. The trick is to move the data into
an auxiliary class `LibraryBase` and derive `Library` from it.
This commit is contained in:
Veloman Yunkan 2021-11-28 18:01:57 +04:00
parent b712c732f2
commit c2927ce6f7
2 changed files with 45 additions and 8 deletions

View File

@ -24,6 +24,7 @@
#include <vector>
#include <map>
#include <memory>
#include <mutex>
#include <zim/archive.h>
#include "book.h"
@ -139,12 +140,14 @@ private: // functions
bool accept(const Book& book) const;
};
/**
* A Library store several books.
* This class is not part of the libkiwix API. Its only purpose is
* to simplify the implementation of the Library's move operations
* and avoid bugs should new data members be added to Library.
*/
class Library
class LibraryBase
{
protected: // data
std::map<std::string, kiwix::Book> m_books;
std::map<std::string, std::shared_ptr<Reader>> m_readers;
std::map<std::string, std::shared_ptr<zim::Archive>> m_archives;
@ -152,6 +155,22 @@ class Library
class BookDB;
std::unique_ptr<BookDB> m_bookDB;
protected: // functions
LibraryBase();
~LibraryBase();
LibraryBase(LibraryBase&& );
LibraryBase& operator=(LibraryBase&& );
};
/**
* A Library store several books.
*/
class Library : private LibraryBase
{
// all data fields must be added in LibraryBase
mutable std::mutex m_mutex;
public:
typedef std::vector<std::string> BookIdCollection;
typedef std::map<std::string, int> AttributeCounts;

View File

@ -58,21 +58,39 @@ bool booksReferToTheSameArchive(const Book& book1, const Book& book2)
} // unnamed namespace
class Library::BookDB : public Xapian::WritableDatabase
class LibraryBase::BookDB : public Xapian::WritableDatabase
{
public:
BookDB() : Xapian::WritableDatabase("", Xapian::DB_BACKEND_INMEMORY) {}
};
/* Constructor */
Library::Library()
LibraryBase::LibraryBase()
: m_bookDB(new BookDB)
{
}
Library::Library(Library&& ) = default;
LibraryBase::~LibraryBase()
{
}
Library& Library::operator=(Library&& ) = default;
LibraryBase::LibraryBase(LibraryBase&& ) = default;
LibraryBase& LibraryBase::operator=(LibraryBase&& ) = default;
/* Constructor */
Library::Library()
{
}
Library::Library(Library&& other)
: LibraryBase(std::move(other))
{
}
Library& Library::operator=(Library&& other)
{
LibraryBase::operator=(std::move(other));
return *this;
}
/* Destructor */
Library::~Library()