summaryrefslogtreecommitdiff
path: root/src/base/buffer.c
blob: 13d3225a30fe628a47d15834f00fe62d8f5b8e0c (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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "buffer.h"

buffer_t * newBuffer(int n)
{
	buffer_t *new;

	new = malloc(sizeof(buffer_t));
	memset(new, 0, sizeof(buffer_t));
	new->alloc = n;
	new->data = malloc(n);
	memset(new->data , 0, n);

	return new;
}

int addBuffer(buffer_t *p, char *data, int len)
{
	assert( p != NULL );
	assert( data != NULL );
	assert( len >= 0 );
	
	if( p->size + len <= p->alloc )
	{
		memcpy(p->data + p->size, data, len);
		p->size += len;
		return 0;
	}

	return -1;
}

int cutBuffer(buffer_t *p, int len)
{
	assert( p != NULL );
	assert( len >= 0 );

	if( p->size - len >= 0 )
	{
		memmove(p->data, p->data + len, p->size - len);
		p->size -= len;
		return 0;
	}

	return -1;
}

int getBufferCount(buffer_t *p)
{
	char *begin;
	char *end;
	int count;
	int size;

	assert( p != NULL );

	count = 0;
	begin = p->data;
	size = p->size;

	while( ( end = memchr(begin, '\n', size) ) != NULL )
	{
		count++;
		size -= ( (end+1) - begin);
		begin = end+1;
	}

	//printf("count = %d\n", count);
	//printf("data = %s\n",  p->data);
	return count;
}

int getBufferLine(buffer_t *p, char *line, int len)
{
	char *end;
	int ret_len;

	assert( p != NULL );
	assert( line != NULL );
	assert( len >= 0 );

	end = NULL;

	end = memchr(p->data, '\n', p->size);

	if( end == NULL ) return -1;

	ret_len = (int) (end - p->data)+1;
	if( ret_len > len-1 ) ret_len = len-1;
	
	memset(line, 0, len);
	memcpy(line, p->data, ret_len);

	cutBuffer(p, ret_len);

	return ret_len;
}

int getBufferData(buffer_t *p, char *line, int len)
{
	assert( p != NULL );
	assert( line != NULL );
	assert( len >= 0 );

	if( p->size < len )
	{
		len = p->size;
	}

	memcpy(line, p->data, len);
	cutBuffer(p, len);

	return len;
}

void destroyBuffer(buffer_t *p)
{
	assert( p != NULL );

	if( p->data != NULL )free(p->data);
	free(p);
}