File: snappymodule.cc

package info (click to toggle)
python-snappy 0.5-1.1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 112 kB
  • ctags: 98
  • sloc: python: 346; cpp: 218; ansic: 113; makefile: 18
file content (293 lines) | stat: -rw-r--r-- 8,811 bytes parent folder | download | duplicates (2)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
Copyright (c) 2011, Andres Moreira <andres@andresmoreira.com>
              2011, Felipe Cruz <felipecruz@loogica.net>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the authors nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANDRES MOREIRA BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Python.h"
#include <string.h>
#include <stdio.h>
#include <snappy-c.h>
#include "crc32c.h"

#define MODULE_VERSION "0.4.1"
#define RESIZE_TOLERATION 0.75

struct module_state {
    PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif


/* if support for Python 2.5 is dropped the bytesobject.h will do this for us */
#if PY_MAJOR_VERSION < 3
#define PyBytes_FromStringAndSize PyString_FromStringAndSize
#define _PyBytes_Resize _PyString_Resize
#define PyBytes_AS_STRING PyString_AS_STRING
#endif

static PyObject *SnappyCompressError,
    *SnappyUncompressError,
    *SnappyInvalidCompressedInputError,
    *SnappyCompressedLengthError;

static inline PyObject *
maybe_resize(PyObject *str, size_t expected_size, size_t actual_size)
{
    // Tolerate up to 25% slop, to reduce the likelihood of
    // reallocation and copying.
    if (actual_size != expected_size) {
	    if (actual_size < expected_size * RESIZE_TOLERATION) {
	        _PyBytes_Resize(&str, actual_size);
	        return str;
	    }
	    Py_SIZE(str) = actual_size;
    }
    return str;
}

static const char *
snappy_strerror(snappy_status status)
{
    switch (status) {
        case SNAPPY_OK:
	        return "no error";
        case SNAPPY_INVALID_INPUT:
	        return "invalid input";
        case SNAPPY_BUFFER_TOO_SMALL:
	        return "buffer too small";
        default:
	        return "unknown error";
    }
}

static PyObject *
snappy__compress(PyObject *self, PyObject *args)
{
    const char * input;
    int input_size;
    size_t compressed_size, actual_size;
    PyObject * result;
    snappy_status status;

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTuple(args, "y#", &input, &input_size))
#else
    if (!PyArg_ParseTuple(args, "s#", &input, &input_size))
#endif
        return NULL;

    // Ask for the max size of the compressed object.
    compressed_size = snappy_max_compressed_length(input_size);

    // Make snappy compression
    result = PyBytes_FromStringAndSize(NULL, compressed_size);
    if (result) {
        actual_size = compressed_size;
        status = snappy_compress(input, input_size, PyBytes_AS_STRING(result), &actual_size);
        if (status == SNAPPY_OK) {
            return maybe_resize(result, compressed_size, actual_size);
        }
        else {
            Py_DECREF(result);
        }
        PyErr_Format(SnappyCompressError,
    		 "Error while compressing: %s", snappy_strerror(status));
    }

    PyErr_Format(SnappyCompressError,
		 "Error while compressing: unable to acquire output string");
    return NULL;
}

static PyObject *
snappy__uncompress(PyObject *self, PyObject *args)
{
    const char * compressed;
    int comp_size;
    size_t uncomp_size, actual_size;
    PyObject * result;
    snappy_status status;

#if PY_MAJOR_VERSION >=3
    if (!PyArg_ParseTuple(args, "y#", &compressed, &comp_size))
#else
    if (!PyArg_ParseTuple(args, "s#", &compressed, &comp_size))
#endif
        return NULL;

    status = snappy_uncompressed_length(compressed, comp_size, &uncomp_size);
    if (status != SNAPPY_OK) {
        PyErr_SetString(SnappyCompressedLengthError,
            "Can not calculate uncompressed length");
        return NULL;
    }

    result = PyBytes_FromStringAndSize(NULL, uncomp_size);
    if (result) {
        actual_size = uncomp_size;
        status = snappy_uncompress(compressed, comp_size, PyBytes_AS_STRING(result), &actual_size);
        if (SNAPPY_OK == status) {
            return maybe_resize(result, uncomp_size, actual_size);
        }
        else {
            Py_DECREF(result);
        }
    }
    PyErr_Format(SnappyUncompressError,
		 "Error while decompressing: %s", snappy_strerror(status));
    return NULL;
}


static PyObject *
snappy__is_valid_compressed_buffer(PyObject *self, PyObject *args)
{
    const char * compressed;
    int comp_size;
    snappy_status status;

    if (!PyArg_ParseTuple(args, "s#", &compressed, &comp_size))
        return NULL;

    status = snappy_validate_compressed_buffer(compressed, comp_size);
    if (status == SNAPPY_OK)
        Py_RETURN_TRUE;
    Py_RETURN_FALSE;
}

static PyObject *
snappy__crc32c(PyObject *self, PyObject *args)
{
    const unsigned char * input;
    int input_size;

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTuple(args, "y#", &input, &input_size))
#else
    if (!PyArg_ParseTuple(args, "s#", &input, &input_size))
#endif
        return NULL;

    return PyLong_FromUnsignedLong(
            crc_finalize(crc_update(crc_init(), input, input_size)));
}

static PyMethodDef snappy_methods[] = {
    {"compress",  snappy__compress, METH_VARARGS,
        "Compress a string using the snappy library."},
    {"uncompress",  snappy__uncompress, METH_VARARGS,
        "Uncompress a string compressed with the snappy library."},
    {"decompress",  snappy__uncompress, METH_VARARGS,
        "Alias to Uncompress method, to be compatible with zlib."},
    {"isValidCompressed",  snappy__is_valid_compressed_buffer, METH_VARARGS,
        "Returns True if the compressed buffer is valid, False otherwise"},
    {"_crc32c",  snappy__crc32c, METH_VARARGS,
        "Generate an RFC3720, section 12.1 CRC-32C"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

#if PY_MAJOR_VERSION >= 3

static int snappy_traverse(PyObject *m, visitproc visit, void *arg) {
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

static int snappy_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}


static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "_snappy",
    NULL,
    sizeof(struct module_state),
    snappy_methods,
    NULL,
    snappy_traverse,
    snappy_clear,
    NULL
};


#define INITERROR return NULL

PyMODINIT_FUNC
PyInit__snappy(void)

#else
#define INITERROR return

PyMODINIT_FUNC
init_snappy(void)
#endif
{
    PyObject *m;

    #if PY_MAJOR_VERSION >= 3
    m = PyModule_Create(&moduledef);
    #else
    m = Py_InitModule("_snappy", snappy_methods);
    #endif

    if (m == NULL)
        INITERROR;

    SnappyCompressError = PyErr_NewException((char*)"snappy.CompressError",
        NULL, NULL);
    SnappyUncompressError = PyErr_NewException((char*)"snappy.UncompressError",
        NULL, NULL);
    SnappyInvalidCompressedInputError = PyErr_NewException(
        (char*)"snappy.InvalidCompressedInputError", NULL, NULL);
    SnappyCompressedLengthError = PyErr_NewException(
        (char*)"snappy.CompressedLengthError", NULL, NULL);

    Py_INCREF(SnappyCompressError);
    Py_INCREF(SnappyUncompressError);
    Py_INCREF(SnappyInvalidCompressedInputError);
    Py_INCREF(SnappyCompressedLengthError);

    PyModule_AddObject(m, "CompressError", SnappyCompressError);
    PyModule_AddObject(m, "UncompressError", SnappyUncompressError);
    PyModule_AddObject(m, "InvalidCompressedInputError",
        SnappyInvalidCompressedInputError);
    PyModule_AddObject(m, "CompressedLengthError", SnappyCompressedLengthError);

    /* Version = MODULE_VERSION */
    if (PyModule_AddStringConstant(m, "__version__", MODULE_VERSION))
        INITERROR;

#if PY_MAJOR_VERSION >= 3
    return m;
#endif
}