snappymodule.cc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. Copyright (c) 2011, Andres Moreira <andres@andresmoreira.com>
  3. 2011, Felipe Cruz <felipecruz@loogica.net>
  4. All rights reserved.
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions are met:
  7. * Redistributions of source code must retain the above copyright
  8. notice, this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. * Neither the name of the authors nor the
  13. names of its contributors may be used to endorse or promote products
  14. derived from this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  16. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. DISCLAIMED. IN NO EVENT SHALL ANDRES MOREIRA BE LIABLE FOR ANY
  19. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  20. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  21. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  22. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Python.h"
  27. #include <string.h>
  28. #include <stdio.h>
  29. #include <snappy-c.h>
  30. #include "crc32c.h"
  31. #define MODULE_VERSION "0.4.1"
  32. #define RESIZE_TOLERATION 0.75
  33. struct module_state {
  34. PyObject *error;
  35. };
  36. #if PY_MAJOR_VERSION >= 3
  37. #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
  38. #else
  39. #define GETSTATE(m) (&_state)
  40. static struct module_state _state;
  41. #endif
  42. /* if support for Python 2.5 is dropped the bytesobject.h will do this for us */
  43. #if PY_MAJOR_VERSION < 3
  44. #define PyBytes_FromStringAndSize PyString_FromStringAndSize
  45. #define _PyBytes_Resize _PyString_Resize
  46. #define PyBytes_AS_STRING PyString_AS_STRING
  47. #endif
  48. static PyObject *SnappyCompressError,
  49. *SnappyUncompressError,
  50. *SnappyInvalidCompressedInputError,
  51. *SnappyCompressedLengthError;
  52. static inline PyObject *
  53. maybe_resize(PyObject *str, size_t expected_size, size_t actual_size)
  54. {
  55. // Tolerate up to 25% slop, to reduce the likelihood of
  56. // reallocation and copying.
  57. if (actual_size != expected_size) {
  58. if (actual_size < expected_size * RESIZE_TOLERATION) {
  59. _PyBytes_Resize(&str, actual_size);
  60. return str;
  61. }
  62. Py_SIZE(str) = actual_size;
  63. }
  64. return str;
  65. }
  66. static const char *
  67. snappy_strerror(snappy_status status)
  68. {
  69. switch (status) {
  70. case SNAPPY_OK:
  71. return "no error";
  72. case SNAPPY_INVALID_INPUT:
  73. return "invalid input";
  74. case SNAPPY_BUFFER_TOO_SMALL:
  75. return "buffer too small";
  76. default:
  77. return "unknown error";
  78. }
  79. }
  80. static PyObject *
  81. snappy__compress(PyObject *self, PyObject *args)
  82. {
  83. const char * input;
  84. int input_size;
  85. size_t compressed_size, actual_size;
  86. PyObject * result;
  87. snappy_status status;
  88. #if PY_MAJOR_VERSION >= 3
  89. if (!PyArg_ParseTuple(args, "y#", &input, &input_size))
  90. #else
  91. if (!PyArg_ParseTuple(args, "s#", &input, &input_size))
  92. #endif
  93. return NULL;
  94. // Ask for the max size of the compressed object.
  95. compressed_size = snappy_max_compressed_length(input_size);
  96. // Make snappy compression
  97. result = PyBytes_FromStringAndSize(NULL, compressed_size);
  98. if (result) {
  99. actual_size = compressed_size;
  100. status = snappy_compress(input, input_size, PyBytes_AS_STRING(result), &actual_size);
  101. if (status == SNAPPY_OK) {
  102. return maybe_resize(result, compressed_size, actual_size);
  103. }
  104. else {
  105. Py_DECREF(result);
  106. }
  107. PyErr_Format(SnappyCompressError,
  108. "Error while compressing: %s", snappy_strerror(status));
  109. }
  110. PyErr_Format(SnappyCompressError,
  111. "Error while compressing: unable to acquire output string");
  112. return NULL;
  113. }
  114. static PyObject *
  115. snappy__uncompress(PyObject *self, PyObject *args)
  116. {
  117. const char * compressed;
  118. int comp_size;
  119. size_t uncomp_size, actual_size;
  120. PyObject * result;
  121. snappy_status status;
  122. #if PY_MAJOR_VERSION >=3
  123. if (!PyArg_ParseTuple(args, "y#", &compressed, &comp_size))
  124. #else
  125. if (!PyArg_ParseTuple(args, "s#", &compressed, &comp_size))
  126. #endif
  127. return NULL;
  128. status = snappy_uncompressed_length(compressed, comp_size, &uncomp_size);
  129. if (status != SNAPPY_OK) {
  130. PyErr_SetString(SnappyCompressedLengthError,
  131. "Can not calculate uncompressed length");
  132. return NULL;
  133. }
  134. result = PyBytes_FromStringAndSize(NULL, uncomp_size);
  135. if (result) {
  136. actual_size = uncomp_size;
  137. status = snappy_uncompress(compressed, comp_size, PyBytes_AS_STRING(result), &actual_size);
  138. if (SNAPPY_OK == status) {
  139. return maybe_resize(result, uncomp_size, actual_size);
  140. }
  141. else {
  142. Py_DECREF(result);
  143. }
  144. }
  145. PyErr_Format(SnappyUncompressError,
  146. "Error while decompressing: %s", snappy_strerror(status));
  147. return NULL;
  148. }
  149. static PyObject *
  150. snappy__is_valid_compressed_buffer(PyObject *self, PyObject *args)
  151. {
  152. const char * compressed;
  153. int comp_size;
  154. snappy_status status;
  155. if (!PyArg_ParseTuple(args, "s#", &compressed, &comp_size))
  156. return NULL;
  157. status = snappy_validate_compressed_buffer(compressed, comp_size);
  158. if (status == SNAPPY_OK)
  159. Py_RETURN_TRUE;
  160. Py_RETURN_FALSE;
  161. }
  162. static PyObject *
  163. snappy__crc32c(PyObject *self, PyObject *args)
  164. {
  165. const unsigned char * input;
  166. int input_size;
  167. #if PY_MAJOR_VERSION >= 3
  168. if (!PyArg_ParseTuple(args, "y#", &input, &input_size))
  169. #else
  170. if (!PyArg_ParseTuple(args, "s#", &input, &input_size))
  171. #endif
  172. return NULL;
  173. return PyLong_FromUnsignedLong(
  174. crc_finalize(crc_update(crc_init(), input, input_size)));
  175. }
  176. static PyMethodDef snappy_methods[] = {
  177. {"compress", snappy__compress, METH_VARARGS,
  178. "Compress a string using the snappy library."},
  179. {"uncompress", snappy__uncompress, METH_VARARGS,
  180. "Uncompress a string compressed with the snappy library."},
  181. {"decompress", snappy__uncompress, METH_VARARGS,
  182. "Alias to Uncompress method, to be compatible with zlib."},
  183. {"isValidCompressed", snappy__is_valid_compressed_buffer, METH_VARARGS,
  184. "Returns True if the compressed buffer is valid, False otherwise"},
  185. {"_crc32c", snappy__crc32c, METH_VARARGS,
  186. "Generate an RFC3720, section 12.1 CRC-32C"},
  187. {NULL, NULL, 0, NULL} /* Sentinel */
  188. };
  189. #if PY_MAJOR_VERSION >= 3
  190. static int snappy_traverse(PyObject *m, visitproc visit, void *arg) {
  191. Py_VISIT(GETSTATE(m)->error);
  192. return 0;
  193. }
  194. static int snappy_clear(PyObject *m) {
  195. Py_CLEAR(GETSTATE(m)->error);
  196. return 0;
  197. }
  198. static struct PyModuleDef moduledef = {
  199. PyModuleDef_HEAD_INIT,
  200. "_snappy",
  201. NULL,
  202. sizeof(struct module_state),
  203. snappy_methods,
  204. NULL,
  205. snappy_traverse,
  206. snappy_clear,
  207. NULL
  208. };
  209. #define INITERROR return NULL
  210. PyMODINIT_FUNC
  211. PyInit__snappy(void)
  212. #else
  213. #define INITERROR return
  214. PyMODINIT_FUNC
  215. init_snappy(void)
  216. #endif
  217. {
  218. PyObject *m;
  219. #if PY_MAJOR_VERSION >= 3
  220. m = PyModule_Create(&moduledef);
  221. #else
  222. m = Py_InitModule("_snappy", snappy_methods);
  223. #endif
  224. if (m == NULL)
  225. INITERROR;
  226. SnappyCompressError = PyErr_NewException((char*)"snappy.CompressError",
  227. NULL, NULL);
  228. SnappyUncompressError = PyErr_NewException((char*)"snappy.UncompressError",
  229. NULL, NULL);
  230. SnappyInvalidCompressedInputError = PyErr_NewException(
  231. (char*)"snappy.InvalidCompressedInputError", NULL, NULL);
  232. SnappyCompressedLengthError = PyErr_NewException(
  233. (char*)"snappy.CompressedLengthError", NULL, NULL);
  234. Py_INCREF(SnappyCompressError);
  235. Py_INCREF(SnappyUncompressError);
  236. Py_INCREF(SnappyInvalidCompressedInputError);
  237. Py_INCREF(SnappyCompressedLengthError);
  238. PyModule_AddObject(m, "CompressError", SnappyCompressError);
  239. PyModule_AddObject(m, "UncompressError", SnappyUncompressError);
  240. PyModule_AddObject(m, "InvalidCompressedInputError",
  241. SnappyInvalidCompressedInputError);
  242. PyModule_AddObject(m, "CompressedLengthError", SnappyCompressedLengthError);
  243. /* Version = MODULE_VERSION */
  244. if (PyModule_AddStringConstant(m, "__version__", MODULE_VERSION))
  245. INITERROR;
  246. #if PY_MAJOR_VERSION >= 3
  247. return m;
  248. #endif
  249. }