aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Pillow/py3/libImaging/PackDecode.c
blob: 7dd432b91c2f49835951a01321f878020a3777e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * The Python Imaging Library.
 * $Id$
 *
 * decoder for PackBits image data.
 *
 * history:
 * 96-04-19 fl Created
 *
 * Copyright (c) Fredrik Lundh 1996.
 * Copyright (c) Secret Labs AB 1997.
 *
 * See the README file for information on usage and redistribution.
 */

#include "Imaging.h"

int
ImagingPackbitsDecode(
    Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) {
    UINT8 n;
    UINT8 *ptr;
    int i;

    ptr = buf;

    for (;;) {
        if (bytes < 1) {
            return ptr - buf;
        }

        if (ptr[0] & 0x80) {
            if (ptr[0] == 0x80) {
                /* Nop */
                ptr++;
                bytes--;
                continue;
            }

            /* Run */
            if (bytes < 2) {
                return ptr - buf;
            }

            for (n = 257 - ptr[0]; n > 0; n--) {
                if (state->x >= state->bytes) {
                    /* state->errcode = IMAGING_CODEC_OVERRUN; */
                    break;
                }
                state->buffer[state->x++] = ptr[1];
            }

            ptr += 2;
            bytes -= 2;

        } else {
            /* Literal */
            n = ptr[0] + 2;

            if (bytes < n) {
                return ptr - buf;
            }

            for (i = 1; i < n; i++) {
                if (state->x >= state->bytes) {
                    /* state->errcode = IMAGING_CODEC_OVERRUN; */
                    break;
                }
                state->buffer[state->x++] = ptr[i];
            }

            ptr += n;
            bytes -= n;
        }

        if (state->x >= state->bytes) {
            /* Got a full line, unpack it */
            state->shuffle(
                (UINT8 *)im->image[state->y + state->yoff] +
                    state->xoff * im->pixelsize,
                state->buffer,
                state->xsize);

            state->x = 0;

            if (++state->y >= state->ysize) {
                /* End of file (errcode = 0) */
                return -1;
            }
        }
    }
}