summaryrefslogtreecommitdiff
path: root/cpp/sbuffer.hpp
blob: 2651b58d5a7472bf8f7a9e659ea7e347b3b325c7 (plain)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// MessagePack for C++ simple buffer implementation
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
#ifndef MSGPACK_SBUFFER_HPP__
#define MSGPACK_SBUFFER_HPP__

#include "msgpack/sbuffer.h"
#include <stdexcept>

namespace msgpack {


class sbuffer : public msgpack_sbuffer {
public:
	sbuffer(size_t initsz = MSGPACK_SBUFFER_INIT_SIZE)
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);

		sbuf->data = (char*)::malloc(initsz);
		if(!sbuf->data) {
			throw std::bad_alloc();
		}

		sbuf->size = 0;
		sbuf->alloc = initsz;
	}

	~sbuffer()
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);
		::free(sbuf->data);
	}

public:
	void write(const char* buf, unsigned int len)
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);
		if(sbuf->alloc - sbuf->size < len) {
			expand_buffer(len);
		}
		memcpy(sbuf->data + sbuf->size, buf, len);
		sbuf->size += len;
	}

	char* data()
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);
		return sbuf->data;
	}

	const char* data() const
	{
		const msgpack_sbuffer* sbuf = static_cast<const msgpack_sbuffer*>(this);
		return sbuf->data;
	}

	size_t size() const
	{
		const msgpack_sbuffer* sbuf = static_cast<const msgpack_sbuffer*>(this);
		return sbuf->size;
	}

	char* release()
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);
		return msgpack_sbuffer_release(sbuf);
	}

private:
	void expand_buffer(size_t len)
	{
		msgpack_sbuffer* sbuf = static_cast<msgpack_sbuffer*>(this);

		size_t nsize = (sbuf->alloc) ?
				sbuf->alloc * 2 : MSGPACK_SBUFFER_INIT_SIZE;
	
		while(nsize < sbuf->size + len) { nsize *= 2; }
	
		void* tmp = realloc(sbuf->data, nsize);
		if(!tmp) {
			throw std::bad_alloc();
		}
	
		sbuf->data = (char*)tmp;
		sbuf->alloc = nsize;
	}

private:
	sbuffer(const sbuffer&);
};


}  // namespace msgpack

#endif /* msgpack/sbuffer.hpp */