#ifndef oo_ObjDictionary_H__ #define oo_ObjDictionary_H__ #include "ObjBase.h" #include "../Self.h" #include #include #include #include #include namespace meow { /*! * @brief 純粹把 \c std::map 包起來, 變成繼承自 ObjBase * * @author cathook */ template class ObjDictionary: public ObjBase { private: struct Myself { std::map dictionary_; Myself() { } ~Myself() { } Myself& copyFrom(Myself const& b) { dictionary_ = b.dictionary_; return *this; } }; Self const self; public: ObjDictionary(): self(true) { } ObjDictionary(ObjDictionary const& d): self(false) { self.copyFrom(b.self); } ObjDictionary(std::map const& d): self(true) { self()->dictionary_ = d; } ~ObjDictionary() { } ObjDictionary& copyFrom(ObjDictionary const& d) { self().copyFrom(d.self); return *this; } ObjDictionary& referenceFrom(ObjDictionary const& d) { self().referenceFrom(d.self); return *this; } size_t size() const { return self->dictionary_.size(); } bool empty() const { return self->dictionary_.empty(); } void clear() { self()->dictionary_.clear(); } std::map::const_iterator end() const { return self->dictionary_.end(); } std::map::iterator end() { return self()->dictionary_.end(); } std::map::const_iterator find(Key const& k) const { return self->dictionary_.find(k); } std::map::iterator find(Key const& k) { return self()->dictionary_.find(k); } bool exist(Key const& k) const { return (find() != end()); } void insert(Key const& k, Value const& v) { self->dictionary_.insert(std::pair(k, v)); } ObjDictionary& operator=(ObjDictionary const& a) { return copyFrom(a); } Value& operator[](Key const& k) { return self()->dictionary_[k]; } bool write(FILE* f, bool bin, unsigned int fg) const { size_t sz = size(); if (bin) { if (fwrite(&sz, sizeof(size_t), 1, f) < 1) return false; } else { if (fprintf(f, "%lu\n", sz) < 1) return false; } for (std::map::const_iterator it = self->dictionary_.begin(); it != self->dictionary_.end(); ++it) { if (it->first .write(f, bin, fg) == false) return false; if (it->second.write(f, bin, fg) == false) return false; } return true; } bool read(FILE* f, bool bin, unsigned int fg) { size_t sz; if (bin) { if (fread(&sz, sizeof(size_t), 1, f) < 1) return false; } else { if (fscanf(f, "%lu\n", &sz) < 0) return false; } for (size_t i = 0; i < sz; i++) { Key k; Value v; if (k.read(f, bin, fg) == false) return false; if (v.read(f, bin, fg) == false) return false; insert(k, v); } return true; } ObjBase* create() const { return new ObjDictionary(); } ObjBase* copyFrom(ObjBase const* b) { return &(copyFrom(*(ObjDictionary*)b)); } char const* ctype() const { return typeid(*this).name(); } std::string type() const { return std::string(ctype()); } }; } #endif // oo_ObjDictionary_H__