compressor.c 46 KB

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