2 * Copyright 2011, Blender Foundation.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 #ifndef __UTIL_CACHE_H__
20 #define __UTIL_CACHE_H__
22 /* Disk Cache based on Hashing
24 * To be used to cache expensive computations. The hash key is created from an
25 * arbitrary number of bytes, by hashing the bytes using MD5, which then gives
26 * the file name containing the data. This data then is read from the file
27 * again into the appropriate data structures.
29 * This way we do not need to accurately track changes, compare dates and
30 * invalidate cache entries, at the cost of exta computation. If everything
31 * is stored in a global cache, computations can perhaps even be shared between
32 * different scenes where it may be hard to detect duplicate work.
35 #include "util_string.h"
36 #include "util_vector.h"
45 CacheBuffer(const void *data_, size_t size_)
46 { data = data_; size = size_; }
51 vector<CacheBuffer> buffers;
55 CacheData(const string& name = "");
58 template<typename T> void add(const vector<T>& data)
60 CacheBuffer buffer(&data[0], data.size()*sizeof(T));
61 buffers.push_back(buffer);
64 template<typename T> void add(const array<T>& data)
66 CacheBuffer buffer(&data[0], data.size()*sizeof(T));
67 buffers.push_back(buffer);
70 void add(void *data, size_t size)
72 CacheBuffer buffer(data, size);
73 buffers.push_back(buffer);
78 CacheBuffer buffer(&data, sizeof(int));
79 buffers.push_back(buffer);
82 void add(size_t& data)
84 CacheBuffer buffer(&data, sizeof(size_t));
85 buffers.push_back(buffer);
88 template<typename T> void read(array<T>& data)
92 if(!fread(&size, sizeof(size), 1, f)) {
93 fprintf(stderr, "Failed to read vector size from cache.\n");
97 data.resize(size/sizeof(T));
99 if(!fread(&data[0], size, 1, f)) {
100 fprintf(stderr, "Failed to read vector data from cache (%ld).\n", size);
107 if(!fread(&data, sizeof(data), 1, f))
108 fprintf(stderr, "Failed to read int from cache.\n");
111 void read(size_t& data)
113 if(!fread(&data, sizeof(data), 1, f))
114 fprintf(stderr, "Failed to read size_t from cache.\n");
122 void insert(const CacheData& key, const CacheData& value);
123 bool lookup(const CacheData& key, CacheData& value);
126 string data_filename(const CacheData& key);
131 #endif /* __UTIL_CACHE_H__ */