| 345 | } |
| 346 | |
| 347 | static int |
| 348 | decode(struct Bitstream *gif, struct DataBlock *block) |
| 349 | { |
| 350 | int code; |
| 351 | unsigned clear = 1 << gif->initial_bit_width; |
| 352 | |
| 353 | /* If a string is being decoded, return the next byte */ |
| 354 | if (gif->str_size != 0) { |
| 355 | return gif->string[--gif->str_size]; |
| 356 | } |
| 357 | |
| 358 | /* Get the next code, until code other than clear */ |
| 359 | while (TRUE) { |
| 360 | code = get_code(gif, block); |
| 361 | if ((unsigned) code != clear) break; |
| 362 | reset_decoder(gif); |
| 363 | } |
| 364 | |
| 365 | if (code == EOF) return EOF; |
| 366 | if ((unsigned) code == clear + 1) return END_OF_DATA; |
| 367 | if (code > gif->dict_size) return EOF; |
| 368 | |
| 369 | /* Add a new string to the dictionary */ |
| 370 | if (gif->last_code != 0xFFFF && gif->dict_size < SIZE(gif->dictionary)) { |
| 371 | unsigned next_code; |
| 372 | if (code < gif->dict_size) { |
| 373 | next_code = code; |
| 374 | } else { |
| 375 | next_code = gif->last_code; |
| 376 | } |
| 377 | while (next_code >= clear) { |
| 378 | next_code = gif->dictionary[next_code].next; |
| 379 | } |
| 380 | gif->dictionary[gif->dict_size].next = gif->last_code; |
| 381 | gif->dictionary[gif->dict_size].byte = next_code; |
| 382 | ++gif->dict_size; |
| 383 | if (gif->dict_size >= 1 << gif->bit_width |
| 384 | && gif->bit_width < MAX_LZW_BITS) { |
| 385 | ++gif->bit_width; |
| 386 | } |
| 387 | } |
| 388 | gif->last_code = code; |
| 389 | |
| 390 | /* code is less than gif->dict_size and not equal to clear or clear + 1 */ |
| 391 | /* Prepare the decoded string for return; note that it is stored in |
| 392 | * reverse order */ |
| 393 | while ((unsigned) code >= clear) { |
| 394 | gif->string[gif->str_size++] = gif->dictionary[code].byte; |
| 395 | code = gif->dictionary[code].next; |
| 396 | } |
| 397 | |
| 398 | return code; |
| 399 | } |
| 400 | |
| 401 | static int |
| 402 | get_code(struct Bitstream *gif, struct DataBlock *block) |
no test coverage detected