LZSS

lzss source code

/**************************************************************
LZSS.C -- A Data Compression Program
(tab = 4 spaces)
***************************************************************
4/6/1989 Haruhiko Okumura
Use, distribute, and modify this program freely.
Please send me your improved versions.
PC-VAN SCIENCE
NIFTY-Serve PAF01022
CompuServe 74050,1022
**************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define N 4096 /* size of ring buffer */
#define F   18 /* upper limit for match_length */
#define THRESHOLD 2 /* encode string into position and length
                        if match_length is greater than this */
#define NIL N /* index for root of binary search trees */

unsigned long int
textsize = 0, /* text size counter */
codesize = 0, /* code size counter */
printcount = 0; /* counter for reporting progress every 1K bytes */
unsigned char
text_buf[N + F - 1]; /* ring buffer of size N,
with extra F-1 bytes to facilitate string comparison */
int match_position, match_length, /* of longest match. These are
set by the InsertNode() procedure. */
lson[N + 1], rson[N + 257], dad[N + 1]; /* left & right children &
parents -- These constitute binary search trees. */
FILE *infile, *outfile; /* input & output files */

void InitTree(void) /* initialize trees */
{
    int i;

    /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and
    left children of node i. These nodes need not be initialized.
    Also, dad[i] is the parent of node i. These are initialized to
    NIL (= N), which stands for 'not used.'
    For i = 0 to 255, rson[N + i + 1] is the root of the tree
    for strings that begin with character i. These are initialized
    to NIL. Note there are 256 trees. */

    for (i = N + 1; i <= N + 256; i++) rson[i] = NIL;
    for (i = 0; i < N; i++) dad[i] = NIL;
}

void InsertNode(int r)
/* Inserts string of length F, text_buf[r..r+F-1], into one of the
trees (text_buf[r]'th tree) and returns the longest-match position
and length via the global variables match_position and match_length.
If match_length = F, then removes the old node in favor of the new
one, because the old one will be deleted sooner.
Note r plays double role, as tree node and position in buffer. */
{
    int i, p, cmp;
    unsigned char *key;

    cmp = 1; key = &text_buf[r]; p = N + 1 + key[0];
    rson[r] = lson[r] = NIL; match_length = 0;
    for ( ; ; ) {
        if (cmp >= 0) {
            if (rson[p] != NIL) p = rson[p];
            else { rson[p] = r; dad[r] = p; return; }
        } else {
            if (lson[p] != NIL) p = lson[p];
            else { lson[p] = r; dad[r] = p; return; }
        }
        for (i = 1; i < F; i++)
            if ((cmp = key[i] - text_buf[p + i]) != 0) break;
        if (i > match_length) {
            match_position = p;
            if ((match_length = i) >= F) break;
        }
    }
    dad[r] = dad[p]; lson[r] = lson[p]; rson[r] = rson[p];
    dad[lson[p]] = r; dad[rson[p]] = r;
    if (rson[dad[p]] == p) rson[dad[p]] = r;
    else                  lson[dad[p]] = r;
    dad[p] = NIL; /* remove p */
}

void DeleteNode(int p) /* deletes node p from tree */
{
    int q;

    if (dad[p] == NIL) return; /* not in tree */
    if (rson[p] == NIL) q = lson[p];
    else if (lson[p] == NIL) q = rson[p];
    else {
        q = lson[p];
        if (rson[q] != NIL) {
            do { q = rson[q]; } while (rson[q] != NIL);
            rson[dad[q]] = lson[q]; dad[lson[q]] = dad[q];
            lson[q] = lson[p]; dad[lson[p]] = q;
        }
        rson[q] = rson[p]; dad[rson[p]] = q;
    }
    dad[q] = dad[p];
    if (rson[dad[p]] == p) rson[dad[p]] = q; else lson[dad[p]] = q;
    dad[p] = NIL;
}

void Encode(void)
{
    int i, c, len, r, s, last_match_length, code_buf_ptr;
    unsigned char code_buf[17], mask;

    InitTree(); /* initialize trees */
    code_buf[0] = 0; /* code_buf[1..16] saves eight units of code, and
                         code_buf[0] works as eight flags, "1" representing that the unit
                         is an unencoded letter (1 byte), "0" a position-and-length pair
                         (2 bytes). Thus, eight units require at most 16 bytes of code. */
    code_buf_ptr = mask = 1;
    s = 0; r = N - F;
    for (i = s; i < r; i++) text_buf[i] = ' '; /* Clear the buffer with
                                                   any character that will appear often. */
    for (len = 0; len < F && (c = getc(infile)) != EOF; len++)
        text_buf[r + len] = c; /* Read F bytes into the last F bytes of
                                   the buffer */
    if ((textsize = len) == 0) return; /* text of size zero */
    for (i = 1; i <= F; i++) InsertNode(r - i); /* Insert the F strings,
                                                    each of which begins with one or more 'space' characters. Note
                                                    the order in which these strings are inserted. This way,
                                                    degenerate trees will be less likely to occur. */
    InsertNode(r); /* Finally, insert the whole string just read. The
                       global variables match_length and match_position are set. */
    do {
        if (match_length > len) match_length = len; /* match_length
                                                        may be spuriously long near the end of text. */
        if (match_length <= THRESHOLD) {
            match_length = 1; /* Not long enough match. Send one byte. */
            code_buf[0] |= mask; /* 'send one byte' flag */
            code_buf[code_buf_ptr++] = text_buf[r]; /* Send uncoded. */
        } else {
            code_buf[code_buf_ptr++] = (unsigned char) match_position;
            code_buf[code_buf_ptr++] = (unsigned char)
                (((match_position >> 4) & 0xf0)
                | (match_length - (THRESHOLD + 1))); /* Send position and
            length pair. Note match_length > THRESHOLD. */
        }
        if ((mask <<= 1) == 0) { /* Shift mask left one bit. */
            for (i = 0; i < code_buf_ptr; i++) /* Send at most 8 units of */
            putc(code_buf[i], outfile);    /* code together */
            codesize += code_buf_ptr;
            code_buf[0] = 0; code_buf_ptr = mask = 1;
        }
        last_match_length = match_length;
        for (i = 0; i < last_match_length &&
            (c = getc(infile)) != EOF; i++) {
            DeleteNode(s); /* Delete old strings and */
            text_buf[s] = c; /* read new bytes */
            if (s < F - 1) text_buf[s + N] = c; /* If the position is
                                                    near the end of buffer, extend the buffer to make
                                                    string comparison easier. */
            s = (s + 1) & (N - 1); r = (r + 1) & (N - 1);
            /* Since this is a ring buffer, increment the position
               modulo N. */
            InsertNode(r); /* Register the string in text_buf[r..r+F-1] */
        }
        if ((textsize += i) > printcount) {
            printf("%12ld\r", textsize); printcount += 1024;
            /* Reports progress each time the textsize exceeds
               multiples of 1024. */
        }
        while (i++ < last_match_length) { /* After the end of text, */
            DeleteNode(s); /* no need to read, but */
            s = (s + 1) & (N - 1); r = (r + 1) & (N - 1);
            if (--len) InsertNode(r); /* buffer may not be empty. */
        }
    } while (len > 0); /* until length of string to be processed is zero */
    if (code_buf_ptr > 1) { /* Send remaining code. */
        for (i = 0; i < code_buf_ptr; i++) putc(code_buf[i], outfile);
        codesize += code_buf_ptr;
    }
    printf("In : %ld bytes\n", textsize); /* Encoding is done. */
    printf("Out: %ld bytes\n", codesize);
    printf("Out/In: %.3f\n", (double)codesize / textsize);
}

void Decode(void) /* Just the reverse of Encode(). */
{
    int i, j, k, r, c;
    unsigned int flags;

    for (i = 0; i < N - F; i++) text_buf[i] = ' ';
    r = N - F; flags = 0;
    for ( ; ; ) {
        if (((flags >>= 1) & 256) == 0) {
            if ((c = getc(infile)) == EOF) break;
            flags = c | 0xff00; /* uses higher byte cleverly */
        } /* to count eight */
        if (flags & 1) {
            if ((c = getc(infile)) == EOF) break;
            putc(c, outfile); text_buf[r++] = c; r &= (N - 1);
        } else {
            if ((i = getc(infile)) == EOF) break;
            if ((j = getc(infile)) == EOF) break;
            i |= ((j & 0xf0) << 4); j = (j & 0x0f) + THRESHOLD;
            for (k = 0; k <= j; k++) {
                c = text_buf[(i + k) & (N - 1)];
                putc(c, outfile); text_buf[r++] = c; r &= (N - 1);
            }
        }
    }
}

int main(int argc, char *argv[])
{
    char *s;

    if (argc != 4) {
        printf("'lzss e file1 file2' encodes file1 into file2.\n"
        "'lzss d file2 file1' decodes file2 into file1.\n");
        return EXIT_FAILURE;
    }
    if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
        || (s = argv[2], (infile = fopen(s, "rb")) == NULL)
        || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
        printf("??? %s\n", s); return EXIT_FAILURE;
    }
    if (toupper(*argv[1]) == 'E') Encode(); else Decode();
    fclose(infile); fclose(outfile);
    return EXIT_SUCCESS;
} 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容