summaryrefslogtreecommitdiff
path: root/filter/buffer.c
blob: 1b7a0793f450ff3ae3fb092ded2d4d4d140ce570 (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
#include <fitz.h>

fz_error *
fz_newbuffer(fz_buffer **bp, int size)
{
	fz_buffer *b;

	b = *bp = fz_malloc(sizeof(fz_buffer));
	if (!b) return fz_outofmem;

	b->ownsdata = 1;
	b->bp = fz_malloc(size);
	if (!b->bp) { fz_free(b); return fz_outofmem; }

	b->rp = b->bp;
	b->wp = b->bp;
	b->ep = b->bp + size;
	b->eof = 0;

	return nil;
}

fz_error *
fz_newbufferwithdata(fz_buffer **bp, unsigned char *data, int size)
{
	fz_buffer *b;

	b = *bp = fz_malloc(sizeof(fz_buffer));
	if (!b) return fz_outofmem;

	b->ownsdata = 0;
	b->bp = data;

	b->rp = b->bp;
	b->wp = b->bp + size;
	b->ep = b->bp + size;
	b->eof = 0;

	return nil;
}

void
fz_dropbuffer(fz_buffer *buf)
{
	if (buf->ownsdata)
		fz_free(buf->bp);
	fz_free(buf);
}

fz_error *
fz_growbuffer(fz_buffer *buf)
{
	unsigned char *newbp;

	int rp = buf->rp - buf->bp;
	int wp = buf->wp - buf->bp;
	int ep = buf->ep - buf->bp;

	assert(buf->ownsdata);

	newbp = fz_realloc(buf->bp, ep * 2);
	if (!newbp) return fz_outofmem;

	buf->bp = newbp;
	buf->rp = buf->bp + rp;
	buf->wp = buf->bp + wp;
	buf->ep = buf->bp + ep * 2;

	return nil;
}

fz_error *
fz_rewindbuffer(fz_buffer *buf)
{
	assert(buf->ownsdata);
	memmove(buf->bp, buf->rp, buf->wp - buf->rp);
	buf->wp = buf->bp + (buf->wp - buf->rp);
	buf->rp = buf->bp;
	return nil;
}