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

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

#include <lua.h>

#include "stream.h"

void grow(lua_State * L, struct buffer * b)
{
	int allocated = b->allocated + 1024;

	if (8192 < allocated)
	{
		lua_pushliteral(L, "Too large buffer");
		lua_error(L);
	}

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

	if (NULL == buffer)
	{
		lua_pushliteral(L, "Could not grow buffer");
		lua_error(L);
	}

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

int read_more(lua_State * L, struct stream * s, int minimum_length, lua_KContext ctx)
{
	const int free_space = s->in.allocated + s->in.offset - s->in.length - 1;

	while (free_space < minimum_length)
	{
		grow(L, &s->in);
	}

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

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

	if (-1 == length)
	{
		if (EWOULDBLOCK == errno || EAGAIN == errno)
		{
			return lua_yieldk(L, 0, ctx, stream_readk);
		}
		else
		{
			lua_pushstring(L, strerror(errno));
			return lua_error(L);
		}
	}

	s->in.length += length;

	return length;
}

int prepare_at_least(lua_State * L, struct stream * s, int minimum_length, lua_KContext ctx)
{
	const int remaining_bytes = s->in.length - s->in.next;

	if (remaining_bytes < minimum_length)
	{
		return read_more(L, s, minimum_length, ctx);
	}

	return remaining_bytes;
}

int 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;
}