dungeon_crawler

diff prototype/src/dataset.h @ 48:aa9e28670ae2

added sound playback, more to do
author John Tsiombikas <nuclear@member.fsf.org>
date Mon, 17 Sep 2012 08:40:59 +0300
parents
children 7f52d6310317
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/prototype/src/dataset.h	Mon Sep 17 08:40:59 2012 +0300
     1.3 @@ -0,0 +1,68 @@
     1.4 +#ifndef DATASET_H_
     1.5 +#define DATASET_H_
     1.6 +
     1.7 +#include <string.h>
     1.8 +#include <string>
     1.9 +#include <map>
    1.10 +#include <functional>
    1.11 +#include "datapath.h"
    1.12 +
    1.13 +template <typename T>
    1.14 +class DataSet {
    1.15 +private:
    1.16 +	mutable std::map<std::string, T> data;
    1.17 +
    1.18 +	std::function<T(const char*)> load;
    1.19 +	std::function<void(T)> destroy;
    1.20 +
    1.21 +public:
    1.22 +	DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func);
    1.23 +	~DataSet();
    1.24 +
    1.25 +	T get(const char *name) const;
    1.26 +};
    1.27 +
    1.28 +template <typename T>
    1.29 +DataSet<T>::DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func)
    1.30 +{
    1.31 +	load = load_func;
    1.32 +	destroy = destr_func;
    1.33 +}
    1.34 +
    1.35 +template <typename T>
    1.36 +DataSet<T>::~DataSet()
    1.37 +{
    1.38 +	if(destroy) {
    1.39 +		for(auto it : data) {
    1.40 +			destroy(it.second);
    1.41 +		}
    1.42 +	}
    1.43 +}
    1.44 +
    1.45 +template <typename T>
    1.46 +T DataSet<T>::get(const char *name) const
    1.47 +{
    1.48 +	auto iter = data.find(name);
    1.49 +	if(iter != data.end()) {
    1.50 +		return iter->second;
    1.51 +	}
    1.52 +
    1.53 +	const char *path, *slash;
    1.54 +	if((slash = strrchr(name, '/'))) {
    1.55 +		path = slash + 1;
    1.56 +	} else {
    1.57 +		path = name;
    1.58 +	}
    1.59 +	if(!(path = datafile_path(path))) {
    1.60 +		fprintf(stderr, "can't find data file: %s\n", name);
    1.61 +		return 0;
    1.62 +	}
    1.63 +
    1.64 +	T res = load(path);
    1.65 +	if(res) {
    1.66 +		data[name] = res;
    1.67 +	}
    1.68 +	return res;
    1.69 +}
    1.70 +
    1.71 +#endif	// DATASET_H_