From 4a64ca903f26d8dd9a1c946027ddebeb82dd4b70 Mon Sep 17 00:00:00 2001
From: Pompolic <pompolic@special-circumstanc.es>
Date: Thu, 20 Feb 2020 16:07:40 +0100
Subject: [PATCH] WIP: filter function + move parser init subroutine before
 caller

---
 pdf.c | 54 ++++++++++++++++++++++++++++++++++--------------------
 1 file changed, 34 insertions(+), 20 deletions(-)

diff --git a/pdf.c b/pdf.c
index 4ed9247..72f2fb8 100644
--- a/pdf.c
+++ b/pdf.c
@@ -498,7 +498,23 @@ HParser *p_rldstring;
 HParser *kstream(HAllocator *, const HParsedToken *, void *);
 HParser *kxstream(HAllocator *, const HParsedToken *, void *);
 
-void init_runlengthdecode_parser(struct Env *aux);
+void
+init_runlengthdecode_parser(struct Env *aux)
+{
+	H_RULE(rldeod, h_ch(0x80));
+	H_ARULE(longlength, h_ch_range(0x81, 0xFF));
+	H_RULE(shortlength, h_ch_range(0x1, 0x7F));
+
+	H_RULE(shortdata, h_uint8());
+	H_RULE(longdata, h_uint8());
+
+	H_RULE(shortrun, h_length_value(shortlength, shortdata));
+	H_ARULE(longrun, SEQ(longlength, longdata));
+
+	H_RULE(rldstring, SEQ(CHX(shortrun, longrun), IGN(rldeod)));
+
+	p_rldstring = rldstring;
+}
 
 void
 init_parser(struct Env *aux)
@@ -705,7 +721,6 @@ init_parser(struct Env *aux)
 	/* debug parser to consume as much as possible */
 	H_RULE(pdfdbg,	SEQ(header, h_many(tail), body, OPT(xr_td), OPT(startxr)));
 
-
 	init_runlengthdecode_parser(aux);
 
 	/* global parser variables */
@@ -721,24 +736,6 @@ init_parser(struct Env *aux)
 	p_return_1 = h_action(epsilon, act_return_uint, (void *)1);
 }
 
-void
-init_runlengthdecode_parser(struct Env *aux)
-{
-	H_RULE(rldeod, h_ch(0x80));
-	H_ARULE(longlength, h_ch_range(0x81, 0xFF));
-	H_RULE(shortlength, h_ch_range(0x1, 0x7F));
-
-	H_RULE(shortdata, h_uint8());
-	H_RULE(longdata, h_uint8());
-
-	H_RULE(shortrun, h_length_value(shortlength, shortdata));
-	H_ARULE(longrun, SEQ(longlength, longdata));
-
-	H_RULE(rldstring, SEQ(CHX(shortrun, longrun), IGN(rldeod)));
-
-	p_rldstring = rldstring;
-}
-
 
 /*
  * lookup and resolution of indirect references
@@ -1093,6 +1090,21 @@ FlateDecode(const Dict *parms, HBytes b, HParser *p)
 	return res;
 }
 
+HParseResult *
+RunLengthDecode(const Dict *parms, HBytes b, HParser *p)
+{
+	HParseResult *res;
+
+	res = h_parse(p_rldstring, b.token, b.len);
+	if(!res)
+	{
+		fprintf(stderr, "parse error in RunLengthDecode filter\n");
+		return NULL;
+	}
+
+	return res;
+}
+
 /*
  * decode the bytes in 'b' according to metadata in the stream dictionary 'd'
  * and parse the result with 'p'.
@@ -1117,6 +1129,8 @@ decode_stream(const Dict *d, HBytes b, HParser *p)
 	assert(v->token_type == TT_BYTES);
 	if (bytes_eq(v->bytes, "FlateDecode"))
 		filter = FlateDecode;
+	else if (bytes_eq(v->bytes, "RunLengthDecode"))
+		filter = RunLengthDecode;
 	else
 		return NULL;		/* filter not supported */
 
-- 
GitLab