aboutsummaryrefslogtreecommitdiffstats
path: root/package/utils/rbextract/src/rle.c
blob: ca198ee9fcaaefe6f47d7e5d8398b484955449db (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
/*
 *  RLE decoding routine
 *
 *  Copyright (C) 2012 Gabor Juhos <juhosg@openwrt.org>
 *
 *  This program is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License version 2 as published
 *  by the Free Software Foundation.
 */

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <sys/types.h>
 
#include "rle.h"

int rle_decode(const unsigned char *src, size_t srclen,
	       unsigned char *dst, size_t dstlen,
	       size_t *src_done, size_t *dst_done)
{
	size_t srcpos, dstpos;
	int ret;

	srcpos = 0;
	dstpos = 0;
	ret = 1;

	/* sanity checks */
	if (!src || !srclen || !dst || !dstlen)
		goto out;

	while (1) {
		signed char count;

		if (srcpos >= srclen)
			break;

		count = (signed char) src[srcpos++];
		if (count == 0) {
			ret = 0;
			break;
		}

		if (count > 0) {
			unsigned char c;

			if (srcpos >= srclen)
				break;

			c = src[srcpos++];

			while (count--) {
				if (dstpos >= dstlen)
					break;

				dst[dstpos++] = c;
			}
		} else {
			count *= -1;

			while (count--) {
				if (srcpos >= srclen)
					break;
				if (dstpos >= dstlen)
					break;
				dst[dstpos++] = src[srcpos++];
			}
		}
	}

out:
	if (src_done)
		*src_done = srcpos;
	if (dst_done)
		*dst_done = dstpos;

	return ret;
}