aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/growablebytebuffer.cpp
blob: fa0dc9bf99e271a8c91ddae553b31a0d858f9daf (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "growablebytebuffer.h"
#include <arpa/inet.h>

using namespace vespalib;

GrowableByteBuffer::GrowableByteBuffer(uint32_t initialLen) :
    _buffer(Alloc::alloc(initialLen)),
    _position(0)
{
}

char*
GrowableByteBuffer::allocate(uint32_t len)
{
    size_t need(_position + len);
    if (need > _buffer.size()) {
        uint32_t newSize = vespalib::roundUp2inN(need);
        Alloc newBuf(Alloc::alloc(newSize));
        memcpy(newBuf.get(), _buffer.get(), _position);
        _buffer.swap(newBuf);
    }

    char* pos = static_cast<char *>(_buffer.get()) + _position;
    _position += len;
    return pos;
}

void
GrowableByteBuffer::putBytes(const void * buffer, uint32_t length)
{
    char* buf = allocate(length);
    memcpy(buf, buffer, length);
}

void
GrowableByteBuffer::putShort(uint16_t v)
{
    uint16_t val = htons(v);
    putBytes(reinterpret_cast<const char*>(&val), sizeof(v));
}

void
GrowableByteBuffer::putInt(uint32_t v)
{
    uint32_t val = htonl(v);
    putBytes(reinterpret_cast<const char*>(&val), sizeof(v));
}

void
GrowableByteBuffer::putReverse(const char* buffer, uint32_t length)
{
    char* buf = allocate(length);
    for (uint32_t i = 0; i < length; i++) {
        buf[(length - i - 1)] = buffer[i];
    }
}

void
GrowableByteBuffer::putLong(uint64_t v)
{
    putReverse(reinterpret_cast<const char*>(&v), sizeof(v));
}

void
GrowableByteBuffer::putDouble(double v)
{
    putReverse(reinterpret_cast<const char*>(&v), sizeof(v));
}

void
GrowableByteBuffer::putString(vespalib::stringref v)
{
    putInt(v.size());
    putBytes(v.data(), v.size());
}

void
GrowableByteBuffer::put_c_string(vespalib::stringref v)
{
    putInt(v.size() + 1);
    putBytes(v.data(), v.size());
    putByte(0);
}

void
GrowableByteBuffer::putByte(uint8_t v)
{
    putBytes(reinterpret_cast<const char*>(&v), sizeof(v));
}

void
GrowableByteBuffer::putBoolean(bool v)
{
    putByte(v);
}