summaryrefslogtreecommitdiff
path: root/cpp/unpack.cpp
blob: 0f02d3c113d82ea5da3ffd6763f5e98284451cf6 (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
#include "msgpack/unpack.hpp"
#include "unpack_context.hpp"
#include <stdlib.h>

namespace msgpack {

struct unpacker::context {
	context(zone& z)
	{
		msgpack_unpacker_init(&m_ctx);
		m_ctx.user = &z;
	}

	~context() { }

	int execute(const void* data, size_t len, size_t* off)
	{
		return msgpack_unpacker_execute(&m_ctx, (const char*)data, len, off);
	}

	object_class* data()
	{
		return msgpack_unpacker_data(&m_ctx);
	}

	void reset()
	{
		zone* z = m_ctx.user;
		msgpack_unpacker_init(&m_ctx);
		m_ctx.user = z;
	}

private:
	msgpack_unpacker m_ctx;

private:
	context();
	context(const context&);
};


unpacker::unpacker(zone& z) :
	m_ctx(new context(z)),
	m_zone(z),
	m_finished(false)
{ }


unpacker::~unpacker() { delete m_ctx; }


size_t unpacker::execute(const void* data, size_t len, size_t off)
{
	int ret = m_ctx->execute(data, len, &off);
	if(ret < 0) {
		throw unpack_error("parse error");
	} else if(ret > 0) {
		m_finished = true;
		return off;
	} else {
		m_finished = false;
		return off;
	}
}


object unpacker::data()
{
	return object(m_ctx->data());
}


void unpacker::reset()
{
	m_ctx->reset();
}


object unpacker::unpack(const void* data, size_t len, zone& z)
{
	context ctx(z);
	size_t off = 0;
	int ret = ctx.execute(data, len, &off);
	if(ret < 0) {
		throw unpack_error("parse error");
	} else if(ret == 0) {
		throw unpack_error("insufficient bytes");
	} else if(off < len) {
		throw unpack_error("extra bytes");
	}
	return ctx.data();
}


}  // namespace msgpack