shithub: pdffs

ref: a9feb43f707673f7139317fac35e843d3bab7983
dir: /f_asciihex.c/

View raw version
#include <u.h>
#include <libc.h>
#include "pdf.h"

/* 7.4.2 ASCIIHexDecode filter */

static int
hexc(int c)
{
	if(c >= 'A' && c <= 'F')
		return c - 'A' + 10;
	if(c >= '0' && c <= '9')
		return c - '0';
	if(c >= 'a' && c <= 'f')
		return c - 'a' + 10;
	return -1;
}

static int
flreadall(void *aux, Buffer *bi, Buffer *bo)
{
	int i, insz, c, c2;
	uchar *in, b;

	USED(aux);

	in = bufdata(bi, &insz);
	for(i = 0; i < insz;){
		if((c = hexc(in[i++])) < 0){
			if(isws(in[i-1]))
				continue;
			if(in[i-1] == '>')
				break;
badchar:
			werrstr("invalid char %02x", in[i-1]);
			return -1;
		}
		c2 = 0;
		if(i < insz && (c2 = hexc(in[i++])) < 0){
			if(in[i-1] != '>')
				c2 = 0;
			else
				goto badchar;
		}
		b = c<<4 | c2;
		bufput(bo, &b, 1);
	}
	bi->off = bi->sz;

	return 0;
}

Filter filterASCIIHex = {
	.name = "ASCIIHexDecode",
	.readall = flreadall,
};