aboutsummaryrefslogtreecommitdiff
path: root/src/libjin-lua/modules/net/l_buffer.h
blob: 7cf6061fdf59077de1b0e59b8ee51cc1cade7717 (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
#ifndef __JIN_LUA_NET_NETBUFFER_H
#define __JIN_LUA_NET_NETBUFFER_H

#include <cstring>
#include <cstdlib>
#include "common/l_common.h"

namespace JinEngine
{
	namespace Lua
	{

		extern const char* Jin_Lua_Buffer;

		void luaopen_Buffer(lua_State* L);

		namespace Net
		{

			class Buffer : public Object
			{
			public:
				Buffer(size_t s = 0)
					: size(s)
				{
					buffer = new char[size];
					memset(buffer, 0, size);
				}

				Buffer(const char* data, size_t s)
					: size(s)
				{
					buffer = new char[size];
					memcpy(buffer, data, size);
				}

				~Buffer()
				{
					if (buffer != nullptr)
					{
						delete[] buffer;
						buffer = nullptr;
						size = 0;
					}
				}

				void append(const void* data, size_t s)
				{
					if (data == nullptr)
						return;
					char* buf = buffer;
					buffer = new char[size + s];
					memcpy(buffer, buf, size);
					memcpy(buffer + size, data, s);
					delete[] buf;
					size += s;
					return;
				}

				/* grab and create a string */
				char* grabString(unsigned int* length, int offset = 0)
				{
					int l = offset;
					for (; l < size; ++l)
					{
						if (buffer[l] == 0)
							break;
					}
					*length = l - offset + 1;
					char* str = (char*)malloc(*length);
					memcpy(str, buffer + offset, *length);
					return str;
				}

				int grabInteger(int* length, int offset = 0)
				{
					*length = sizeof(int);
					return *((int*)(buffer + offset));
				}

				float grabFloat(int* length, int offset = 0)
				{
					*length = sizeof(float);
					return *((float*)(buffer + offset));
				}

				bool grabBoolean(int* length, int offset = 0)
				{
					*length = sizeof(bool);
					return *((bool*)(buffer + offset));
				}

				char* buffer;
				size_t size;

			};

		} // namespace Net
	} // namespace Lua
} // namespace JinEngine

#endif