aboutsummaryrefslogtreecommitdiff
path: root/src/lua/net/Buffer.h
blob: 035da5cc80c0c3330e5a733cf062e21527097405 (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
#ifndef __JIN_LUA_NET_NETBUFFER_H
#define __JIN_LUA_NET_NETBUFFER_H

#include <cstring>
#include <cstdlib>
#include "../luaopen_types.h"

namespace jin
{
namespace lua
{
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;
        }

        const char* grabString(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;

    };

} // net
} // lua
} // jin

#endif