dungeon_crawler
annotate prototype/src/dataset.h @ 53:1ea56011c1ff
stuff + streaming start
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Wed, 19 Sep 2012 01:08:41 +0300 |
parents | |
children | 7f52d6310317 |
rev | line source |
---|---|
nuclear@48 | 1 #ifndef DATASET_H_ |
nuclear@48 | 2 #define DATASET_H_ |
nuclear@48 | 3 |
nuclear@48 | 4 #include <string.h> |
nuclear@48 | 5 #include <string> |
nuclear@48 | 6 #include <map> |
nuclear@48 | 7 #include <functional> |
nuclear@48 | 8 #include "datapath.h" |
nuclear@48 | 9 |
nuclear@48 | 10 template <typename T> |
nuclear@48 | 11 class DataSet { |
nuclear@48 | 12 private: |
nuclear@48 | 13 mutable std::map<std::string, T> data; |
nuclear@48 | 14 |
nuclear@48 | 15 std::function<T(const char*)> load; |
nuclear@48 | 16 std::function<void(T)> destroy; |
nuclear@48 | 17 |
nuclear@48 | 18 public: |
nuclear@48 | 19 DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func); |
nuclear@48 | 20 ~DataSet(); |
nuclear@48 | 21 |
nuclear@48 | 22 T get(const char *name) const; |
nuclear@48 | 23 }; |
nuclear@48 | 24 |
nuclear@48 | 25 template <typename T> |
nuclear@48 | 26 DataSet<T>::DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func) |
nuclear@48 | 27 { |
nuclear@48 | 28 load = load_func; |
nuclear@48 | 29 destroy = destr_func; |
nuclear@48 | 30 } |
nuclear@48 | 31 |
nuclear@48 | 32 template <typename T> |
nuclear@48 | 33 DataSet<T>::~DataSet() |
nuclear@48 | 34 { |
nuclear@48 | 35 if(destroy) { |
nuclear@48 | 36 for(auto it : data) { |
nuclear@48 | 37 destroy(it.second); |
nuclear@48 | 38 } |
nuclear@48 | 39 } |
nuclear@48 | 40 } |
nuclear@48 | 41 |
nuclear@48 | 42 template <typename T> |
nuclear@48 | 43 T DataSet<T>::get(const char *name) const |
nuclear@48 | 44 { |
nuclear@48 | 45 auto iter = data.find(name); |
nuclear@48 | 46 if(iter != data.end()) { |
nuclear@48 | 47 return iter->second; |
nuclear@48 | 48 } |
nuclear@48 | 49 |
nuclear@48 | 50 const char *path, *slash; |
nuclear@48 | 51 if((slash = strrchr(name, '/'))) { |
nuclear@48 | 52 path = slash + 1; |
nuclear@48 | 53 } else { |
nuclear@48 | 54 path = name; |
nuclear@48 | 55 } |
nuclear@48 | 56 if(!(path = datafile_path(path))) { |
nuclear@48 | 57 fprintf(stderr, "can't find data file: %s\n", name); |
nuclear@48 | 58 return 0; |
nuclear@48 | 59 } |
nuclear@48 | 60 |
nuclear@48 | 61 T res = load(path); |
nuclear@48 | 62 if(res) { |
nuclear@48 | 63 data[name] = res; |
nuclear@48 | 64 } |
nuclear@48 | 65 return res; |
nuclear@48 | 66 } |
nuclear@48 | 67 |
nuclear@48 | 68 #endif // DATASET_H_ |