compressor.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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. #include "pool.h"
  10. extern PyObject* ZstdError;
  11. int setup_cctx(ZstdCompressor* compressor) {
  12. size_t zresult;
  13. assert(compressor);
  14. assert(compressor->cctx);
  15. assert(compressor->params);
  16. zresult = ZSTD_CCtx_setParametersUsingCCtxParams(compressor->cctx, compressor->params);
  17. if (ZSTD_isError(zresult)) {
  18. PyErr_Format(ZstdError, "could not set compression parameters: %s",
  19. ZSTD_getErrorName(zresult));
  20. return 1;
  21. }
  22. if (compressor->dict) {
  23. if (compressor->dict->cdict) {
  24. zresult = ZSTD_CCtx_refCDict(compressor->cctx, compressor->dict->cdict);
  25. }
  26. else {
  27. zresult = ZSTD_CCtx_loadDictionary_advanced(compressor->cctx,
  28. compressor->dict->dictData, compressor->dict->dictSize,
  29. ZSTD_dlm_byRef, compressor->dict->dictType);
  30. }
  31. if (ZSTD_isError(zresult)) {
  32. PyErr_Format(ZstdError, "could not load compression dictionary: %s",
  33. ZSTD_getErrorName(zresult));
  34. return 1;
  35. }
  36. }
  37. return 0;
  38. }
  39. static PyObject* frame_progression(ZSTD_CCtx* cctx) {
  40. PyObject* result = NULL;
  41. PyObject* value;
  42. ZSTD_frameProgression progression;
  43. result = PyTuple_New(3);
  44. if (!result) {
  45. return NULL;
  46. }
  47. progression = ZSTD_getFrameProgression(cctx);
  48. value = PyLong_FromUnsignedLongLong(progression.ingested);
  49. if (!value) {
  50. Py_DECREF(result);
  51. return NULL;
  52. }
  53. PyTuple_SET_ITEM(result, 0, value);
  54. value = PyLong_FromUnsignedLongLong(progression.consumed);
  55. if (!value) {
  56. Py_DECREF(result);
  57. return NULL;
  58. }
  59. PyTuple_SET_ITEM(result, 1, value);
  60. value = PyLong_FromUnsignedLongLong(progression.produced);
  61. if (!value) {
  62. Py_DECREF(result);
  63. return NULL;
  64. }
  65. PyTuple_SET_ITEM(result, 2, value);
  66. return result;
  67. }
  68. PyDoc_STRVAR(ZstdCompressor__doc__,
  69. "ZstdCompressor(level=None, dict_data=None, compression_params=None)\n"
  70. "\n"
  71. "Create an object used to perform Zstandard compression.\n"
  72. "\n"
  73. "An instance can compress data various ways. Instances can be used multiple\n"
  74. "times. Each compression operation will use the compression parameters\n"
  75. "defined at construction time.\n"
  76. "\n"
  77. "Compression can be configured via the following names arguments:\n"
  78. "\n"
  79. "level\n"
  80. " Integer compression level.\n"
  81. "dict_data\n"
  82. " A ``ZstdCompressionDict`` to be used to compress with dictionary data.\n"
  83. "compression_params\n"
  84. " A ``CompressionParameters`` instance defining low-level compression"
  85. " parameters. If defined, this will overwrite the ``level`` argument.\n"
  86. "write_checksum\n"
  87. " If True, a 4 byte content checksum will be written with the compressed\n"
  88. " data, allowing the decompressor to perform content verification.\n"
  89. "write_content_size\n"
  90. " If True (the default), the decompressed content size will be included in\n"
  91. " the header of the compressed data. This data will only be written if the\n"
  92. " compressor knows the size of the input data.\n"
  93. "write_dict_id\n"
  94. " Determines whether the dictionary ID will be written into the compressed\n"
  95. " data. Defaults to True. Only adds content to the compressed data if\n"
  96. " a dictionary is being used.\n"
  97. "threads\n"
  98. " Number of threads to use to compress data concurrently. When set,\n"
  99. " compression operations are performed on multiple threads. The default\n"
  100. " value (0) disables multi-threaded compression. A value of ``-1`` means to\n"
  101. " set the number of threads to the number of detected logical CPUs.\n"
  102. );
  103. static int ZstdCompressor_init(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  104. static char* kwlist[] = {
  105. "level",
  106. "dict_data",
  107. "compression_params",
  108. "write_checksum",
  109. "write_content_size",
  110. "write_dict_id",
  111. "threads",
  112. NULL
  113. };
  114. int level = 3;
  115. ZstdCompressionDict* dict = NULL;
  116. ZstdCompressionParametersObject* params = NULL;
  117. PyObject* writeChecksum = NULL;
  118. PyObject* writeContentSize = NULL;
  119. PyObject* writeDictID = NULL;
  120. int threads = 0;
  121. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iO!O!OOOi:ZstdCompressor",
  122. kwlist, &level, &ZstdCompressionDictType, &dict,
  123. &ZstdCompressionParametersType, &params,
  124. &writeChecksum, &writeContentSize, &writeDictID, &threads)) {
  125. return -1;
  126. }
  127. if (level > ZSTD_maxCLevel()) {
  128. PyErr_Format(PyExc_ValueError, "level must be less than %d",
  129. ZSTD_maxCLevel() + 1);
  130. return -1;
  131. }
  132. if (threads < 0) {
  133. threads = cpu_count();
  134. }
  135. /* We create a ZSTD_CCtx for reuse among multiple operations to reduce the
  136. overhead of each compression operation. */
  137. self->cctx = ZSTD_createCCtx();
  138. if (!self->cctx) {
  139. PyErr_NoMemory();
  140. return -1;
  141. }
  142. /* TODO stuff the original parameters away somewhere so we can reset later. This
  143. will allow us to do things like automatically adjust cparams based on input
  144. size (assuming zstd isn't doing that internally). */
  145. self->params = ZSTD_createCCtxParams();
  146. if (!self->params) {
  147. PyErr_NoMemory();
  148. return -1;
  149. }
  150. if (params && writeChecksum) {
  151. PyErr_SetString(PyExc_ValueError,
  152. "cannot define compression_params and write_checksum");
  153. return -1;
  154. }
  155. if (params && writeContentSize) {
  156. PyErr_SetString(PyExc_ValueError,
  157. "cannot define compression_params and write_content_size");
  158. return -1;
  159. }
  160. if (params && writeDictID) {
  161. PyErr_SetString(PyExc_ValueError,
  162. "cannot define compression_params and write_dict_id");
  163. return -1;
  164. }
  165. if (params && threads) {
  166. PyErr_SetString(PyExc_ValueError,
  167. "cannot define compression_params and threads");
  168. return -1;
  169. }
  170. if (params) {
  171. if (set_parameters(self->params, params)) {
  172. return -1;
  173. }
  174. }
  175. else {
  176. if (set_parameter(self->params, ZSTD_c_compressionLevel, level)) {
  177. return -1;
  178. }
  179. if (set_parameter(self->params, ZSTD_c_contentSizeFlag,
  180. writeContentSize ? PyObject_IsTrue(writeContentSize) : 1)) {
  181. return -1;
  182. }
  183. if (set_parameter(self->params, ZSTD_c_checksumFlag,
  184. writeChecksum ? PyObject_IsTrue(writeChecksum) : 0)) {
  185. return -1;
  186. }
  187. if (set_parameter(self->params, ZSTD_c_dictIDFlag,
  188. writeDictID ? PyObject_IsTrue(writeDictID) : 1)) {
  189. return -1;
  190. }
  191. if (threads) {
  192. if (set_parameter(self->params, ZSTD_c_nbWorkers, threads)) {
  193. return -1;
  194. }
  195. }
  196. }
  197. if (dict) {
  198. self->dict = dict;
  199. Py_INCREF(dict);
  200. }
  201. if (setup_cctx(self)) {
  202. return -1;
  203. }
  204. return 0;
  205. }
  206. static void ZstdCompressor_dealloc(ZstdCompressor* self) {
  207. if (self->cctx) {
  208. ZSTD_freeCCtx(self->cctx);
  209. self->cctx = NULL;
  210. }
  211. if (self->params) {
  212. ZSTD_freeCCtxParams(self->params);
  213. self->params = NULL;
  214. }
  215. Py_XDECREF(self->dict);
  216. PyObject_Del(self);
  217. }
  218. PyDoc_STRVAR(ZstdCompressor_memory_size__doc__,
  219. "memory_size()\n"
  220. "\n"
  221. "Obtain the memory usage of this compressor, in bytes.\n"
  222. );
  223. static PyObject* ZstdCompressor_memory_size(ZstdCompressor* self) {
  224. if (self->cctx) {
  225. return PyLong_FromSize_t(ZSTD_sizeof_CCtx(self->cctx));
  226. }
  227. else {
  228. PyErr_SetString(ZstdError, "no compressor context found; this should never happen");
  229. return NULL;
  230. }
  231. }
  232. PyDoc_STRVAR(ZstdCompressor_frame_progression__doc__,
  233. "frame_progression()\n"
  234. "\n"
  235. "Return information on how much work the compressor has done.\n"
  236. "\n"
  237. "Returns a 3-tuple of (ingested, consumed, produced).\n"
  238. );
  239. static PyObject* ZstdCompressor_frame_progression(ZstdCompressor* self) {
  240. return frame_progression(self->cctx);
  241. }
  242. PyDoc_STRVAR(ZstdCompressor_copy_stream__doc__,
  243. "copy_stream(ifh, ofh[, size=0, read_size=default, write_size=default])\n"
  244. "compress data between streams\n"
  245. "\n"
  246. "Data will be read from ``ifh``, compressed, and written to ``ofh``.\n"
  247. "``ifh`` must have a ``read(size)`` method. ``ofh`` must have a ``write(data)``\n"
  248. "method.\n"
  249. "\n"
  250. "An optional ``size`` argument specifies the size of the source stream.\n"
  251. "If defined, compression parameters will be tuned based on the size.\n"
  252. "\n"
  253. "Optional arguments ``read_size`` and ``write_size`` define the chunk sizes\n"
  254. "of ``read()`` and ``write()`` operations, respectively. By default, they use\n"
  255. "the default compression stream input and output sizes, respectively.\n"
  256. );
  257. static PyObject* ZstdCompressor_copy_stream(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  258. static char* kwlist[] = {
  259. "ifh",
  260. "ofh",
  261. "size",
  262. "read_size",
  263. "write_size",
  264. NULL
  265. };
  266. PyObject* source;
  267. PyObject* dest;
  268. unsigned long long sourceSize = ZSTD_CONTENTSIZE_UNKNOWN;
  269. size_t inSize = ZSTD_CStreamInSize();
  270. size_t outSize = ZSTD_CStreamOutSize();
  271. ZSTD_inBuffer input;
  272. ZSTD_outBuffer output;
  273. Py_ssize_t totalRead = 0;
  274. Py_ssize_t totalWrite = 0;
  275. char* readBuffer;
  276. Py_ssize_t readSize;
  277. PyObject* readResult = NULL;
  278. PyObject* res = NULL;
  279. size_t zresult;
  280. PyObject* writeResult;
  281. PyObject* totalReadPy;
  282. PyObject* totalWritePy;
  283. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|Kkk:copy_stream", kwlist,
  284. &source, &dest, &sourceSize, &inSize, &outSize)) {
  285. return NULL;
  286. }
  287. if (!PyObject_HasAttrString(source, "read")) {
  288. PyErr_SetString(PyExc_ValueError, "first argument must have a read() method");
  289. return NULL;
  290. }
  291. if (!PyObject_HasAttrString(dest, "write")) {
  292. PyErr_SetString(PyExc_ValueError, "second argument must have a write() method");
  293. return NULL;
  294. }
  295. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  296. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, sourceSize);
  297. if (ZSTD_isError(zresult)) {
  298. PyErr_Format(ZstdError, "error setting source size: %s",
  299. ZSTD_getErrorName(zresult));
  300. return NULL;
  301. }
  302. /* Prevent free on uninitialized memory in finally. */
  303. output.dst = PyMem_Malloc(outSize);
  304. if (!output.dst) {
  305. PyErr_NoMemory();
  306. res = NULL;
  307. goto finally;
  308. }
  309. output.size = outSize;
  310. output.pos = 0;
  311. input.src = NULL;
  312. input.size = 0;
  313. input.pos = 0;
  314. while (1) {
  315. /* Try to read from source stream. */
  316. readResult = PyObject_CallMethod(source, "read", "n", inSize);
  317. if (!readResult) {
  318. PyErr_SetString(ZstdError, "could not read() from source");
  319. goto finally;
  320. }
  321. PyBytes_AsStringAndSize(readResult, &readBuffer, &readSize);
  322. /* If no data was read, we're at EOF. */
  323. if (0 == readSize) {
  324. break;
  325. }
  326. totalRead += readSize;
  327. /* Send data to compressor */
  328. input.src = readBuffer;
  329. input.size = readSize;
  330. input.pos = 0;
  331. while (input.pos < input.size) {
  332. Py_BEGIN_ALLOW_THREADS
  333. zresult = ZSTD_compressStream2(self->cctx, &output, &input, ZSTD_e_continue);
  334. Py_END_ALLOW_THREADS
  335. if (ZSTD_isError(zresult)) {
  336. res = NULL;
  337. PyErr_Format(ZstdError, "zstd compress error: %s", ZSTD_getErrorName(zresult));
  338. goto finally;
  339. }
  340. if (output.pos) {
  341. #if PY_MAJOR_VERSION >= 3
  342. writeResult = PyObject_CallMethod(dest, "write", "y#",
  343. #else
  344. writeResult = PyObject_CallMethod(dest, "write", "s#",
  345. #endif
  346. output.dst, output.pos);
  347. Py_XDECREF(writeResult);
  348. totalWrite += output.pos;
  349. output.pos = 0;
  350. }
  351. }
  352. Py_CLEAR(readResult);
  353. }
  354. /* We've finished reading. Now flush the compressor stream. */
  355. assert(input.pos == input.size);
  356. while (1) {
  357. Py_BEGIN_ALLOW_THREADS
  358. zresult = ZSTD_compressStream2(self->cctx, &output, &input, ZSTD_e_end);
  359. Py_END_ALLOW_THREADS
  360. if (ZSTD_isError(zresult)) {
  361. PyErr_Format(ZstdError, "error ending compression stream: %s",
  362. ZSTD_getErrorName(zresult));
  363. res = NULL;
  364. goto finally;
  365. }
  366. if (output.pos) {
  367. #if PY_MAJOR_VERSION >= 3
  368. writeResult = PyObject_CallMethod(dest, "write", "y#",
  369. #else
  370. writeResult = PyObject_CallMethod(dest, "write", "s#",
  371. #endif
  372. output.dst, output.pos);
  373. totalWrite += output.pos;
  374. Py_XDECREF(writeResult);
  375. output.pos = 0;
  376. }
  377. if (!zresult) {
  378. break;
  379. }
  380. }
  381. totalReadPy = PyLong_FromSsize_t(totalRead);
  382. totalWritePy = PyLong_FromSsize_t(totalWrite);
  383. res = PyTuple_Pack(2, totalReadPy, totalWritePy);
  384. Py_DECREF(totalReadPy);
  385. Py_DECREF(totalWritePy);
  386. finally:
  387. if (output.dst) {
  388. PyMem_Free(output.dst);
  389. }
  390. Py_XDECREF(readResult);
  391. return res;
  392. }
  393. PyDoc_STRVAR(ZstdCompressor_stream_reader__doc__,
  394. "stream_reader(source, [size=0])\n"
  395. "\n"
  396. "Obtain an object that behaves like an I/O stream.\n"
  397. "\n"
  398. "The source object can be any object with a ``read(size)`` method\n"
  399. "or an object that conforms to the buffer protocol.\n"
  400. );
  401. static ZstdCompressionReader* ZstdCompressor_stream_reader(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  402. static char* kwlist[] = {
  403. "source",
  404. "size",
  405. "read_size",
  406. NULL
  407. };
  408. PyObject* source;
  409. unsigned long long sourceSize = ZSTD_CONTENTSIZE_UNKNOWN;
  410. size_t readSize = ZSTD_CStreamInSize();
  411. ZstdCompressionReader* result = NULL;
  412. size_t zresult;
  413. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|Kk:stream_reader", kwlist,
  414. &source, &sourceSize, &readSize)) {
  415. return NULL;
  416. }
  417. result = (ZstdCompressionReader*)PyObject_CallObject((PyObject*)&ZstdCompressionReaderType, NULL);
  418. if (!result) {
  419. return NULL;
  420. }
  421. result->entered = 0;
  422. result->closed = 0;
  423. if (PyObject_HasAttrString(source, "read")) {
  424. result->reader = source;
  425. Py_INCREF(source);
  426. result->readSize = readSize;
  427. }
  428. else if (1 == PyObject_CheckBuffer(source)) {
  429. if (0 != PyObject_GetBuffer(source, &result->buffer, PyBUF_CONTIG_RO)) {
  430. goto except;
  431. }
  432. assert(result->buffer.len >= 0);
  433. sourceSize = result->buffer.len;
  434. }
  435. else {
  436. PyErr_SetString(PyExc_TypeError,
  437. "must pass an object with a read() method or that conforms to the buffer protocol");
  438. goto except;
  439. }
  440. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  441. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, sourceSize);
  442. if (ZSTD_isError(zresult)) {
  443. PyErr_Format(ZstdError, "error setting source source: %s",
  444. ZSTD_getErrorName(zresult));
  445. goto except;
  446. }
  447. result->compressor = self;
  448. Py_INCREF(self);
  449. return result;
  450. except:
  451. Py_CLEAR(result);
  452. return NULL;
  453. }
  454. PyDoc_STRVAR(ZstdCompressor_compress__doc__,
  455. "compress(data)\n"
  456. "\n"
  457. "Compress data in a single operation.\n"
  458. "\n"
  459. "This is the simplest mechanism to perform compression: simply pass in a\n"
  460. "value and get a compressed value back. It is almost the most prone to abuse.\n"
  461. "The input and output values must fit in memory, so passing in very large\n"
  462. "values can result in excessive memory usage. For this reason, one of the\n"
  463. "streaming based APIs is preferred for larger values.\n"
  464. );
  465. static PyObject* ZstdCompressor_compress(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  466. static char* kwlist[] = {
  467. "data",
  468. NULL
  469. };
  470. Py_buffer source;
  471. size_t destSize;
  472. PyObject* output = NULL;
  473. size_t zresult;
  474. ZSTD_outBuffer outBuffer;
  475. ZSTD_inBuffer inBuffer;
  476. #if PY_MAJOR_VERSION >= 3
  477. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|O:compress",
  478. #else
  479. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|O:compress",
  480. #endif
  481. kwlist, &source)) {
  482. return NULL;
  483. }
  484. if (!PyBuffer_IsContiguous(&source, 'C') || source.ndim > 1) {
  485. PyErr_SetString(PyExc_ValueError,
  486. "data buffer should be contiguous and have at most one dimension");
  487. goto finally;
  488. }
  489. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  490. destSize = ZSTD_compressBound(source.len);
  491. output = PyBytes_FromStringAndSize(NULL, destSize);
  492. if (!output) {
  493. goto finally;
  494. }
  495. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, source.len);
  496. if (ZSTD_isError(zresult)) {
  497. PyErr_Format(ZstdError, "error setting source size: %s",
  498. ZSTD_getErrorName(zresult));
  499. Py_CLEAR(output);
  500. goto finally;
  501. }
  502. inBuffer.src = source.buf;
  503. inBuffer.size = source.len;
  504. inBuffer.pos = 0;
  505. outBuffer.dst = PyBytes_AsString(output);
  506. outBuffer.size = destSize;
  507. outBuffer.pos = 0;
  508. Py_BEGIN_ALLOW_THREADS
  509. /* By avoiding ZSTD_compress(), we don't necessarily write out content
  510. size. This means the argument to ZstdCompressor to control frame
  511. parameters is honored. */
  512. zresult = ZSTD_compressStream2(self->cctx, &outBuffer, &inBuffer, ZSTD_e_end);
  513. Py_END_ALLOW_THREADS
  514. if (ZSTD_isError(zresult)) {
  515. PyErr_Format(ZstdError, "cannot compress: %s", ZSTD_getErrorName(zresult));
  516. Py_CLEAR(output);
  517. goto finally;
  518. }
  519. else if (zresult) {
  520. PyErr_SetString(ZstdError, "unexpected partial frame flush");
  521. Py_CLEAR(output);
  522. goto finally;
  523. }
  524. Py_SIZE(output) = outBuffer.pos;
  525. finally:
  526. PyBuffer_Release(&source);
  527. return output;
  528. }
  529. PyDoc_STRVAR(ZstdCompressionObj__doc__,
  530. "compressobj()\n"
  531. "\n"
  532. "Return an object exposing ``compress(data)`` and ``flush()`` methods.\n"
  533. "\n"
  534. "The returned object exposes an API similar to ``zlib.compressobj`` and\n"
  535. "``bz2.BZ2Compressor`` so that callers can swap in the zstd compressor\n"
  536. "without changing how compression is performed.\n"
  537. );
  538. static ZstdCompressionObj* ZstdCompressor_compressobj(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  539. static char* kwlist[] = {
  540. "size",
  541. NULL
  542. };
  543. unsigned long long inSize = ZSTD_CONTENTSIZE_UNKNOWN;
  544. size_t outSize = ZSTD_CStreamOutSize();
  545. ZstdCompressionObj* result = NULL;
  546. size_t zresult;
  547. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|K:compressobj", kwlist, &inSize)) {
  548. return NULL;
  549. }
  550. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  551. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, inSize);
  552. if (ZSTD_isError(zresult)) {
  553. PyErr_Format(ZstdError, "error setting source size: %s",
  554. ZSTD_getErrorName(zresult));
  555. return NULL;
  556. }
  557. result = (ZstdCompressionObj*)PyObject_CallObject((PyObject*)&ZstdCompressionObjType, NULL);
  558. if (!result) {
  559. return NULL;
  560. }
  561. result->output.dst = PyMem_Malloc(outSize);
  562. if (!result->output.dst) {
  563. PyErr_NoMemory();
  564. Py_DECREF(result);
  565. return NULL;
  566. }
  567. result->output.size = outSize;
  568. result->compressor = self;
  569. Py_INCREF(result->compressor);
  570. return result;
  571. }
  572. PyDoc_STRVAR(ZstdCompressor_read_to_iter__doc__,
  573. "read_to_iter(reader, [size=0, read_size=default, write_size=default])\n"
  574. "Read uncompressed data from a reader and return an iterator\n"
  575. "\n"
  576. "Returns an iterator of compressed data produced from reading from ``reader``.\n"
  577. "\n"
  578. "Uncompressed data will be obtained from ``reader`` by calling the\n"
  579. "``read(size)`` method of it. The source data will be streamed into a\n"
  580. "compressor. As compressed data is available, it will be exposed to the\n"
  581. "iterator.\n"
  582. "\n"
  583. "Data is read from the source in chunks of ``read_size``. Compressed chunks\n"
  584. "are at most ``write_size`` bytes. Both values default to the zstd input and\n"
  585. "and output defaults, respectively.\n"
  586. "\n"
  587. "The caller is partially in control of how fast data is fed into the\n"
  588. "compressor by how it consumes the returned iterator. The compressor will\n"
  589. "not consume from the reader unless the caller consumes from the iterator.\n"
  590. );
  591. static ZstdCompressorIterator* ZstdCompressor_read_to_iter(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  592. static char* kwlist[] = {
  593. "reader",
  594. "size",
  595. "read_size",
  596. "write_size",
  597. NULL
  598. };
  599. PyObject* reader;
  600. unsigned long long sourceSize = ZSTD_CONTENTSIZE_UNKNOWN;
  601. size_t inSize = ZSTD_CStreamInSize();
  602. size_t outSize = ZSTD_CStreamOutSize();
  603. ZstdCompressorIterator* result;
  604. size_t zresult;
  605. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|Kkk:read_to_iter", kwlist,
  606. &reader, &sourceSize, &inSize, &outSize)) {
  607. return NULL;
  608. }
  609. result = (ZstdCompressorIterator*)PyObject_CallObject((PyObject*)&ZstdCompressorIteratorType, NULL);
  610. if (!result) {
  611. return NULL;
  612. }
  613. if (PyObject_HasAttrString(reader, "read")) {
  614. result->reader = reader;
  615. Py_INCREF(result->reader);
  616. }
  617. else if (1 == PyObject_CheckBuffer(reader)) {
  618. if (0 != PyObject_GetBuffer(reader, &result->buffer, PyBUF_CONTIG_RO)) {
  619. goto except;
  620. }
  621. sourceSize = result->buffer.len;
  622. }
  623. else {
  624. PyErr_SetString(PyExc_ValueError,
  625. "must pass an object with a read() method or conforms to buffer protocol");
  626. goto except;
  627. }
  628. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  629. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, sourceSize);
  630. if (ZSTD_isError(zresult)) {
  631. PyErr_Format(ZstdError, "error setting source size: %s",
  632. ZSTD_getErrorName(zresult));
  633. return NULL;
  634. }
  635. result->compressor = self;
  636. Py_INCREF(result->compressor);
  637. result->inSize = inSize;
  638. result->outSize = outSize;
  639. result->output.dst = PyMem_Malloc(outSize);
  640. if (!result->output.dst) {
  641. PyErr_NoMemory();
  642. goto except;
  643. }
  644. result->output.size = outSize;
  645. goto finally;
  646. except:
  647. Py_CLEAR(result);
  648. finally:
  649. return result;
  650. }
  651. PyDoc_STRVAR(ZstdCompressor_stream_writer___doc__,
  652. "Create a context manager to write compressed data to an object.\n"
  653. "\n"
  654. "The passed object must have a ``write()`` method.\n"
  655. "\n"
  656. "The caller feeds input data to the object by calling ``compress(data)``.\n"
  657. "Compressed data is written to the argument given to this function.\n"
  658. "\n"
  659. "The function takes an optional ``size`` argument indicating the total size\n"
  660. "of the eventual input. If specified, the size will influence compression\n"
  661. "parameter tuning and could result in the size being written into the\n"
  662. "header of the compressed data.\n"
  663. "\n"
  664. "An optional ``write_size`` argument is also accepted. It defines the maximum\n"
  665. "byte size of chunks fed to ``write()``. By default, it uses the zstd default\n"
  666. "for a compressor output stream.\n"
  667. );
  668. static ZstdCompressionWriter* ZstdCompressor_stream_writer(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  669. static char* kwlist[] = {
  670. "writer",
  671. "size",
  672. "write_size",
  673. "write_return_read",
  674. NULL
  675. };
  676. PyObject* writer;
  677. ZstdCompressionWriter* result;
  678. size_t zresult;
  679. unsigned long long sourceSize = ZSTD_CONTENTSIZE_UNKNOWN;
  680. size_t outSize = ZSTD_CStreamOutSize();
  681. PyObject* writeReturnRead = NULL;
  682. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|KkO:stream_writer", kwlist,
  683. &writer, &sourceSize, &outSize, &writeReturnRead)) {
  684. return NULL;
  685. }
  686. if (!PyObject_HasAttrString(writer, "write")) {
  687. PyErr_SetString(PyExc_ValueError, "must pass an object with a write() method");
  688. return NULL;
  689. }
  690. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  691. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, sourceSize);
  692. if (ZSTD_isError(zresult)) {
  693. PyErr_Format(ZstdError, "error setting source size: %s",
  694. ZSTD_getErrorName(zresult));
  695. return NULL;
  696. }
  697. result = (ZstdCompressionWriter*)PyObject_CallObject((PyObject*)&ZstdCompressionWriterType, NULL);
  698. if (!result) {
  699. return NULL;
  700. }
  701. result->entered = 0;
  702. result->closed = 0;
  703. result->output.dst = PyMem_Malloc(outSize);
  704. if (!result->output.dst) {
  705. Py_DECREF(result);
  706. return (ZstdCompressionWriter*)PyErr_NoMemory();
  707. }
  708. result->output.pos = 0;
  709. result->output.size = outSize;
  710. result->compressor = self;
  711. Py_INCREF(result->compressor);
  712. result->writer = writer;
  713. Py_INCREF(result->writer);
  714. result->outSize = outSize;
  715. result->bytesCompressed = 0;
  716. result->writeReturnRead = writeReturnRead ? PyObject_IsTrue(writeReturnRead) : 0;
  717. return result;
  718. }
  719. PyDoc_STRVAR(ZstdCompressor_chunker__doc__,
  720. "Create an object for iterative compressing to same-sized chunks.\n"
  721. );
  722. static ZstdCompressionChunker* ZstdCompressor_chunker(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  723. static char* kwlist[] = {
  724. "size",
  725. "chunk_size",
  726. NULL
  727. };
  728. unsigned long long sourceSize = ZSTD_CONTENTSIZE_UNKNOWN;
  729. size_t chunkSize = ZSTD_CStreamOutSize();
  730. ZstdCompressionChunker* chunker;
  731. size_t zresult;
  732. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Kk:chunker", kwlist,
  733. &sourceSize, &chunkSize)) {
  734. return NULL;
  735. }
  736. ZSTD_CCtx_reset(self->cctx, ZSTD_reset_session_only);
  737. zresult = ZSTD_CCtx_setPledgedSrcSize(self->cctx, sourceSize);
  738. if (ZSTD_isError(zresult)) {
  739. PyErr_Format(ZstdError, "error setting source size: %s",
  740. ZSTD_getErrorName(zresult));
  741. return NULL;
  742. }
  743. chunker = (ZstdCompressionChunker*)PyObject_CallObject((PyObject*)&ZstdCompressionChunkerType, NULL);
  744. if (!chunker) {
  745. return NULL;
  746. }
  747. chunker->output.dst = PyMem_Malloc(chunkSize);
  748. if (!chunker->output.dst) {
  749. PyErr_NoMemory();
  750. Py_DECREF(chunker);
  751. return NULL;
  752. }
  753. chunker->output.size = chunkSize;
  754. chunker->output.pos = 0;
  755. chunker->compressor = self;
  756. Py_INCREF(chunker->compressor);
  757. chunker->chunkSize = chunkSize;
  758. return chunker;
  759. }
  760. typedef struct {
  761. void* sourceData;
  762. size_t sourceSize;
  763. } DataSource;
  764. typedef struct {
  765. DataSource* sources;
  766. Py_ssize_t sourcesSize;
  767. unsigned long long totalSourceSize;
  768. } DataSources;
  769. typedef struct {
  770. void* dest;
  771. Py_ssize_t destSize;
  772. BufferSegment* segments;
  773. Py_ssize_t segmentsSize;
  774. } DestBuffer;
  775. typedef enum {
  776. WorkerError_none = 0,
  777. WorkerError_zstd = 1,
  778. WorkerError_no_memory = 2,
  779. WorkerError_nospace = 3,
  780. } WorkerError;
  781. /**
  782. * Holds state for an individual worker performing multi_compress_to_buffer work.
  783. */
  784. typedef struct {
  785. /* Used for compression. */
  786. ZSTD_CCtx* cctx;
  787. /* What to compress. */
  788. DataSource* sources;
  789. Py_ssize_t sourcesSize;
  790. Py_ssize_t startOffset;
  791. Py_ssize_t endOffset;
  792. unsigned long long totalSourceSize;
  793. /* Result storage. */
  794. DestBuffer* destBuffers;
  795. Py_ssize_t destCount;
  796. /* Error tracking. */
  797. WorkerError error;
  798. size_t zresult;
  799. Py_ssize_t errorOffset;
  800. } WorkerState;
  801. static void compress_worker(WorkerState* state) {
  802. Py_ssize_t inputOffset = state->startOffset;
  803. Py_ssize_t remainingItems = state->endOffset - state->startOffset + 1;
  804. Py_ssize_t currentBufferStartOffset = state->startOffset;
  805. size_t zresult;
  806. void* newDest;
  807. size_t allocationSize;
  808. size_t boundSize;
  809. Py_ssize_t destOffset = 0;
  810. DataSource* sources = state->sources;
  811. DestBuffer* destBuffer;
  812. assert(!state->destBuffers);
  813. assert(0 == state->destCount);
  814. /*
  815. * The total size of the compressed data is unknown until we actually
  816. * compress data. That means we can't pre-allocate the exact size we need.
  817. *
  818. * There is a cost to every allocation and reallocation. So, it is in our
  819. * interest to minimize the number of allocations.
  820. *
  821. * There is also a cost to too few allocations. If allocations are too
  822. * large they may fail. If buffers are shared and all inputs become
  823. * irrelevant at different lifetimes, then a reference to one segment
  824. * in the buffer will keep the entire buffer alive. This leads to excessive
  825. * memory usage.
  826. *
  827. * Our current strategy is to assume a compression ratio of 16:1 and
  828. * allocate buffers of that size, rounded up to the nearest power of 2
  829. * (because computers like round numbers). That ratio is greater than what
  830. * most inputs achieve. This is by design: we don't want to over-allocate.
  831. * But we don't want to under-allocate and lead to too many buffers either.
  832. */
  833. state->destCount = 1;
  834. state->destBuffers = calloc(1, sizeof(DestBuffer));
  835. if (NULL == state->destBuffers) {
  836. state->error = WorkerError_no_memory;
  837. return;
  838. }
  839. destBuffer = &state->destBuffers[state->destCount - 1];
  840. /*
  841. * Rather than track bounds and grow the segments buffer, allocate space
  842. * to hold remaining items then truncate when we're done with it.
  843. */
  844. destBuffer->segments = calloc(remainingItems, sizeof(BufferSegment));
  845. if (NULL == destBuffer->segments) {
  846. state->error = WorkerError_no_memory;
  847. return;
  848. }
  849. destBuffer->segmentsSize = remainingItems;
  850. assert(state->totalSourceSize <= SIZE_MAX);
  851. allocationSize = roundpow2((size_t)state->totalSourceSize >> 4);
  852. /* If the maximum size of the output is larger than that, round up. */
  853. boundSize = ZSTD_compressBound(sources[inputOffset].sourceSize);
  854. if (boundSize > allocationSize) {
  855. allocationSize = roundpow2(boundSize);
  856. }
  857. destBuffer->dest = malloc(allocationSize);
  858. if (NULL == destBuffer->dest) {
  859. state->error = WorkerError_no_memory;
  860. return;
  861. }
  862. destBuffer->destSize = allocationSize;
  863. for (inputOffset = state->startOffset; inputOffset <= state->endOffset; inputOffset++) {
  864. void* source = sources[inputOffset].sourceData;
  865. size_t sourceSize = sources[inputOffset].sourceSize;
  866. size_t destAvailable;
  867. void* dest;
  868. ZSTD_outBuffer opOutBuffer;
  869. ZSTD_inBuffer opInBuffer;
  870. destAvailable = destBuffer->destSize - destOffset;
  871. boundSize = ZSTD_compressBound(sourceSize);
  872. /*
  873. * Not enough space in current buffer to hold largest compressed output.
  874. * So allocate and switch to a new output buffer.
  875. */
  876. if (boundSize > destAvailable) {
  877. /*
  878. * The downsizing of the existing buffer is optional. It should be cheap
  879. * (unlike growing). So we just do it.
  880. */
  881. if (destAvailable) {
  882. newDest = realloc(destBuffer->dest, destOffset);
  883. if (NULL == newDest) {
  884. state->error = WorkerError_no_memory;
  885. return;
  886. }
  887. destBuffer->dest = newDest;
  888. destBuffer->destSize = destOffset;
  889. }
  890. /* Truncate segments buffer. */
  891. newDest = realloc(destBuffer->segments,
  892. (inputOffset - currentBufferStartOffset + 1) * sizeof(BufferSegment));
  893. if (NULL == newDest) {
  894. state->error = WorkerError_no_memory;
  895. return;
  896. }
  897. destBuffer->segments = newDest;
  898. destBuffer->segmentsSize = inputOffset - currentBufferStartOffset;
  899. /* Grow space for new struct. */
  900. /* TODO consider over-allocating so we don't do this every time. */
  901. newDest = realloc(state->destBuffers, (state->destCount + 1) * sizeof(DestBuffer));
  902. if (NULL == newDest) {
  903. state->error = WorkerError_no_memory;
  904. return;
  905. }
  906. state->destBuffers = newDest;
  907. state->destCount++;
  908. destBuffer = &state->destBuffers[state->destCount - 1];
  909. /* Don't take any chances with non-NULL pointers. */
  910. memset(destBuffer, 0, sizeof(DestBuffer));
  911. /**
  912. * We could dynamically update allocation size based on work done so far.
  913. * For now, keep is simple.
  914. */
  915. assert(state->totalSourceSize <= SIZE_MAX);
  916. allocationSize = roundpow2((size_t)state->totalSourceSize >> 4);
  917. if (boundSize > allocationSize) {
  918. allocationSize = roundpow2(boundSize);
  919. }
  920. destBuffer->dest = malloc(allocationSize);
  921. if (NULL == destBuffer->dest) {
  922. state->error = WorkerError_no_memory;
  923. return;
  924. }
  925. destBuffer->destSize = allocationSize;
  926. destAvailable = allocationSize;
  927. destOffset = 0;
  928. destBuffer->segments = calloc(remainingItems, sizeof(BufferSegment));
  929. if (NULL == destBuffer->segments) {
  930. state->error = WorkerError_no_memory;
  931. return;
  932. }
  933. destBuffer->segmentsSize = remainingItems;
  934. currentBufferStartOffset = inputOffset;
  935. }
  936. dest = (char*)destBuffer->dest + destOffset;
  937. opInBuffer.src = source;
  938. opInBuffer.size = sourceSize;
  939. opInBuffer.pos = 0;
  940. opOutBuffer.dst = dest;
  941. opOutBuffer.size = destAvailable;
  942. opOutBuffer.pos = 0;
  943. zresult = ZSTD_CCtx_setPledgedSrcSize(state->cctx, sourceSize);
  944. if (ZSTD_isError(zresult)) {
  945. state->error = WorkerError_zstd;
  946. state->zresult = zresult;
  947. state->errorOffset = inputOffset;
  948. break;
  949. }
  950. zresult = ZSTD_compressStream2(state->cctx, &opOutBuffer, &opInBuffer, ZSTD_e_end);
  951. if (ZSTD_isError(zresult)) {
  952. state->error = WorkerError_zstd;
  953. state->zresult = zresult;
  954. state->errorOffset = inputOffset;
  955. break;
  956. }
  957. else if (zresult) {
  958. state->error = WorkerError_nospace;
  959. state->errorOffset = inputOffset;
  960. break;
  961. }
  962. destBuffer->segments[inputOffset - currentBufferStartOffset].offset = destOffset;
  963. destBuffer->segments[inputOffset - currentBufferStartOffset].length = opOutBuffer.pos;
  964. destOffset += opOutBuffer.pos;
  965. remainingItems--;
  966. }
  967. if (destBuffer->destSize > destOffset) {
  968. newDest = realloc(destBuffer->dest, destOffset);
  969. if (NULL == newDest) {
  970. state->error = WorkerError_no_memory;
  971. return;
  972. }
  973. destBuffer->dest = newDest;
  974. destBuffer->destSize = destOffset;
  975. }
  976. }
  977. ZstdBufferWithSegmentsCollection* compress_from_datasources(ZstdCompressor* compressor,
  978. DataSources* sources, Py_ssize_t threadCount) {
  979. unsigned long long bytesPerWorker;
  980. POOL_ctx* pool = NULL;
  981. WorkerState* workerStates = NULL;
  982. Py_ssize_t i;
  983. unsigned long long workerBytes = 0;
  984. Py_ssize_t workerStartOffset = 0;
  985. Py_ssize_t currentThread = 0;
  986. int errored = 0;
  987. Py_ssize_t segmentsCount = 0;
  988. Py_ssize_t segmentIndex;
  989. PyObject* segmentsArg = NULL;
  990. ZstdBufferWithSegments* buffer;
  991. ZstdBufferWithSegmentsCollection* result = NULL;
  992. assert(sources->sourcesSize > 0);
  993. assert(sources->totalSourceSize > 0);
  994. assert(threadCount >= 1);
  995. /* More threads than inputs makes no sense. */
  996. threadCount = sources->sourcesSize < threadCount ? sources->sourcesSize
  997. : threadCount;
  998. /* TODO lower thread count when input size is too small and threads would add
  999. overhead. */
  1000. workerStates = PyMem_Malloc(threadCount * sizeof(WorkerState));
  1001. if (NULL == workerStates) {
  1002. PyErr_NoMemory();
  1003. goto finally;
  1004. }
  1005. memset(workerStates, 0, threadCount * sizeof(WorkerState));
  1006. if (threadCount > 1) {
  1007. pool = POOL_create(threadCount, 1);
  1008. if (NULL == pool) {
  1009. PyErr_SetString(ZstdError, "could not initialize zstd thread pool");
  1010. goto finally;
  1011. }
  1012. }
  1013. bytesPerWorker = sources->totalSourceSize / threadCount;
  1014. for (i = 0; i < threadCount; i++) {
  1015. size_t zresult;
  1016. workerStates[i].cctx = ZSTD_createCCtx();
  1017. if (!workerStates[i].cctx) {
  1018. PyErr_NoMemory();
  1019. goto finally;
  1020. }
  1021. zresult = ZSTD_CCtx_setParametersUsingCCtxParams(workerStates[i].cctx,
  1022. compressor->params);
  1023. if (ZSTD_isError(zresult)) {
  1024. PyErr_Format(ZstdError, "could not set compression parameters: %s",
  1025. ZSTD_getErrorName(zresult));
  1026. goto finally;
  1027. }
  1028. if (compressor->dict) {
  1029. if (compressor->dict->cdict) {
  1030. zresult = ZSTD_CCtx_refCDict(workerStates[i].cctx, compressor->dict->cdict);
  1031. }
  1032. else {
  1033. zresult = ZSTD_CCtx_loadDictionary_advanced(
  1034. workerStates[i].cctx,
  1035. compressor->dict->dictData,
  1036. compressor->dict->dictSize,
  1037. ZSTD_dlm_byRef,
  1038. compressor->dict->dictType);
  1039. }
  1040. if (ZSTD_isError(zresult)) {
  1041. PyErr_Format(ZstdError, "could not load compression dictionary: %s",
  1042. ZSTD_getErrorName(zresult));
  1043. goto finally;
  1044. }
  1045. }
  1046. workerStates[i].sources = sources->sources;
  1047. workerStates[i].sourcesSize = sources->sourcesSize;
  1048. }
  1049. Py_BEGIN_ALLOW_THREADS
  1050. for (i = 0; i < sources->sourcesSize; i++) {
  1051. workerBytes += sources->sources[i].sourceSize;
  1052. /*
  1053. * The last worker/thread needs to handle all remaining work. Don't
  1054. * trigger it prematurely. Defer to the block outside of the loop
  1055. * to run the last worker/thread. But do still process this loop
  1056. * so workerBytes is correct.
  1057. */
  1058. if (currentThread == threadCount - 1) {
  1059. continue;
  1060. }
  1061. if (workerBytes >= bytesPerWorker) {
  1062. assert(currentThread < threadCount);
  1063. workerStates[currentThread].totalSourceSize = workerBytes;
  1064. workerStates[currentThread].startOffset = workerStartOffset;
  1065. workerStates[currentThread].endOffset = i;
  1066. if (threadCount > 1) {
  1067. POOL_add(pool, (POOL_function)compress_worker, &workerStates[currentThread]);
  1068. }
  1069. else {
  1070. compress_worker(&workerStates[currentThread]);
  1071. }
  1072. currentThread++;
  1073. workerStartOffset = i + 1;
  1074. workerBytes = 0;
  1075. }
  1076. }
  1077. if (workerBytes) {
  1078. assert(currentThread < threadCount);
  1079. workerStates[currentThread].totalSourceSize = workerBytes;
  1080. workerStates[currentThread].startOffset = workerStartOffset;
  1081. workerStates[currentThread].endOffset = sources->sourcesSize - 1;
  1082. if (threadCount > 1) {
  1083. POOL_add(pool, (POOL_function)compress_worker, &workerStates[currentThread]);
  1084. }
  1085. else {
  1086. compress_worker(&workerStates[currentThread]);
  1087. }
  1088. }
  1089. if (threadCount > 1) {
  1090. POOL_free(pool);
  1091. pool = NULL;
  1092. }
  1093. Py_END_ALLOW_THREADS
  1094. for (i = 0; i < threadCount; i++) {
  1095. switch (workerStates[i].error) {
  1096. case WorkerError_no_memory:
  1097. PyErr_NoMemory();
  1098. errored = 1;
  1099. break;
  1100. case WorkerError_zstd:
  1101. PyErr_Format(ZstdError, "error compressing item %zd: %s",
  1102. workerStates[i].errorOffset, ZSTD_getErrorName(workerStates[i].zresult));
  1103. errored = 1;
  1104. break;
  1105. case WorkerError_nospace:
  1106. PyErr_Format(ZstdError, "error compressing item %zd: not enough space in output",
  1107. workerStates[i].errorOffset);
  1108. errored = 1;
  1109. break;
  1110. default:
  1111. ;
  1112. }
  1113. if (errored) {
  1114. break;
  1115. }
  1116. }
  1117. if (errored) {
  1118. goto finally;
  1119. }
  1120. segmentsCount = 0;
  1121. for (i = 0; i < threadCount; i++) {
  1122. WorkerState* state = &workerStates[i];
  1123. segmentsCount += state->destCount;
  1124. }
  1125. segmentsArg = PyTuple_New(segmentsCount);
  1126. if (NULL == segmentsArg) {
  1127. goto finally;
  1128. }
  1129. segmentIndex = 0;
  1130. for (i = 0; i < threadCount; i++) {
  1131. Py_ssize_t j;
  1132. WorkerState* state = &workerStates[i];
  1133. for (j = 0; j < state->destCount; j++) {
  1134. DestBuffer* destBuffer = &state->destBuffers[j];
  1135. buffer = BufferWithSegments_FromMemory(destBuffer->dest, destBuffer->destSize,
  1136. destBuffer->segments, destBuffer->segmentsSize);
  1137. if (NULL == buffer) {
  1138. goto finally;
  1139. }
  1140. /* Tell instance to use free() instsead of PyMem_Free(). */
  1141. buffer->useFree = 1;
  1142. /*
  1143. * BufferWithSegments_FromMemory takes ownership of the backing memory.
  1144. * Unset it here so it doesn't get freed below.
  1145. */
  1146. destBuffer->dest = NULL;
  1147. destBuffer->segments = NULL;
  1148. PyTuple_SET_ITEM(segmentsArg, segmentIndex++, (PyObject*)buffer);
  1149. }
  1150. }
  1151. result = (ZstdBufferWithSegmentsCollection*)PyObject_CallObject(
  1152. (PyObject*)&ZstdBufferWithSegmentsCollectionType, segmentsArg);
  1153. finally:
  1154. Py_CLEAR(segmentsArg);
  1155. if (pool) {
  1156. POOL_free(pool);
  1157. }
  1158. if (workerStates) {
  1159. Py_ssize_t j;
  1160. for (i = 0; i < threadCount; i++) {
  1161. WorkerState state = workerStates[i];
  1162. if (state.cctx) {
  1163. ZSTD_freeCCtx(state.cctx);
  1164. }
  1165. /* malloc() is used in worker thread. */
  1166. for (j = 0; j < state.destCount; j++) {
  1167. if (state.destBuffers) {
  1168. free(state.destBuffers[j].dest);
  1169. free(state.destBuffers[j].segments);
  1170. }
  1171. }
  1172. free(state.destBuffers);
  1173. }
  1174. PyMem_Free(workerStates);
  1175. }
  1176. return result;
  1177. }
  1178. PyDoc_STRVAR(ZstdCompressor_multi_compress_to_buffer__doc__,
  1179. "Compress multiple pieces of data as a single operation\n"
  1180. "\n"
  1181. "Receives a ``BufferWithSegmentsCollection``, a ``BufferWithSegments``, or\n"
  1182. "a list of bytes like objects holding data to compress.\n"
  1183. "\n"
  1184. "Returns a ``BufferWithSegmentsCollection`` holding compressed data.\n"
  1185. "\n"
  1186. "This function is optimized to perform multiple compression operations as\n"
  1187. "as possible with as little overhead as possbile.\n"
  1188. );
  1189. static ZstdBufferWithSegmentsCollection* ZstdCompressor_multi_compress_to_buffer(ZstdCompressor* self, PyObject* args, PyObject* kwargs) {
  1190. static char* kwlist[] = {
  1191. "data",
  1192. "threads",
  1193. NULL
  1194. };
  1195. PyObject* data;
  1196. int threads = 0;
  1197. Py_buffer* dataBuffers = NULL;
  1198. DataSources sources;
  1199. Py_ssize_t i;
  1200. Py_ssize_t sourceCount = 0;
  1201. ZstdBufferWithSegmentsCollection* result = NULL;
  1202. memset(&sources, 0, sizeof(sources));
  1203. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:multi_compress_to_buffer", kwlist,
  1204. &data, &threads)) {
  1205. return NULL;
  1206. }
  1207. if (threads < 0) {
  1208. threads = cpu_count();
  1209. }
  1210. if (threads < 2) {
  1211. threads = 1;
  1212. }
  1213. if (PyObject_TypeCheck(data, &ZstdBufferWithSegmentsType)) {
  1214. ZstdBufferWithSegments* buffer = (ZstdBufferWithSegments*)data;
  1215. sources.sources = PyMem_Malloc(buffer->segmentCount * sizeof(DataSource));
  1216. if (NULL == sources.sources) {
  1217. PyErr_NoMemory();
  1218. goto finally;
  1219. }
  1220. for (i = 0; i < buffer->segmentCount; i++) {
  1221. if (buffer->segments[i].length > SIZE_MAX) {
  1222. PyErr_Format(PyExc_ValueError,
  1223. "buffer segment %zd is too large for this platform", i);
  1224. goto finally;
  1225. }
  1226. sources.sources[i].sourceData = (char*)buffer->data + buffer->segments[i].offset;
  1227. sources.sources[i].sourceSize = (size_t)buffer->segments[i].length;
  1228. sources.totalSourceSize += buffer->segments[i].length;
  1229. }
  1230. sources.sourcesSize = buffer->segmentCount;
  1231. }
  1232. else if (PyObject_TypeCheck(data, &ZstdBufferWithSegmentsCollectionType)) {
  1233. Py_ssize_t j;
  1234. Py_ssize_t offset = 0;
  1235. ZstdBufferWithSegments* buffer;
  1236. ZstdBufferWithSegmentsCollection* collection = (ZstdBufferWithSegmentsCollection*)data;
  1237. sourceCount = BufferWithSegmentsCollection_length(collection);
  1238. sources.sources = PyMem_Malloc(sourceCount * sizeof(DataSource));
  1239. if (NULL == sources.sources) {
  1240. PyErr_NoMemory();
  1241. goto finally;
  1242. }
  1243. for (i = 0; i < collection->bufferCount; i++) {
  1244. buffer = collection->buffers[i];
  1245. for (j = 0; j < buffer->segmentCount; j++) {
  1246. if (buffer->segments[j].length > SIZE_MAX) {
  1247. PyErr_Format(PyExc_ValueError,
  1248. "buffer segment %zd in buffer %zd is too large for this platform",
  1249. j, i);
  1250. goto finally;
  1251. }
  1252. sources.sources[offset].sourceData = (char*)buffer->data + buffer->segments[j].offset;
  1253. sources.sources[offset].sourceSize = (size_t)buffer->segments[j].length;
  1254. sources.totalSourceSize += buffer->segments[j].length;
  1255. offset++;
  1256. }
  1257. }
  1258. sources.sourcesSize = sourceCount;
  1259. }
  1260. else if (PyList_Check(data)) {
  1261. sourceCount = PyList_GET_SIZE(data);
  1262. sources.sources = PyMem_Malloc(sourceCount * sizeof(DataSource));
  1263. if (NULL == sources.sources) {
  1264. PyErr_NoMemory();
  1265. goto finally;
  1266. }
  1267. dataBuffers = PyMem_Malloc(sourceCount * sizeof(Py_buffer));
  1268. if (NULL == dataBuffers) {
  1269. PyErr_NoMemory();
  1270. goto finally;
  1271. }
  1272. memset(dataBuffers, 0, sourceCount * sizeof(Py_buffer));
  1273. for (i = 0; i < sourceCount; i++) {
  1274. if (0 != PyObject_GetBuffer(PyList_GET_ITEM(data, i),
  1275. &dataBuffers[i], PyBUF_CONTIG_RO)) {
  1276. PyErr_Clear();
  1277. PyErr_Format(PyExc_TypeError, "item %zd not a bytes like object", i);
  1278. goto finally;
  1279. }
  1280. sources.sources[i].sourceData = dataBuffers[i].buf;
  1281. sources.sources[i].sourceSize = dataBuffers[i].len;
  1282. sources.totalSourceSize += dataBuffers[i].len;
  1283. }
  1284. sources.sourcesSize = sourceCount;
  1285. }
  1286. else {
  1287. PyErr_SetString(PyExc_TypeError, "argument must be list of BufferWithSegments");
  1288. goto finally;
  1289. }
  1290. if (0 == sources.sourcesSize) {
  1291. PyErr_SetString(PyExc_ValueError, "no source elements found");
  1292. goto finally;
  1293. }
  1294. if (0 == sources.totalSourceSize) {
  1295. PyErr_SetString(PyExc_ValueError, "source elements are empty");
  1296. goto finally;
  1297. }
  1298. if (sources.totalSourceSize > SIZE_MAX) {
  1299. PyErr_SetString(PyExc_ValueError, "sources are too large for this platform");
  1300. goto finally;
  1301. }
  1302. result = compress_from_datasources(self, &sources, threads);
  1303. finally:
  1304. PyMem_Free(sources.sources);
  1305. if (dataBuffers) {
  1306. for (i = 0; i < sourceCount; i++) {
  1307. PyBuffer_Release(&dataBuffers[i]);
  1308. }
  1309. PyMem_Free(dataBuffers);
  1310. }
  1311. return result;
  1312. }
  1313. static PyMethodDef ZstdCompressor_methods[] = {
  1314. { "chunker", (PyCFunction)ZstdCompressor_chunker,
  1315. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_chunker__doc__ },
  1316. { "compress", (PyCFunction)ZstdCompressor_compress,
  1317. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_compress__doc__ },
  1318. { "compressobj", (PyCFunction)ZstdCompressor_compressobj,
  1319. METH_VARARGS | METH_KEYWORDS, ZstdCompressionObj__doc__ },
  1320. { "copy_stream", (PyCFunction)ZstdCompressor_copy_stream,
  1321. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_copy_stream__doc__ },
  1322. { "stream_reader", (PyCFunction)ZstdCompressor_stream_reader,
  1323. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_stream_reader__doc__ },
  1324. { "stream_writer", (PyCFunction)ZstdCompressor_stream_writer,
  1325. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_stream_writer___doc__ },
  1326. { "read_to_iter", (PyCFunction)ZstdCompressor_read_to_iter,
  1327. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_read_to_iter__doc__ },
  1328. /* TODO Remove deprecated API */
  1329. { "read_from", (PyCFunction)ZstdCompressor_read_to_iter,
  1330. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_read_to_iter__doc__ },
  1331. /* TODO remove deprecated API */
  1332. { "write_to", (PyCFunction)ZstdCompressor_stream_writer,
  1333. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_stream_writer___doc__ },
  1334. { "multi_compress_to_buffer", (PyCFunction)ZstdCompressor_multi_compress_to_buffer,
  1335. METH_VARARGS | METH_KEYWORDS, ZstdCompressor_multi_compress_to_buffer__doc__ },
  1336. { "memory_size", (PyCFunction)ZstdCompressor_memory_size,
  1337. METH_NOARGS, ZstdCompressor_memory_size__doc__ },
  1338. { "frame_progression", (PyCFunction)ZstdCompressor_frame_progression,
  1339. METH_NOARGS, ZstdCompressor_frame_progression__doc__ },
  1340. { NULL, NULL }
  1341. };
  1342. PyTypeObject ZstdCompressorType = {
  1343. PyVarObject_HEAD_INIT(NULL, 0)
  1344. "zstd.ZstdCompressor", /* tp_name */
  1345. sizeof(ZstdCompressor), /* tp_basicsize */
  1346. 0, /* tp_itemsize */
  1347. (destructor)ZstdCompressor_dealloc, /* tp_dealloc */
  1348. 0, /* tp_print */
  1349. 0, /* tp_getattr */
  1350. 0, /* tp_setattr */
  1351. 0, /* tp_compare */
  1352. 0, /* tp_repr */
  1353. 0, /* tp_as_number */
  1354. 0, /* tp_as_sequence */
  1355. 0, /* tp_as_mapping */
  1356. 0, /* tp_hash */
  1357. 0, /* tp_call */
  1358. 0, /* tp_str */
  1359. 0, /* tp_getattro */
  1360. 0, /* tp_setattro */
  1361. 0, /* tp_as_buffer */
  1362. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1363. ZstdCompressor__doc__, /* tp_doc */
  1364. 0, /* tp_traverse */
  1365. 0, /* tp_clear */
  1366. 0, /* tp_richcompare */
  1367. 0, /* tp_weaklistoffset */
  1368. 0, /* tp_iter */
  1369. 0, /* tp_iternext */
  1370. ZstdCompressor_methods, /* tp_methods */
  1371. 0, /* tp_members */
  1372. 0, /* tp_getset */
  1373. 0, /* tp_base */
  1374. 0, /* tp_dict */
  1375. 0, /* tp_descr_get */
  1376. 0, /* tp_descr_set */
  1377. 0, /* tp_dictoffset */
  1378. (initproc)ZstdCompressor_init, /* tp_init */
  1379. 0, /* tp_alloc */
  1380. PyType_GenericNew, /* tp_new */
  1381. };
  1382. void compressor_module_init(PyObject* mod) {
  1383. Py_TYPE(&ZstdCompressorType) = &PyType_Type;
  1384. if (PyType_Ready(&ZstdCompressorType) < 0) {
  1385. return;
  1386. }
  1387. Py_INCREF((PyObject*)&ZstdCompressorType);
  1388. PyModule_AddObject(mod, "ZstdCompressor",
  1389. (PyObject*)&ZstdCompressorType);
  1390. }