1 // Copyright (c) 2013, Facebook, Inc. All rights reserved.
2 // This source code is licensed under both the GPLv2 (found in the
3 // COPYING file in the root directory) and Apache 2.0 License
4 // (found in the LICENSE.Apache file in the root directory).
11 #include "include/rocksdb/comparator.h"
12 #include "util/arena.h"
13 #include "util/mutexlock.h"
20 // Buffer abstraction that can be manipulated via append
22 class CacheWriteBuffer
{
24 explicit CacheWriteBuffer(const size_t size
) : size_(size
), pos_(0) {
25 buf_
.reset(new char[size_
]);
30 virtual ~CacheWriteBuffer() {}
32 void Append(const char* buf
, const size_t size
) {
33 assert(pos_
+ size
<= size_
);
34 memcpy(buf_
.get() + pos_
, buf
, size
);
36 assert(pos_
<= size_
);
39 void FillTrailingZeros() {
40 assert(pos_
<= size_
);
41 memset(buf_
.get() + pos_
, '0', size_
- pos_
);
45 void Reset() { pos_
= 0; }
46 size_t Free() const { return size_
- pos_
; }
47 size_t Capacity() const { return size_
; }
48 size_t Used() const { return pos_
; }
49 char* Data() const { return buf_
.get(); }
52 std::unique_ptr
<char[]> buf_
;
58 // CacheWriteBufferAllocator
60 // Buffer pool abstraction(not thread safe)
62 class CacheWriteBufferAllocator
{
64 explicit CacheWriteBufferAllocator(const size_t buffer_size
,
65 const size_t buffer_count
)
66 : cond_empty_(&lock_
), buffer_size_(buffer_size
) {
68 buffer_size_
= buffer_size
;
69 for (uint32_t i
= 0; i
< buffer_count
; i
++) {
70 auto* buf
= new CacheWriteBuffer(buffer_size_
);
79 virtual ~CacheWriteBufferAllocator() {
81 assert(bufs_
.size() * buffer_size_
== Capacity());
82 for (auto* buf
: bufs_
) {
88 CacheWriteBuffer
* Allocate() {
94 assert(!bufs_
.empty());
95 CacheWriteBuffer
* const buf
= bufs_
.front();
100 void Deallocate(CacheWriteBuffer
* const buf
) {
104 bufs_
.push_back(buf
);
105 cond_empty_
.Signal();
108 void WaitUntilUsable() {
109 // We are asked to wait till we have buffers available
111 while (bufs_
.empty()) {
116 size_t Capacity() const { return bufs_
.size() * buffer_size_
; }
117 size_t Free() const { return bufs_
.size() * buffer_size_
; }
118 size_t BufferSize() const { return buffer_size_
; }
121 port::Mutex lock_
; // Sync lock
122 port::CondVar cond_empty_
; // Condition var for empty buffers
123 size_t buffer_size_
; // Size of each buffer
124 std::list
<CacheWriteBuffer
*> bufs_
; // Buffer stash
127 } // namespace rocksdb