summaryrefslogtreecommitdiffhomepage
path: root/buffer.c
blob: 026152210e29521b30c1aafc9ec0ea43735dbc98 (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
#include "buffer.h"

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int buffer_grow(struct buffer * b)
{
	int allocated = b->allocated + 1024;

	if (8192 < allocated)
	{
		errno = ENOMEM;
		return -1;
	}

	void * buffer = realloc(b->data, allocated);

	if (NULL == buffer)
		return -1;

	b->data = buffer;
	b->allocated = allocated;

	return allocated;
}

int buffer_prepare_at_least(int fd, struct buffer * in, int minimum_length)
{
	const int remaining_bytes = in->length - in->next;

	if (remaining_bytes >= minimum_length)
		return remaining_bytes;

	const int free_space = in->allocated + in->offset - in->length - 1;

	while (free_space < minimum_length)
		if (-1 == buffer_grow(in))
			return -1;

	if (0 < in->offset)
	{
		memmove(in->data, in->data + in->offset, in->length - in->offset);
		in->offset = 0;
		in->length -= in->offset;
	}

	int length = read(fd, in->data + in->length, free_space);

	if (-1 == length)
		return -1;

	in->length += length;

	return in->length - in->next;
}

int buffer_until(struct buffer * b, const char * pattern, int pattern_length)
{
	while (b->next + pattern_length <= b->length)
	{
		if (0 == strncmp(&b->data[b->next], pattern, pattern_length))
		{
			return b->next;
		}
		else
		{
			b->next++;
		}
	}

	return -1;
}