blob: 3dbad27a4cf3cd4bacf2a33cc78cffcaa69b7b79 (
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
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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "smart_buffer.h"
#include <cassert>
namespace vespalib {
void
SmartBuffer::ensure_free(size_t bytes)
{
if (write_len() >= bytes) {
return;
}
if ((unused() < bytes) || ((unused() * 3) < read_len())) {
size_t new_size = std::max(_data.size() * 2, read_len() + bytes);
alloc::Alloc new_buf(alloc::Alloc::alloc(new_size));
if (read_ptr()) {
memcpy(new_buf.get(), read_ptr(), read_len());
}
_data.swap(new_buf);
} else {
if (read_ptr()) {
memmove(_data.get(), read_ptr(), read_len());
}
}
_write_pos = read_len();
_read_pos = 0;
}
void
SmartBuffer::drop()
{
alloc::Alloc empty_buf;
_data.swap(empty_buf);
reset();
}
SmartBuffer::SmartBuffer(size_t initial_size)
: _data(alloc::Alloc::alloc(initial_size)),
_read_pos(0),
_write_pos(0)
{
}
SmartBuffer::~SmartBuffer() = default;
Memory
SmartBuffer::obtain()
{
return Memory(read_ptr(), read_len());
}
Input &
SmartBuffer::evict(size_t bytes)
{
assert(read_len() >= bytes);
_read_pos += bytes;
if (_read_pos == _write_pos) {
_read_pos = 0;
_write_pos = 0;
}
return *this;
}
WritableMemory
SmartBuffer::reserve(size_t bytes)
{
ensure_free(bytes);
return WritableMemory(write_ptr(), write_len());
}
Output &
SmartBuffer::commit(size_t bytes)
{
assert(write_len() >= bytes);
_write_pos += bytes;
return *this;
}
} // namespace vespalib
|