From: Mikko Rasa Date: Fri, 20 Jan 2012 20:28:06 +0000 (+0200) Subject: Add DirectoryCollection class for creating directory-backed collections X-Git-Url: http://git.tdb.fi/?a=commitdiff_plain;h=a4091f14dfbf4d5f822fa26740a7b3f305c449e6;p=libs%2Fdatafile.git Add DirectoryCollection class for creating directory-backed collections --- diff --git a/source/directorycollection.cpp b/source/directorycollection.cpp new file mode 100644 index 0000000..25808d6 --- /dev/null +++ b/source/directorycollection.cpp @@ -0,0 +1,41 @@ +#include +#include "directorycollection.h" + +using namespace std; + +namespace Msp { +namespace DataFile { + +DirectoryCollection::DirectoryCollection() +{ + set_directory("."); +} + +void DirectoryCollection::set_directory(const FS::Path &d) +{ + dirs.clear(); + add_directory(d); +} + +void DirectoryCollection::add_directory(const FS::Path &d) +{ + dirs.push_back(d); +} + +bool DirectoryCollection::lookup_file(const string &name, FS::Path &result) const +{ + for(list::const_iterator i=dirs.begin(); i!=dirs.end(); ++i) + { + FS::Path file_path = *i/name; + if(FS::exists(file_path)) + { + result = file_path; + return true; + } + } + + return false; +} + +} // namespace DataFile +} // namespace Msp diff --git a/source/directorycollection.h b/source/directorycollection.h new file mode 100644 index 0000000..93f9354 --- /dev/null +++ b/source/directorycollection.h @@ -0,0 +1,52 @@ +#ifndef MSP_DATAFILE_DIRECTORYCOLLECTION_H_ +#define MSP_DATAFILE_DIRECTORYCOLLECTION_H_ + +#include +#include "collection.h" + +namespace Msp { +namespace DataFile { + +/** +A Collection that can automatically load items from files in a directory. +*/ +class DirectoryCollection: public Collection +{ +private: + std::list dirs; + +public: + DirectoryCollection(); + +protected: + void set_directory(const FS::Path &); + void add_directory(const FS::Path &); + + template + CollectionItemType &add_type() + { + return Collection::add_type().creator(&DirectoryCollection::create); + } + +private: + template + T *create(const std::string &name) + { + FS::Path file; + if(lookup_file(name, file)) + { + RefPtr item = new T; + load(*item, file.str()); + return item.release(); + } + else + return 0; + } + + bool lookup_file(const std::string &, FS::Path &) const; +}; + +} // namespace DataFile +} // namespace Msp + +#endif