4 * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5 * Copyright 1999, 2000, 2001 Bernardo Innocenti <bernie@develer.com>
6 * This file is part of DevLib - See README.devlib for information.
9 * \brief General-purpose run-length {en,de}coding algorithm (implementation)
11 * Original source code from http://www.compuphase.com/compress.htm
14 * \author Bernardo Innocenti <bernie@develer.com>
19 *#* Revision 1.3 2005/11/04 16:20:02 bernie
20 *#* Fix reference to README.devlib in header.
22 *#* Revision 1.2 2004/08/25 14:12:09 rasky
23 *#* Aggiornato il comment block dei log RCS
25 *#* Revision 1.1 2004/08/04 02:35:54 bernie
26 *#* Import simple RLE algorithm.
34 * Run-length encode \a len bytes from the \a input buffer
35 * to the \a output buffer.
37 int rle(unsigned char *output, const unsigned char *input, int len)
49 first = input[index++];
51 /* Scan for bytes identical to the first one */
52 while ((index < len) && (index - count < 127) && (input[index] == first))
55 if (index - count == 1)
57 /* Failed to "replicate" the current byte. See how many to copy.
59 while ((index < len) && (index - count < 127))
61 /* Avoid a replicate run of only 2-bytes after a literal run.
62 * There is no gain in this, and there is a risc of loss if the
63 * run after the two identical bytes is another literal run.
64 * So search for 3 identical bytes.
66 if ((input[index] == input[index - 1]) &&
67 ((index > 1) && (input[index] == input[index - 2])))
69 /* Reset the index so we can back up these three identical
70 * bytes in the next run.
79 /* Output a run of uncompressed bytes: write length and values */
80 *out++ = (unsigned char)(count - index);
81 for (i = count; i < index; i++)
86 /* Output a compressed run: write length and value */
87 *out++ = (unsigned char)(index - count);
94 /* Output EOF marker */
97 return (out - output);
102 * Run-length decode from the \a input buffer to the \a output
105 * \note The output buffer must be large enough to accomodate
106 * all decoded output.
108 int unrle(unsigned char *output, const unsigned char *input)
119 count = (signed char)*input++;
138 return (out - output);