summaryrefslogtreecommitdiff
path: root/src/buffer.c
blob: 37cbdfce09898ddcd4c04319aa33573fb45d0a60 (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

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

#include "main.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 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 getData(buffer_t *p, char *line, int len)
{
	assert( p != NULL );
	assert( line != NULL );
	assert( len >= 0 );

	if( p->size < len)return -1;
	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);
}

/*
int main()
{
	buffer_t *p;
	char str[64];
	char *s[] = {"hello world\n", "dalsi riadok\n", "koniec\n", NULL};
	int i;

	p = newBuffer(1024 * 10);

	for( i = 0 ; s[i] != NULL ; i++)
		addBuffer(p, s[i], strlen(s[i]));

	while( getBufferLine(p, str, 64) > 0 )
	{
		printf("str = %s\n", str);
	}

	destroyBuffer(p);
	return 0;
}
*/