-
Notifications
You must be signed in to change notification settings - Fork 79
/
cache.h
80 lines (67 loc) · 1.7 KB
/
cache.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#ifndef WMDRELAX_CACHE_H_
#define WMDRELAX_CACHE_H_
#include <cstdio>
#include <mutex>
namespace wmd {
/// This is supposed to be the base class for all the other caches.
/// "Cache" here means the carrier of reusable buffers which should eliminate
/// memory allocations. It should be used as follows:
///
/// Cache instance;
/// instance.allocate(100500);
/// // thread safety
/// {
/// // the problem size is 100
/// std::lock_guard<std::mutex> _(instance.enter(100));
/// auto whatever = instance.whatever();
/// // ... use whatever ...
/// }
class Cache {
public:
enum AllocationError {
kAllocationErrorSuccess = 0,
/// Can't allocate empty cache.
kAllocationErrorInvalidSize,
/// You have to deallocate the cache first before allocating again.
kAllocationErrorDeallocationNeeded
};
Cache() : size_(0) {}
virtual ~Cache() {}
AllocationError allocate(size_t size) {
if (size == 0) {
return kAllocationErrorInvalidSize;
}
if (size_ != 0) {
return kAllocationErrorDeallocationNeeded;
}
size_ = size;
_allocate();
return kAllocationErrorSuccess;
}
void reset() noexcept {
_reset();
size_ = 0;
}
std::mutex& enter(size_t size) const {
#ifndef NDEBUG
assert(size_ >= size && "the cache is too small");
#else
if (size_ < size) {
fprintf(stderr, "emd: cache size is too small: %zu < %zu\n",
size_, size);
throw "the cache is too small";
}
#endif
return lock_;
}
protected:
virtual void _allocate() = 0;
virtual void _reset() noexcept = 0;
size_t size_;
private:
Cache(const Cache&) = delete;
Cache& operator=(const Cache&) = delete;
mutable std::mutex lock_;
};
}
#endif // WMDRELAX_CACHE_H_