commit 68108a4aa05489ffac8c941ae90c4d995f4eaa47 from: Sven M. Hallberg date: Wed Jun 14 13:16:21 2023 UTC statically allocate global lzw decoder context Avoids the use of malloc(). Also factors out table initialization to a function lzw_init_table(). commit - 1afde767c483e9672beed15c549717de2db061da commit + 68108a4aa05489ffac8c941ae90c4d995f4eaa47 blob - 7bb22711853d9cc43175aa795e1b504f6811abcb blob + b079e588e6363b61fd3b5cfe6c64418fb6649429 --- lzw.c +++ lzw.c @@ -1,6 +1,5 @@ #include #include -#include /* malloc, free */ #include /* memcpy */ #include "lzw.h" @@ -50,6 +49,20 @@ struct context { */ static void +lzw_init_table(struct context *ctx) +{ + int i; + + /* set up the static entries */ + for(i = 0; i < 256; i++) { + ctx->table[i].len = 1; + ctx->table[i].prefix = -1; /* none */ + ctx->table[i].first = i; + ctx->table[i].last = i; + } +} + +static void lzw_clear_table(struct context *ctx) { ctx->next = 258; @@ -96,7 +109,7 @@ lzw_code_string(struct context *ctx, int code, uint8_t */ HParser *p_lzwdata; -static struct context *context; +static struct context context; /* @@ -262,18 +275,8 @@ kcodeword(HAllocator *mm__, const HParsedToken *x, voi void init_LZW_parser() { - int i; - /* initialize global context variable, incl. static table entries */ - context = malloc(sizeof *context); - assert(context != NULL); - for(i = 0; i < 256; i++) - { - context->table[i].len = 1; - context->table[i].prefix = -1; /* none */ - context->table[i].first = i; - context->table[i].last = i; - } + lzw_init_table(&context); init_LZW_context(1); /* static parsers for code words of all possible sizes */ @@ -283,13 +286,13 @@ init_LZW_parser() p_code12 = h_bits(12, false); /* kcodeword() selects the appropriate parser based on context */ - H_RULE (codeword, h_bind(h_epsilon_p(), kcodeword, context)); + H_RULE (codeword, h_bind(h_epsilon_p(), kcodeword, &context)); H_VRULE (eod, codeword); - H_AVDRULE(clear, codeword, context); - H_AVDRULE(output, codeword, context); + H_AVDRULE(clear, codeword, &context); + H_AVDRULE(output, codeword, &context); - H_ADRULE(lzwblock, h_right(clear, h_many(output)), context); + H_ADRULE(lzwblock, h_right(clear, h_many(output)), &context); H_ARULE (lzwdata, h_left(h_many1(lzwblock), eod)); // XXX validate that the last byte is zero-padded? // XXX require h_end_p()? @@ -307,6 +310,6 @@ parse_LZW_data(const uint8_t *input, size_t length) void init_LZW_context(int earlychange) { - lzw_clear_table(context); - context->earlychange = !!earlychange; + lzw_clear_table(&context); + context.earlychange = !!earlychange; }