summaryrefslogtreecommitdiff
path: root/fitz/stm_open.c
blob: 48e9587fce52f246ffed255024818b0c513de2a4 (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
/*
 * Creation and destruction.
 */

#include "fitz_base.h"
#include "fitz_stream.h"

static fz_stream *
newstm(int kind)
{
	fz_stream *stm;

	stm = fz_malloc(sizeof(fz_stream));

	stm->refs = 1;
	stm->kind = kind;
	stm->dead = 0;
	stm->error = fz_okay;
	stm->buffer = nil;

	stm->chain = nil;
	stm->filter = nil;
	stm->file = -1;

	return stm;
}

fz_stream *
fz_keepstream(fz_stream *stm)
{
	stm->refs ++;
	return stm;
}

void
fz_dropstream(fz_stream *stm)
{
	stm->refs --;
	if (stm->refs == 0)
	{
		if (stm->error)
		{
			fz_catch(stm->error, "dropped unhandled ioerror");
			stm->error = fz_okay;
		}

		switch (stm->kind)
		{
		case FZ_SFILE:
			close(stm->file);
			break;
		case FZ_SFILTER:
			fz_dropfilter(stm->filter);
			fz_dropstream(stm->chain);
			break;
		case FZ_SBUFFER:
			break;
		}

		fz_dropbuffer(stm->buffer);
		fz_free(stm);
	}
}

fz_error fz_openrfile(fz_stream **stmp, char *path)
{
	fz_stream *stm;

	stm = newstm(FZ_SFILE);

	stm->buffer = fz_newbuffer(FZ_BUFSIZE);

	stm->file = open(path, O_BINARY | O_RDONLY, 0666);
	if (stm->file < 0)
	{
		fz_dropbuffer(stm->buffer);
		fz_free(stm);
		return fz_throw("syserr: open '%s': %s", path, strerror(errno));
	}

	*stmp = stm;
	return fz_okay;
}

fz_stream * fz_openrfilter(fz_filter *flt, fz_stream *src)
{
	fz_stream *stm;

	stm = newstm(FZ_SFILTER);
	stm->buffer = fz_newbuffer(FZ_BUFSIZE);
	stm->chain = fz_keepstream(src);
	stm->filter = fz_keepfilter(flt);

	return stm;
}

fz_stream * fz_openrbuffer(fz_buffer *buf)
{
	fz_stream *stm;

	stm = newstm(FZ_SBUFFER);
	stm->buffer = fz_keepbuffer(buf);
	stm->buffer->eof = 1;

	return stm;
}

fz_stream * fz_openrmemory(unsigned char *mem, int len)
{
	fz_buffer *buf;
	fz_stream *stm;

	buf = fz_newbufferwithmemory(mem, len);
	stm = fz_openrbuffer(buf);
	fz_dropbuffer(buf);

	return stm;
}