compressionwriter.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /**
  2. * Copyright (c) 2016-present, Gregory Szorc
  3. * All rights reserved.
  4. *
  5. * This software may be modified and distributed under the terms
  6. * of the BSD license. See the LICENSE file for details.
  7. */
  8. #include "python-zstandard.h"
  9. extern PyObject *ZstdError;
  10. static void ZstdCompressionWriter_dealloc(ZstdCompressionWriter *self) {
  11. Py_XDECREF(self->compressor);
  12. Py_XDECREF(self->writer);
  13. PyMem_Free(self->output.dst);
  14. self->output.dst = NULL;
  15. PyObject_Del(self);
  16. }
  17. static PyObject *ZstdCompressionWriter_enter(ZstdCompressionWriter *self) {
  18. if (self->closed) {
  19. PyErr_SetString(PyExc_ValueError, "stream is closed");
  20. return NULL;
  21. }
  22. if (self->entered) {
  23. PyErr_SetString(ZstdError, "cannot __enter__ multiple times");
  24. return NULL;
  25. }
  26. self->entered = 1;
  27. Py_INCREF(self);
  28. return (PyObject *)self;
  29. }
  30. static PyObject *ZstdCompressionWriter_exit(ZstdCompressionWriter *self,
  31. PyObject *args) {
  32. PyObject *exc_type;
  33. PyObject *exc_value;
  34. PyObject *exc_tb;
  35. if (!PyArg_ParseTuple(args, "OOO:__exit__", &exc_type, &exc_value,
  36. &exc_tb)) {
  37. return NULL;
  38. }
  39. self->entered = 0;
  40. PyObject *result = PyObject_CallMethod((PyObject *)self, "close", NULL);
  41. if (NULL == result) {
  42. return NULL;
  43. }
  44. Py_RETURN_FALSE;
  45. }
  46. static PyObject *
  47. ZstdCompressionWriter_memory_size(ZstdCompressionWriter *self) {
  48. return PyLong_FromSize_t(ZSTD_sizeof_CCtx(self->compressor->cctx));
  49. }
  50. static PyObject *ZstdCompressionWriter_write(ZstdCompressionWriter *self,
  51. PyObject *args, PyObject *kwargs) {
  52. static char *kwlist[] = {"data", NULL};
  53. PyObject *result = NULL;
  54. Py_buffer source;
  55. size_t zresult;
  56. ZSTD_inBuffer input;
  57. PyObject *res;
  58. Py_ssize_t totalWrite = 0;
  59. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*:write", kwlist,
  60. &source)) {
  61. return NULL;
  62. }
  63. if (self->closed) {
  64. PyErr_SetString(PyExc_ValueError, "stream is closed");
  65. return NULL;
  66. }
  67. self->output.pos = 0;
  68. input.src = source.buf;
  69. input.size = source.len;
  70. input.pos = 0;
  71. while (input.pos < (size_t)source.len) {
  72. Py_BEGIN_ALLOW_THREADS zresult = ZSTD_compressStream2(
  73. self->compressor->cctx, &self->output, &input, ZSTD_e_continue);
  74. Py_END_ALLOW_THREADS
  75. if (ZSTD_isError(zresult)) {
  76. PyErr_Format(ZstdError, "zstd compress error: %s",
  77. ZSTD_getErrorName(zresult));
  78. goto finally;
  79. }
  80. /* Copy data from output buffer to writer. */
  81. if (self->output.pos) {
  82. res = PyObject_CallMethod(self->writer, "write", "y#",
  83. self->output.dst, self->output.pos);
  84. if (NULL == res) {
  85. goto finally;
  86. }
  87. Py_XDECREF(res);
  88. totalWrite += self->output.pos;
  89. self->bytesCompressed += self->output.pos;
  90. }
  91. self->output.pos = 0;
  92. }
  93. if (self->writeReturnRead) {
  94. result = PyLong_FromSize_t(input.pos);
  95. }
  96. else {
  97. result = PyLong_FromSsize_t(totalWrite);
  98. }
  99. finally:
  100. PyBuffer_Release(&source);
  101. return result;
  102. }
  103. static PyObject *ZstdCompressionWriter_flush(ZstdCompressionWriter *self,
  104. PyObject *args, PyObject *kwargs) {
  105. static char *kwlist[] = {"flush_mode", NULL};
  106. size_t zresult;
  107. ZSTD_inBuffer input;
  108. PyObject *res;
  109. Py_ssize_t totalWrite = 0;
  110. unsigned flush_mode = 0;
  111. ZSTD_EndDirective flush;
  112. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|I:flush", kwlist,
  113. &flush_mode)) {
  114. return NULL;
  115. }
  116. switch (flush_mode) {
  117. case 0:
  118. flush = ZSTD_e_flush;
  119. break;
  120. case 1:
  121. flush = ZSTD_e_end;
  122. break;
  123. default:
  124. PyErr_Format(PyExc_ValueError, "unknown flush_mode: %d", flush_mode);
  125. return NULL;
  126. }
  127. if (self->closed) {
  128. PyErr_SetString(PyExc_ValueError, "stream is closed");
  129. return NULL;
  130. }
  131. self->output.pos = 0;
  132. input.src = NULL;
  133. input.size = 0;
  134. input.pos = 0;
  135. while (1) {
  136. Py_BEGIN_ALLOW_THREADS zresult = ZSTD_compressStream2(
  137. self->compressor->cctx, &self->output, &input, flush);
  138. Py_END_ALLOW_THREADS
  139. if (ZSTD_isError(zresult)) {
  140. PyErr_Format(ZstdError, "zstd compress error: %s",
  141. ZSTD_getErrorName(zresult));
  142. return NULL;
  143. }
  144. /* Copy data from output buffer to writer. */
  145. if (self->output.pos) {
  146. res = PyObject_CallMethod(self->writer, "write", "y#",
  147. self->output.dst, self->output.pos);
  148. if (NULL == res) {
  149. return NULL;
  150. }
  151. Py_XDECREF(res);
  152. totalWrite += self->output.pos;
  153. self->bytesCompressed += self->output.pos;
  154. }
  155. self->output.pos = 0;
  156. if (!zresult) {
  157. break;
  158. }
  159. }
  160. if (!self->closing && PyObject_HasAttrString(self->writer, "flush")) {
  161. res = PyObject_CallMethod(self->writer, "flush", NULL);
  162. if (NULL == res) {
  163. return NULL;
  164. }
  165. Py_XDECREF(res);
  166. }
  167. return PyLong_FromSsize_t(totalWrite);
  168. }
  169. static PyObject *ZstdCompressionWriter_close(ZstdCompressionWriter *self) {
  170. PyObject *result;
  171. if (self->closed) {
  172. Py_RETURN_NONE;
  173. }
  174. self->closing = 1;
  175. result = PyObject_CallMethod((PyObject *)self, "flush", "I", 1);
  176. self->closing = 0;
  177. self->closed = 1;
  178. if (NULL == result) {
  179. return NULL;
  180. }
  181. /* Call close on underlying stream as well. */
  182. if (self->closefd && PyObject_HasAttrString(self->writer, "close")) {
  183. return PyObject_CallMethod(self->writer, "close", NULL);
  184. }
  185. Py_RETURN_NONE;
  186. }
  187. static PyObject *ZstdCompressionWriter_fileno(ZstdCompressionWriter *self) {
  188. if (PyObject_HasAttrString(self->writer, "fileno")) {
  189. return PyObject_CallMethod(self->writer, "fileno", NULL);
  190. }
  191. else {
  192. PyErr_SetString(PyExc_OSError,
  193. "fileno not available on underlying writer");
  194. return NULL;
  195. }
  196. }
  197. static PyObject *ZstdCompressionWriter_tell(ZstdCompressionWriter *self) {
  198. return PyLong_FromUnsignedLongLong(self->bytesCompressed);
  199. }
  200. static PyObject *ZstdCompressionWriter_writelines(PyObject *self,
  201. PyObject *args) {
  202. PyErr_SetNone(PyExc_NotImplementedError);
  203. return NULL;
  204. }
  205. static PyObject *ZstdCompressionWriter_iter(PyObject *self) {
  206. set_io_unsupported_operation();
  207. return NULL;
  208. }
  209. static PyObject *ZstdCompressionWriter_iternext(PyObject *self) {
  210. set_io_unsupported_operation();
  211. return NULL;
  212. }
  213. static PyObject *ZstdCompressionWriter_false(PyObject *self, PyObject *args) {
  214. Py_RETURN_FALSE;
  215. }
  216. static PyObject *ZstdCompressionWriter_true(PyObject *self, PyObject *args) {
  217. Py_RETURN_TRUE;
  218. }
  219. static PyObject *ZstdCompressionWriter_unsupported(PyObject *self,
  220. PyObject *args,
  221. PyObject *kwargs) {
  222. set_io_unsupported_operation();
  223. return NULL;
  224. }
  225. static PyMethodDef ZstdCompressionWriter_methods[] = {
  226. {"__enter__", (PyCFunction)ZstdCompressionWriter_enter, METH_NOARGS,
  227. PyDoc_STR("Enter a compression context.")},
  228. {"__exit__", (PyCFunction)ZstdCompressionWriter_exit, METH_VARARGS,
  229. PyDoc_STR("Exit a compression context.")},
  230. {"close", (PyCFunction)ZstdCompressionWriter_close, METH_NOARGS, NULL},
  231. {"fileno", (PyCFunction)ZstdCompressionWriter_fileno, METH_NOARGS, NULL},
  232. {"isatty", (PyCFunction)ZstdCompressionWriter_false, METH_NOARGS, NULL},
  233. {"readable", (PyCFunction)ZstdCompressionWriter_false, METH_NOARGS, NULL},
  234. {"readline", (PyCFunction)ZstdCompressionWriter_unsupported,
  235. METH_VARARGS | METH_KEYWORDS, NULL},
  236. {"readlines", (PyCFunction)ZstdCompressionWriter_unsupported,
  237. METH_VARARGS | METH_KEYWORDS, NULL},
  238. {"seek", (PyCFunction)ZstdCompressionWriter_unsupported,
  239. METH_VARARGS | METH_KEYWORDS, NULL},
  240. {"seekable", ZstdCompressionWriter_false, METH_NOARGS, NULL},
  241. {"truncate", (PyCFunction)ZstdCompressionWriter_unsupported,
  242. METH_VARARGS | METH_KEYWORDS, NULL},
  243. {"writable", ZstdCompressionWriter_true, METH_NOARGS, NULL},
  244. {"writelines", ZstdCompressionWriter_writelines, METH_VARARGS, NULL},
  245. {"read", (PyCFunction)ZstdCompressionWriter_unsupported,
  246. METH_VARARGS | METH_KEYWORDS, NULL},
  247. {"readall", (PyCFunction)ZstdCompressionWriter_unsupported,
  248. METH_VARARGS | METH_KEYWORDS, NULL},
  249. {"readinto", (PyCFunction)ZstdCompressionWriter_unsupported,
  250. METH_VARARGS | METH_KEYWORDS, NULL},
  251. {"memory_size", (PyCFunction)ZstdCompressionWriter_memory_size, METH_NOARGS,
  252. PyDoc_STR("Obtain the memory size of the underlying compressor")},
  253. {"write", (PyCFunction)ZstdCompressionWriter_write,
  254. METH_VARARGS | METH_KEYWORDS, PyDoc_STR("Compress data")},
  255. {"flush", (PyCFunction)ZstdCompressionWriter_flush,
  256. METH_VARARGS | METH_KEYWORDS,
  257. PyDoc_STR("Flush data and finish a zstd frame")},
  258. {"tell", (PyCFunction)ZstdCompressionWriter_tell, METH_NOARGS,
  259. PyDoc_STR("Returns current number of bytes compressed")},
  260. {NULL, NULL}};
  261. static PyMemberDef ZstdCompressionWriter_members[] = {
  262. {"closed", T_BOOL, offsetof(ZstdCompressionWriter, closed), READONLY, NULL},
  263. {NULL}};
  264. PyType_Slot ZstdCompressionWriterSlots[] = {
  265. {Py_tp_dealloc, ZstdCompressionWriter_dealloc},
  266. {Py_tp_iter, ZstdCompressionWriter_iter},
  267. {Py_tp_iternext, ZstdCompressionWriter_iternext},
  268. {Py_tp_methods, ZstdCompressionWriter_methods},
  269. {Py_tp_members, ZstdCompressionWriter_members},
  270. {Py_tp_new, PyType_GenericNew},
  271. {0, NULL},
  272. };
  273. PyType_Spec ZstdCompressionWriterSpec = {
  274. "zstd.ZstdCompressionWriter",
  275. sizeof(ZstdCompressionWriter),
  276. 0,
  277. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  278. ZstdCompressionWriterSlots,
  279. };
  280. PyTypeObject *ZstdCompressionWriterType;
  281. void compressionwriter_module_init(PyObject *mod) {
  282. ZstdCompressionWriterType =
  283. (PyTypeObject *)PyType_FromSpec(&ZstdCompressionWriterSpec);
  284. if (PyType_Ready(ZstdCompressionWriterType) < 0) {
  285. return;
  286. }
  287. Py_INCREF((PyObject *)ZstdCompressionWriterType);
  288. PyModule_AddObject(mod, "ZstdCompressionWriter",
  289. (PyObject *)ZstdCompressionWriterType);
  290. }