summaryrefslogtreecommitdiff
path: root/fitz/filt_ahxd.c
blob: 5e1fe17c0fc6deddf0d80cd4f696d275e495b315 (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
#include "fitz_base.h"
#include "fitz_stream.h"

typedef struct fz_ahxd_s fz_ahxd;

struct fz_ahxd_s
{
	fz_filter super;
	int odd;
	int a;
};

static inline int iswhite(int a)
{
	switch (a) {
	case '\n': case '\r': case '\t': case ' ':
	case '\0': case '\f': case '\b': case 0177:
		return 1;
	}
	return 0;
}

static inline int ishex(int a)
{
	return (a >= 'A' && a <= 'F') ||
		(a >= 'a' && a <= 'f') ||
		(a >= '0' && a <= '9');
}

static inline int fromhex(int a)
{
	if (a >= 'A' && a <= 'F')
		return a - 'A' + 0xA;
	if (a >= 'a' && a <= 'f')
		return a - 'a' + 0xA;
	if (a >= '0' && a <= '9')
		return a - '0';
	return 0;
}

fz_error
fz_newahxd(fz_filter **fp, fz_obj *params)
{
	FZ_NEWFILTER(fz_ahxd, f, ahxd);
	f->odd = 0;
	f->a = 0;
	return fz_okay;
}

void
fz_dropahxd(fz_filter *f)
{
}

fz_error
fz_processahxd(fz_filter *filter, fz_buffer *in, fz_buffer *out)
{
	fz_ahxd *f = (fz_ahxd*)filter;
	int b, c;

	while (1)
	{
		if (in->rp == in->wp)
			return fz_ioneedin;

		if (out->wp == out->ep)
			return fz_ioneedout;

		c = *in->rp++;

		if (ishex(c)) {
			if (!f->odd) {
				f->a = fromhex(c);
				f->odd = 1;
			}
			else {
				b = fromhex(c);
				*out->wp++ = (f->a << 4) | b;
				f->odd = 0;
			}
		}

		else if (c == '>') {
			if (f->odd)
				*out->wp++ = (f->a << 4);
			return fz_iodone;
		}

		else if (!iswhite(c)) {
			return fz_throw("bad data in ahxd: '%c'", c);
		}
	}
}

void
fz_pushbackahxd(fz_filter *filter, fz_buffer *in, fz_buffer *out, int n)
{
	int k;

	assert(filter->process == fz_processahxd);
	assert(out->wp - n >= out->rp);

	k = 0;
	while (k < n * 2) {
		in->rp --;
		if (ishex(*in->rp))
			k ++;
	}

	out->wp -= n;
}