1 /* deflate_rle.c -- compress data using RLE strategy of deflation algorithm
2 *
3 * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
4 * For conditions of distribution and use, see copyright notice in zlib.h
5 */
6
7 #include "zbuild.h"
8 #include "deflate.h"
9 #include "deflate_p.h"
10 #include "functable.h"
11
12 /* ===========================================================================
13 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
14 * one. Do not maintain a hash table. (It will be regenerated if this run of
15 * deflate switches away from Z_RLE.)
16 */
deflate_rle(deflate_state * s,int flush)17 Z_INTERNAL block_state deflate_rle(deflate_state *s, int flush) {
18 int bflush = 0; /* set if current block must be flushed */
19 unsigned int prev; /* byte at distance one to match */
20 unsigned char *scan, *strend; /* scan goes up to strend for length of run */
21 uint32_t match_len = 0;
22
23 for (;;) {
24 /* Make sure that we always have enough lookahead, except
25 * at the end of the input file. We need STD_MAX_MATCH bytes
26 * for the longest run, plus one for the unrolled loop.
27 */
28 if (s->lookahead <= STD_MAX_MATCH) {
29 fill_window(s);
30 if (s->lookahead <= STD_MAX_MATCH && flush == Z_NO_FLUSH)
31 return need_more;
32 if (s->lookahead == 0)
33 break; /* flush the current block */
34 }
35
36 /* See how many times the previous byte repeats */
37 if (s->lookahead >= STD_MIN_MATCH && s->strstart > 0) {
38 scan = s->window + s->strstart - 1;
39 prev = *scan;
40 if (prev == *++scan && prev == *++scan && prev == *++scan) {
41 strend = s->window + s->strstart + STD_MAX_MATCH;
42 do {
43 } while (prev == *++scan && prev == *++scan &&
44 prev == *++scan && prev == *++scan &&
45 prev == *++scan && prev == *++scan &&
46 prev == *++scan && prev == *++scan &&
47 scan < strend);
48 match_len = STD_MAX_MATCH - (unsigned int)(strend - scan);
49 match_len = MIN(match_len, s->lookahead);
50 }
51 Assert(scan <= s->window + s->window_size - 1, "wild scan");
52 }
53
54 /* Emit match if have run of STD_MIN_MATCH or longer, else emit literal */
55 if (match_len >= STD_MIN_MATCH) {
56 check_match(s, s->strstart, s->strstart - 1, match_len);
57
58 bflush = zng_tr_tally_dist(s, 1, match_len - STD_MIN_MATCH);
59
60 s->lookahead -= match_len;
61 s->strstart += match_len;
62 match_len = 0;
63 } else {
64 /* No match, output a literal byte */
65 bflush = zng_tr_tally_lit(s, s->window[s->strstart]);
66 s->lookahead--;
67 s->strstart++;
68 }
69 if (bflush)
70 FLUSH_BLOCK(s, 0);
71 }
72 s->insert = 0;
73 if (flush == Z_FINISH) {
74 FLUSH_BLOCK(s, 1);
75 return finish_done;
76 }
77 if (s->sym_next)
78 FLUSH_BLOCK(s, 0);
79 return block_done;
80 }
81