about summary refs log tree commit diff
path: root/src/engine/e_packer.c
blob: 9e77927d672ea2378436939fabf37aa251ae2173 (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */

#include "e_system.h"
#include "e_packer.h"
#include "e_compression.h"

/* useful for debugging */
#define packing_error(p) p->error = 1
/* #define packing_error(p) p->error = 1; dbg_break() */

void packer_reset(PACKER *p)
{
	p->error = 0;
	p->current = p->buffer;
	p->end = p->current + PACKER_BUFFER_SIZE;
}

void packer_add_int(PACKER *p, int i)
{
	if(p->error)
		return;
	
	/* make sure that we have space enough */
	if(p->end - p->current < 6)
	{
		dbg_break();
		p->error = 1;
	}
	else
		p->current = vint_pack(p->current, i);
}

void packer_add_string(PACKER *p, const char *str, int limit)
{
	if(p->error)
		return;
		
	if(limit > 0)
	{
		while(*str && limit != 0)
		{
			*p->current++ = *str++;
			limit--;
			
			if(p->current >= p->end)
			{
				packing_error(p);
				break;
			}
		}
		*p->current++ = 0;
	}
	else
	{
		while(*str)
		{
			*p->current++ = *str++;

			if(p->current >= p->end)
			{
				packing_error(p);
				break;
			}
		}
		*p->current++ = 0;
	}
}

void packer_add_raw(PACKER *p, const unsigned char *data, int size)
{
	if(p->error)
		return;
		
	if(p->current+size >= p->end)
	{
		packing_error(p);
		return;
	}
	
	while(size)
	{
		*p->current++ = *data++;
		size--;
	}
}

int packer_size(PACKER *p)
{
	return (const unsigned char *)p->current-(const unsigned char *)p->buffer;
}

const unsigned char *packer_data(PACKER *p)
{
	return (const unsigned char *)p->buffer;
}

void unpacker_reset(UNPACKER *p, const unsigned char *data, int size)
{
	p->error = 0;
	p->start = data;
	p->end = p->start + size;
	p->current = p->start;
}

int unpacker_get_int(UNPACKER *p)
{
	int i;
	if(p->error || p->current >= p->end)
		return 0;
	p->current = vint_unpack(p->current, &i);
	if(p->current > p->end)
	{
		packing_error(p);
		return 0;
	}
	return i;
}

const char *unpacker_get_string(UNPACKER *p)
{
	const char *ptr;
	if(p->error || p->current >= p->end)
		return "";
		
	ptr = (const char *)p->current;
	while(*p->current) /* skip the string */
	{
		p->current++;
		if(p->current == p->end)
		{
			packing_error(p);
			return "";
		}
	}
	p->current++;
	return ptr;
}

const unsigned char *unpacker_get_raw(UNPACKER *p, int size)
{
	const unsigned char *ptr = p->current;
	p->current += size;
	if(p->current > p->end)
	{
		packing_error(p);
		return 0;
	}
	return ptr;
}