shithub: pdffs

ref: 34238e0feb181a0c120561486d4c86b054d112bc
dir: /dict.c/

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

Object *
pdfdict(char *p, char **e, int len)
{
	Object *o, *k, *v;
	KeyValue *kv;

	o = nil;
	if(len < 4 || p[0] != '<' || p[1] != '<'){
		werrstr("invalid dict");
		goto err;
	}
	p += 2;
	len -= 2;

	o = calloc(1, sizeof(*o));
	o->type = Odict;
	for(; len >= 2;){
		for(; len > 2 && isws(*p); p++, len--);
		if(len < 1){
			werrstr("too short");
			goto err;
		}

		if(p[0] == '>' && p[1] == '>'){
			p += 2;
			break;
		}

		if((k = pdfobject(p, e, len)) == nil)
			goto err;
		if(k->type != Oname){
			freeobject(k);
			werrstr("expected name as a key");
			goto err;
		}
		len -= *e - p;
		p = *e;

		if((v = pdfobject(p, e, len)) == nil){
			freeobject(k);
			goto err;
		}
		len -= *e - p;
		p = *e;

		if((kv = realloc(o->dict.kv, (o->dict.nkv+1)*sizeof(KeyValue))) == nil){
			freeobject(k);
			freeobject(v);
			goto err;
		}

		o->dict.kv = kv;
		kv[o->dict.nkv].key = strdup(k->name);
		freeobject(k);
		kv[o->dict.nkv++].value = v;
	}

	*e = p;

	return o;
err:
	freeobject(o);

	return nil;
}