blob: 7c560898de588fd9e6694918752f99166a0610d8 (
plain) (
blame)
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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "input.h"
#include "output.h"
#include <vespa/vespalib/util/alloc.h>
namespace vespalib {
/**
* A somewhat smarter buffer compared to SimpleBuffer. Keeps track of
* data in a continuous memory segment. Tries to limit copying of
* data.
**/
class SmartBuffer : public Input,
public Output
{
private:
alloc::Alloc _data;
size_t _read_pos;
size_t _write_pos;
const char *read_ptr() const { return (const char *)(_data.get()) + _read_pos; }
size_t read_len() const { return (_write_pos - _read_pos); }
char *write_ptr() { return (char *)(_data.get()) + _write_pos; }
size_t write_len() const { return (_data.size() - _write_pos); }
size_t unused() const { return (_data.size() - read_len()); }
void ensure_free(size_t bytes);
void drop();
public:
SmartBuffer(size_t initial_size);
~SmartBuffer();
bool empty() const { return (read_len() == 0); }
size_t capacity() const { return _data.size(); }
void drop_if_empty() {
if (empty() && (_data.size() > 0)) {
drop();
}
}
void reset() {
_read_pos = 0;
_write_pos = 0;
}
Memory obtain() override;
Input &evict(size_t bytes) override;
WritableMemory reserve(size_t bytes) override;
Output &commit(size_t bytes) override;
};
} // namespace vespalib
|