decompressor.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828
  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. /**
  12. * Ensure the ZSTD_DCtx on a decompressor is initiated and ready for a new operation.
  13. */
  14. int ensure_dctx(ZstdDecompressor* decompressor, int loadDict) {
  15. size_t zresult;
  16. ZSTD_DCtx_reset(decompressor->dctx, ZSTD_reset_session_only);
  17. if (decompressor->maxWindowSize) {
  18. zresult = ZSTD_DCtx_setMaxWindowSize(decompressor->dctx, decompressor->maxWindowSize);
  19. if (ZSTD_isError(zresult)) {
  20. PyErr_Format(ZstdError, "unable to set max window size: %s",
  21. ZSTD_getErrorName(zresult));
  22. return 1;
  23. }
  24. }
  25. zresult = ZSTD_DCtx_setFormat(decompressor->dctx, decompressor->format);
  26. if (ZSTD_isError(zresult)) {
  27. PyErr_Format(ZstdError, "unable to set decoding format: %s",
  28. ZSTD_getErrorName(zresult));
  29. return 1;
  30. }
  31. if (loadDict && decompressor->dict) {
  32. if (ensure_ddict(decompressor->dict)) {
  33. return 1;
  34. }
  35. zresult = ZSTD_DCtx_refDDict(decompressor->dctx, decompressor->dict->ddict);
  36. if (ZSTD_isError(zresult)) {
  37. PyErr_Format(ZstdError, "unable to reference prepared dictionary: %s",
  38. ZSTD_getErrorName(zresult));
  39. return 1;
  40. }
  41. }
  42. return 0;
  43. }
  44. PyDoc_STRVAR(Decompressor__doc__,
  45. "ZstdDecompressor(dict_data=None)\n"
  46. "\n"
  47. "Create an object used to perform Zstandard decompression.\n"
  48. "\n"
  49. "An instance can perform multiple decompression operations."
  50. );
  51. static int Decompressor_init(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  52. static char* kwlist[] = {
  53. "dict_data",
  54. "max_window_size",
  55. "format",
  56. NULL
  57. };
  58. ZstdCompressionDict* dict = NULL;
  59. Py_ssize_t maxWindowSize = 0;
  60. ZSTD_format_e format = ZSTD_f_zstd1;
  61. self->dctx = NULL;
  62. self->dict = NULL;
  63. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O!nI:ZstdDecompressor", kwlist,
  64. &ZstdCompressionDictType, &dict, &maxWindowSize, &format)) {
  65. return -1;
  66. }
  67. self->dctx = ZSTD_createDCtx();
  68. if (!self->dctx) {
  69. PyErr_NoMemory();
  70. goto except;
  71. }
  72. self->maxWindowSize = maxWindowSize;
  73. self->format = format;
  74. if (dict) {
  75. self->dict = dict;
  76. Py_INCREF(dict);
  77. }
  78. if (ensure_dctx(self, 1)) {
  79. goto except;
  80. }
  81. return 0;
  82. except:
  83. Py_CLEAR(self->dict);
  84. if (self->dctx) {
  85. ZSTD_freeDCtx(self->dctx);
  86. self->dctx = NULL;
  87. }
  88. return -1;
  89. }
  90. static void Decompressor_dealloc(ZstdDecompressor* self) {
  91. Py_CLEAR(self->dict);
  92. if (self->dctx) {
  93. ZSTD_freeDCtx(self->dctx);
  94. self->dctx = NULL;
  95. }
  96. PyObject_Del(self);
  97. }
  98. PyDoc_STRVAR(Decompressor_memory_size__doc__,
  99. "memory_size() -- Size of decompression context, in bytes\n"
  100. );
  101. static PyObject* Decompressor_memory_size(ZstdDecompressor* self) {
  102. if (self->dctx) {
  103. return PyLong_FromSize_t(ZSTD_sizeof_DCtx(self->dctx));
  104. }
  105. else {
  106. PyErr_SetString(ZstdError, "no decompressor context found; this should never happen");
  107. return NULL;
  108. }
  109. }
  110. PyDoc_STRVAR(Decompressor_copy_stream__doc__,
  111. "copy_stream(ifh, ofh[, read_size=default, write_size=default]) -- decompress data between streams\n"
  112. "\n"
  113. "Compressed data will be read from ``ifh``, decompressed, and written to\n"
  114. "``ofh``. ``ifh`` must have a ``read(size)`` method. ``ofh`` must have a\n"
  115. "``write(data)`` method.\n"
  116. "\n"
  117. "The optional ``read_size`` and ``write_size`` arguments control the chunk\n"
  118. "size of data that is ``read()`` and ``write()`` between streams. They default\n"
  119. "to the default input and output sizes of zstd decompressor streams.\n"
  120. );
  121. static PyObject* Decompressor_copy_stream(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  122. static char* kwlist[] = {
  123. "ifh",
  124. "ofh",
  125. "read_size",
  126. "write_size",
  127. NULL
  128. };
  129. PyObject* source;
  130. PyObject* dest;
  131. size_t inSize = ZSTD_DStreamInSize();
  132. size_t outSize = ZSTD_DStreamOutSize();
  133. ZSTD_inBuffer input;
  134. ZSTD_outBuffer output;
  135. Py_ssize_t totalRead = 0;
  136. Py_ssize_t totalWrite = 0;
  137. char* readBuffer;
  138. Py_ssize_t readSize;
  139. PyObject* readResult = NULL;
  140. PyObject* res = NULL;
  141. size_t zresult = 0;
  142. PyObject* writeResult;
  143. PyObject* totalReadPy;
  144. PyObject* totalWritePy;
  145. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|kk:copy_stream", kwlist,
  146. &source, &dest, &inSize, &outSize)) {
  147. return NULL;
  148. }
  149. if (!PyObject_HasAttrString(source, "read")) {
  150. PyErr_SetString(PyExc_ValueError, "first argument must have a read() method");
  151. return NULL;
  152. }
  153. if (!PyObject_HasAttrString(dest, "write")) {
  154. PyErr_SetString(PyExc_ValueError, "second argument must have a write() method");
  155. return NULL;
  156. }
  157. /* Prevent free on uninitialized memory in finally. */
  158. output.dst = NULL;
  159. if (ensure_dctx(self, 1)) {
  160. res = NULL;
  161. goto finally;
  162. }
  163. output.dst = PyMem_Malloc(outSize);
  164. if (!output.dst) {
  165. PyErr_NoMemory();
  166. res = NULL;
  167. goto finally;
  168. }
  169. output.size = outSize;
  170. output.pos = 0;
  171. /* Read source stream until EOF */
  172. while (1) {
  173. readResult = PyObject_CallMethod(source, "read", "n", inSize);
  174. if (!readResult) {
  175. PyErr_SetString(ZstdError, "could not read() from source");
  176. goto finally;
  177. }
  178. PyBytes_AsStringAndSize(readResult, &readBuffer, &readSize);
  179. /* If no data was read, we're at EOF. */
  180. if (0 == readSize) {
  181. break;
  182. }
  183. totalRead += readSize;
  184. /* Send data to decompressor */
  185. input.src = readBuffer;
  186. input.size = readSize;
  187. input.pos = 0;
  188. while (input.pos < input.size) {
  189. Py_BEGIN_ALLOW_THREADS
  190. zresult = ZSTD_decompressStream(self->dctx, &output, &input);
  191. Py_END_ALLOW_THREADS
  192. if (ZSTD_isError(zresult)) {
  193. PyErr_Format(ZstdError, "zstd decompressor error: %s",
  194. ZSTD_getErrorName(zresult));
  195. res = NULL;
  196. goto finally;
  197. }
  198. if (output.pos) {
  199. #if PY_MAJOR_VERSION >= 3
  200. writeResult = PyObject_CallMethod(dest, "write", "y#",
  201. #else
  202. writeResult = PyObject_CallMethod(dest, "write", "s#",
  203. #endif
  204. output.dst, output.pos);
  205. Py_XDECREF(writeResult);
  206. totalWrite += output.pos;
  207. output.pos = 0;
  208. }
  209. }
  210. Py_CLEAR(readResult);
  211. }
  212. /* Source stream is exhausted. Finish up. */
  213. totalReadPy = PyLong_FromSsize_t(totalRead);
  214. totalWritePy = PyLong_FromSsize_t(totalWrite);
  215. res = PyTuple_Pack(2, totalReadPy, totalWritePy);
  216. Py_DECREF(totalReadPy);
  217. Py_DECREF(totalWritePy);
  218. finally:
  219. if (output.dst) {
  220. PyMem_Free(output.dst);
  221. }
  222. Py_XDECREF(readResult);
  223. return res;
  224. }
  225. PyDoc_STRVAR(Decompressor_decompress__doc__,
  226. "decompress(data[, max_output_size=None]) -- Decompress data in its entirety\n"
  227. "\n"
  228. "This method will decompress the entirety of the argument and return the\n"
  229. "result.\n"
  230. "\n"
  231. "The input bytes are expected to contain a full Zstandard frame (something\n"
  232. "compressed with ``ZstdCompressor.compress()`` or similar). If the input does\n"
  233. "not contain a full frame, an exception will be raised.\n"
  234. "\n"
  235. "If the frame header of the compressed data does not contain the content size\n"
  236. "``max_output_size`` must be specified or ``ZstdError`` will be raised. An\n"
  237. "allocation of size ``max_output_size`` will be performed and an attempt will\n"
  238. "be made to perform decompression into that buffer. If the buffer is too\n"
  239. "small or cannot be allocated, ``ZstdError`` will be raised. The buffer will\n"
  240. "be resized if it is too large.\n"
  241. "\n"
  242. "Uncompressed data could be much larger than compressed data. As a result,\n"
  243. "calling this function could result in a very large memory allocation being\n"
  244. "performed to hold the uncompressed data. Therefore it is **highly**\n"
  245. "recommended to use a streaming decompression method instead of this one.\n"
  246. );
  247. PyObject* Decompressor_decompress(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  248. static char* kwlist[] = {
  249. "data",
  250. "max_output_size",
  251. NULL
  252. };
  253. Py_buffer source;
  254. Py_ssize_t maxOutputSize = 0;
  255. unsigned long long decompressedSize;
  256. size_t destCapacity;
  257. PyObject* result = NULL;
  258. size_t zresult;
  259. ZSTD_outBuffer outBuffer;
  260. ZSTD_inBuffer inBuffer;
  261. #if PY_MAJOR_VERSION >= 3
  262. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "y*|n:decompress",
  263. #else
  264. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|n:decompress",
  265. #endif
  266. kwlist, &source, &maxOutputSize)) {
  267. return NULL;
  268. }
  269. if (!PyBuffer_IsContiguous(&source, 'C') || source.ndim > 1) {
  270. PyErr_SetString(PyExc_ValueError,
  271. "data buffer should be contiguous and have at most one dimension");
  272. goto finally;
  273. }
  274. if (ensure_dctx(self, 1)) {
  275. goto finally;
  276. }
  277. decompressedSize = ZSTD_getFrameContentSize(source.buf, source.len);
  278. if (ZSTD_CONTENTSIZE_ERROR == decompressedSize) {
  279. PyErr_SetString(ZstdError, "error determining content size from frame header");
  280. goto finally;
  281. }
  282. /* Special case of empty frame. */
  283. else if (0 == decompressedSize) {
  284. result = PyBytes_FromStringAndSize("", 0);
  285. goto finally;
  286. }
  287. /* Missing content size in frame header. */
  288. if (ZSTD_CONTENTSIZE_UNKNOWN == decompressedSize) {
  289. if (0 == maxOutputSize) {
  290. PyErr_SetString(ZstdError, "could not determine content size in frame header");
  291. goto finally;
  292. }
  293. result = PyBytes_FromStringAndSize(NULL, maxOutputSize);
  294. destCapacity = maxOutputSize;
  295. decompressedSize = 0;
  296. }
  297. /* Size is recorded in frame header. */
  298. else {
  299. assert(SIZE_MAX >= PY_SSIZE_T_MAX);
  300. if (decompressedSize > PY_SSIZE_T_MAX) {
  301. PyErr_SetString(ZstdError, "frame is too large to decompress on this platform");
  302. goto finally;
  303. }
  304. result = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)decompressedSize);
  305. destCapacity = (size_t)decompressedSize;
  306. }
  307. if (!result) {
  308. goto finally;
  309. }
  310. outBuffer.dst = PyBytes_AsString(result);
  311. outBuffer.size = destCapacity;
  312. outBuffer.pos = 0;
  313. inBuffer.src = source.buf;
  314. inBuffer.size = source.len;
  315. inBuffer.pos = 0;
  316. Py_BEGIN_ALLOW_THREADS
  317. zresult = ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
  318. Py_END_ALLOW_THREADS
  319. if (ZSTD_isError(zresult)) {
  320. PyErr_Format(ZstdError, "decompression error: %s", ZSTD_getErrorName(zresult));
  321. Py_CLEAR(result);
  322. goto finally;
  323. }
  324. else if (zresult) {
  325. PyErr_Format(ZstdError, "decompression error: did not decompress full frame");
  326. Py_CLEAR(result);
  327. goto finally;
  328. }
  329. else if (decompressedSize && outBuffer.pos != decompressedSize) {
  330. PyErr_Format(ZstdError, "decompression error: decompressed %zu bytes; expected %llu",
  331. zresult, decompressedSize);
  332. Py_CLEAR(result);
  333. goto finally;
  334. }
  335. else if (outBuffer.pos < destCapacity) {
  336. if (safe_pybytes_resize(&result, outBuffer.pos)) {
  337. Py_CLEAR(result);
  338. goto finally;
  339. }
  340. }
  341. finally:
  342. PyBuffer_Release(&source);
  343. return result;
  344. }
  345. PyDoc_STRVAR(Decompressor_decompressobj__doc__,
  346. "decompressobj([write_size=default])\n"
  347. "\n"
  348. "Incrementally feed data into a decompressor.\n"
  349. "\n"
  350. "The returned object exposes a ``decompress(data)`` method. This makes it\n"
  351. "compatible with ``zlib.decompressobj`` and ``bz2.BZ2Decompressor`` so that\n"
  352. "callers can swap in the zstd decompressor while using the same API.\n"
  353. );
  354. static ZstdDecompressionObj* Decompressor_decompressobj(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  355. static char* kwlist[] = {
  356. "write_size",
  357. NULL
  358. };
  359. ZstdDecompressionObj* result = NULL;
  360. size_t outSize = ZSTD_DStreamOutSize();
  361. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|k:decompressobj", kwlist, &outSize)) {
  362. return NULL;
  363. }
  364. if (!outSize) {
  365. PyErr_SetString(PyExc_ValueError, "write_size must be positive");
  366. return NULL;
  367. }
  368. result = (ZstdDecompressionObj*)PyObject_CallObject((PyObject*)&ZstdDecompressionObjType, NULL);
  369. if (!result) {
  370. return NULL;
  371. }
  372. if (ensure_dctx(self, 1)) {
  373. Py_DECREF(result);
  374. return NULL;
  375. }
  376. result->decompressor = self;
  377. Py_INCREF(result->decompressor);
  378. result->outSize = outSize;
  379. return result;
  380. }
  381. PyDoc_STRVAR(Decompressor_read_to_iter__doc__,
  382. "read_to_iter(reader[, read_size=default, write_size=default, skip_bytes=0])\n"
  383. "Read compressed data and return an iterator\n"
  384. "\n"
  385. "Returns an iterator of decompressed data chunks produced from reading from\n"
  386. "the ``reader``.\n"
  387. "\n"
  388. "Compressed data will be obtained from ``reader`` by calling the\n"
  389. "``read(size)`` method of it. The source data will be streamed into a\n"
  390. "decompressor. As decompressed data is available, it will be exposed to the\n"
  391. "returned iterator.\n"
  392. "\n"
  393. "Data is ``read()`` in chunks of size ``read_size`` and exposed to the\n"
  394. "iterator in chunks of size ``write_size``. The default values are the input\n"
  395. "and output sizes for a zstd streaming decompressor.\n"
  396. "\n"
  397. "There is also support for skipping the first ``skip_bytes`` of data from\n"
  398. "the source.\n"
  399. );
  400. static ZstdDecompressorIterator* Decompressor_read_to_iter(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  401. static char* kwlist[] = {
  402. "reader",
  403. "read_size",
  404. "write_size",
  405. "skip_bytes",
  406. NULL
  407. };
  408. PyObject* reader;
  409. size_t inSize = ZSTD_DStreamInSize();
  410. size_t outSize = ZSTD_DStreamOutSize();
  411. ZstdDecompressorIterator* result;
  412. size_t skipBytes = 0;
  413. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kkk:read_to_iter", kwlist,
  414. &reader, &inSize, &outSize, &skipBytes)) {
  415. return NULL;
  416. }
  417. if (skipBytes >= inSize) {
  418. PyErr_SetString(PyExc_ValueError,
  419. "skip_bytes must be smaller than read_size");
  420. return NULL;
  421. }
  422. result = (ZstdDecompressorIterator*)PyObject_CallObject((PyObject*)&ZstdDecompressorIteratorType, NULL);
  423. if (!result) {
  424. return NULL;
  425. }
  426. if (PyObject_HasAttrString(reader, "read")) {
  427. result->reader = reader;
  428. Py_INCREF(result->reader);
  429. }
  430. else if (1 == PyObject_CheckBuffer(reader)) {
  431. /* Object claims it is a buffer. Try to get a handle to it. */
  432. if (0 != PyObject_GetBuffer(reader, &result->buffer, PyBUF_CONTIG_RO)) {
  433. goto except;
  434. }
  435. }
  436. else {
  437. PyErr_SetString(PyExc_ValueError,
  438. "must pass an object with a read() method or conforms to buffer protocol");
  439. goto except;
  440. }
  441. result->decompressor = self;
  442. Py_INCREF(result->decompressor);
  443. result->inSize = inSize;
  444. result->outSize = outSize;
  445. result->skipBytes = skipBytes;
  446. if (ensure_dctx(self, 1)) {
  447. goto except;
  448. }
  449. result->input.src = PyMem_Malloc(inSize);
  450. if (!result->input.src) {
  451. PyErr_NoMemory();
  452. goto except;
  453. }
  454. goto finally;
  455. except:
  456. Py_CLEAR(result);
  457. finally:
  458. return result;
  459. }
  460. PyDoc_STRVAR(Decompressor_stream_reader__doc__,
  461. "stream_reader(source, [read_size=default, [read_across_frames=False]])\n"
  462. "\n"
  463. "Obtain an object that behaves like an I/O stream that can be used for\n"
  464. "reading decompressed output from an object.\n"
  465. "\n"
  466. "The source object can be any object with a ``read(size)`` method or that\n"
  467. "conforms to the buffer protocol.\n"
  468. "\n"
  469. "``read_across_frames`` controls the behavior of ``read()`` when the end\n"
  470. "of a zstd frame is reached. When ``True``, ``read()`` can potentially\n"
  471. "return data belonging to multiple zstd frames. When ``False``, ``read()``\n"
  472. "will return when the end of a frame is reached.\n"
  473. );
  474. static ZstdDecompressionReader* Decompressor_stream_reader(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  475. static char* kwlist[] = {
  476. "source",
  477. "read_size",
  478. "read_across_frames",
  479. NULL
  480. };
  481. PyObject* source;
  482. size_t readSize = ZSTD_DStreamInSize();
  483. PyObject* readAcrossFrames = NULL;
  484. ZstdDecompressionReader* result;
  485. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kO:stream_reader", kwlist,
  486. &source, &readSize, &readAcrossFrames)) {
  487. return NULL;
  488. }
  489. if (ensure_dctx(self, 1)) {
  490. return NULL;
  491. }
  492. result = (ZstdDecompressionReader*)PyObject_CallObject((PyObject*)&ZstdDecompressionReaderType, NULL);
  493. if (NULL == result) {
  494. return NULL;
  495. }
  496. result->entered = 0;
  497. result->closed = 0;
  498. if (PyObject_HasAttrString(source, "read")) {
  499. result->reader = source;
  500. Py_INCREF(source);
  501. result->readSize = readSize;
  502. }
  503. else if (1 == PyObject_CheckBuffer(source)) {
  504. if (0 != PyObject_GetBuffer(source, &result->buffer, PyBUF_CONTIG_RO)) {
  505. Py_CLEAR(result);
  506. return NULL;
  507. }
  508. }
  509. else {
  510. PyErr_SetString(PyExc_TypeError,
  511. "must pass an object with a read() method or that conforms to the buffer protocol");
  512. Py_CLEAR(result);
  513. return NULL;
  514. }
  515. result->decompressor = self;
  516. Py_INCREF(self);
  517. result->readAcrossFrames = readAcrossFrames ? PyObject_IsTrue(readAcrossFrames) : 0;
  518. return result;
  519. }
  520. PyDoc_STRVAR(Decompressor_stream_writer__doc__,
  521. "Create a context manager to write decompressed data to an object.\n"
  522. "\n"
  523. "The passed object must have a ``write()`` method.\n"
  524. "\n"
  525. "The caller feeds intput data to the object by calling ``write(data)``.\n"
  526. "Decompressed data is written to the argument given as it is decompressed.\n"
  527. "\n"
  528. "An optional ``write_size`` argument defines the size of chunks to\n"
  529. "``write()`` to the writer. It defaults to the default output size for a zstd\n"
  530. "streaming decompressor.\n"
  531. );
  532. static ZstdDecompressionWriter* Decompressor_stream_writer(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  533. static char* kwlist[] = {
  534. "writer",
  535. "write_size",
  536. "write_return_read",
  537. NULL
  538. };
  539. PyObject* writer;
  540. size_t outSize = ZSTD_DStreamOutSize();
  541. PyObject* writeReturnRead = NULL;
  542. ZstdDecompressionWriter* result;
  543. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|kO:stream_writer", kwlist,
  544. &writer, &outSize, &writeReturnRead)) {
  545. return NULL;
  546. }
  547. if (!PyObject_HasAttrString(writer, "write")) {
  548. PyErr_SetString(PyExc_ValueError, "must pass an object with a write() method");
  549. return NULL;
  550. }
  551. if (ensure_dctx(self, 1)) {
  552. return NULL;
  553. }
  554. result = (ZstdDecompressionWriter*)PyObject_CallObject((PyObject*)&ZstdDecompressionWriterType, NULL);
  555. if (!result) {
  556. return NULL;
  557. }
  558. result->entered = 0;
  559. result->closed = 0;
  560. result->decompressor = self;
  561. Py_INCREF(result->decompressor);
  562. result->writer = writer;
  563. Py_INCREF(result->writer);
  564. result->outSize = outSize;
  565. result->writeReturnRead = writeReturnRead ? PyObject_IsTrue(writeReturnRead) : 0;
  566. return result;
  567. }
  568. PyDoc_STRVAR(Decompressor_decompress_content_dict_chain__doc__,
  569. "Decompress a series of chunks using the content dictionary chaining technique\n"
  570. );
  571. static PyObject* Decompressor_decompress_content_dict_chain(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  572. static char* kwlist[] = {
  573. "frames",
  574. NULL
  575. };
  576. PyObject* chunks;
  577. Py_ssize_t chunksLen;
  578. Py_ssize_t chunkIndex;
  579. char parity = 0;
  580. PyObject* chunk;
  581. char* chunkData;
  582. Py_ssize_t chunkSize;
  583. size_t zresult;
  584. ZSTD_frameHeader frameHeader;
  585. void* buffer1 = NULL;
  586. size_t buffer1Size = 0;
  587. size_t buffer1ContentSize = 0;
  588. void* buffer2 = NULL;
  589. size_t buffer2Size = 0;
  590. size_t buffer2ContentSize = 0;
  591. void* destBuffer = NULL;
  592. PyObject* result = NULL;
  593. ZSTD_outBuffer outBuffer;
  594. ZSTD_inBuffer inBuffer;
  595. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!:decompress_content_dict_chain",
  596. kwlist, &PyList_Type, &chunks)) {
  597. return NULL;
  598. }
  599. chunksLen = PyList_Size(chunks);
  600. if (!chunksLen) {
  601. PyErr_SetString(PyExc_ValueError, "empty input chain");
  602. return NULL;
  603. }
  604. /* The first chunk should not be using a dictionary. We handle it specially. */
  605. chunk = PyList_GetItem(chunks, 0);
  606. if (!PyBytes_Check(chunk)) {
  607. PyErr_SetString(PyExc_ValueError, "chunk 0 must be bytes");
  608. return NULL;
  609. }
  610. /* We require that all chunks be zstd frames and that they have content size set. */
  611. PyBytes_AsStringAndSize(chunk, &chunkData, &chunkSize);
  612. zresult = ZSTD_getFrameHeader(&frameHeader, (void*)chunkData, chunkSize);
  613. if (ZSTD_isError(zresult)) {
  614. PyErr_SetString(PyExc_ValueError, "chunk 0 is not a valid zstd frame");
  615. return NULL;
  616. }
  617. else if (zresult) {
  618. PyErr_SetString(PyExc_ValueError, "chunk 0 is too small to contain a zstd frame");
  619. return NULL;
  620. }
  621. if (ZSTD_CONTENTSIZE_UNKNOWN == frameHeader.frameContentSize) {
  622. PyErr_SetString(PyExc_ValueError, "chunk 0 missing content size in frame");
  623. return NULL;
  624. }
  625. assert(ZSTD_CONTENTSIZE_ERROR != frameHeader.frameContentSize);
  626. /* We check against PY_SSIZE_T_MAX here because we ultimately cast the
  627. * result to a Python object and it's length can be no greater than
  628. * Py_ssize_t. In theory, we could have an intermediate frame that is
  629. * larger. But a) why would this API be used for frames that large b)
  630. * it isn't worth the complexity to support. */
  631. assert(SIZE_MAX >= PY_SSIZE_T_MAX);
  632. if (frameHeader.frameContentSize > PY_SSIZE_T_MAX) {
  633. PyErr_SetString(PyExc_ValueError,
  634. "chunk 0 is too large to decompress on this platform");
  635. return NULL;
  636. }
  637. if (ensure_dctx(self, 0)) {
  638. goto finally;
  639. }
  640. buffer1Size = (size_t)frameHeader.frameContentSize;
  641. buffer1 = PyMem_Malloc(buffer1Size);
  642. if (!buffer1) {
  643. goto finally;
  644. }
  645. outBuffer.dst = buffer1;
  646. outBuffer.size = buffer1Size;
  647. outBuffer.pos = 0;
  648. inBuffer.src = chunkData;
  649. inBuffer.size = chunkSize;
  650. inBuffer.pos = 0;
  651. Py_BEGIN_ALLOW_THREADS
  652. zresult = ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
  653. Py_END_ALLOW_THREADS
  654. if (ZSTD_isError(zresult)) {
  655. PyErr_Format(ZstdError, "could not decompress chunk 0: %s", ZSTD_getErrorName(zresult));
  656. goto finally;
  657. }
  658. else if (zresult) {
  659. PyErr_Format(ZstdError, "chunk 0 did not decompress full frame");
  660. goto finally;
  661. }
  662. buffer1ContentSize = outBuffer.pos;
  663. /* Special case of a simple chain. */
  664. if (1 == chunksLen) {
  665. result = PyBytes_FromStringAndSize(buffer1, buffer1Size);
  666. goto finally;
  667. }
  668. /* This should ideally look at next chunk. But this is slightly simpler. */
  669. buffer2Size = (size_t)frameHeader.frameContentSize;
  670. buffer2 = PyMem_Malloc(buffer2Size);
  671. if (!buffer2) {
  672. goto finally;
  673. }
  674. /* For each subsequent chunk, use the previous fulltext as a content dictionary.
  675. Our strategy is to have 2 buffers. One holds the previous fulltext (to be
  676. used as a content dictionary) and the other holds the new fulltext. The
  677. buffers grow when needed but never decrease in size. This limits the
  678. memory allocator overhead.
  679. */
  680. for (chunkIndex = 1; chunkIndex < chunksLen; chunkIndex++) {
  681. chunk = PyList_GetItem(chunks, chunkIndex);
  682. if (!PyBytes_Check(chunk)) {
  683. PyErr_Format(PyExc_ValueError, "chunk %zd must be bytes", chunkIndex);
  684. goto finally;
  685. }
  686. PyBytes_AsStringAndSize(chunk, &chunkData, &chunkSize);
  687. zresult = ZSTD_getFrameHeader(&frameHeader, (void*)chunkData, chunkSize);
  688. if (ZSTD_isError(zresult)) {
  689. PyErr_Format(PyExc_ValueError, "chunk %zd is not a valid zstd frame", chunkIndex);
  690. goto finally;
  691. }
  692. else if (zresult) {
  693. PyErr_Format(PyExc_ValueError, "chunk %zd is too small to contain a zstd frame", chunkIndex);
  694. goto finally;
  695. }
  696. if (ZSTD_CONTENTSIZE_UNKNOWN == frameHeader.frameContentSize) {
  697. PyErr_Format(PyExc_ValueError, "chunk %zd missing content size in frame", chunkIndex);
  698. goto finally;
  699. }
  700. assert(ZSTD_CONTENTSIZE_ERROR != frameHeader.frameContentSize);
  701. if (frameHeader.frameContentSize > PY_SSIZE_T_MAX) {
  702. PyErr_Format(PyExc_ValueError,
  703. "chunk %zd is too large to decompress on this platform", chunkIndex);
  704. goto finally;
  705. }
  706. inBuffer.src = chunkData;
  707. inBuffer.size = chunkSize;
  708. inBuffer.pos = 0;
  709. parity = chunkIndex % 2;
  710. /* This could definitely be abstracted to reduce code duplication. */
  711. if (parity) {
  712. /* Resize destination buffer to hold larger content. */
  713. if (buffer2Size < frameHeader.frameContentSize) {
  714. buffer2Size = (size_t)frameHeader.frameContentSize;
  715. destBuffer = PyMem_Realloc(buffer2, buffer2Size);
  716. if (!destBuffer) {
  717. goto finally;
  718. }
  719. buffer2 = destBuffer;
  720. }
  721. Py_BEGIN_ALLOW_THREADS
  722. zresult = ZSTD_DCtx_refPrefix_advanced(self->dctx,
  723. buffer1, buffer1ContentSize, ZSTD_dct_rawContent);
  724. Py_END_ALLOW_THREADS
  725. if (ZSTD_isError(zresult)) {
  726. PyErr_Format(ZstdError,
  727. "failed to load prefix dictionary at chunk %zd", chunkIndex);
  728. goto finally;
  729. }
  730. outBuffer.dst = buffer2;
  731. outBuffer.size = buffer2Size;
  732. outBuffer.pos = 0;
  733. Py_BEGIN_ALLOW_THREADS
  734. zresult = ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
  735. Py_END_ALLOW_THREADS
  736. if (ZSTD_isError(zresult)) {
  737. PyErr_Format(ZstdError, "could not decompress chunk %zd: %s",
  738. chunkIndex, ZSTD_getErrorName(zresult));
  739. goto finally;
  740. }
  741. else if (zresult) {
  742. PyErr_Format(ZstdError, "chunk %zd did not decompress full frame",
  743. chunkIndex);
  744. goto finally;
  745. }
  746. buffer2ContentSize = outBuffer.pos;
  747. }
  748. else {
  749. if (buffer1Size < frameHeader.frameContentSize) {
  750. buffer1Size = (size_t)frameHeader.frameContentSize;
  751. destBuffer = PyMem_Realloc(buffer1, buffer1Size);
  752. if (!destBuffer) {
  753. goto finally;
  754. }
  755. buffer1 = destBuffer;
  756. }
  757. Py_BEGIN_ALLOW_THREADS
  758. zresult = ZSTD_DCtx_refPrefix_advanced(self->dctx,
  759. buffer2, buffer2ContentSize, ZSTD_dct_rawContent);
  760. Py_END_ALLOW_THREADS
  761. if (ZSTD_isError(zresult)) {
  762. PyErr_Format(ZstdError,
  763. "failed to load prefix dictionary at chunk %zd", chunkIndex);
  764. goto finally;
  765. }
  766. outBuffer.dst = buffer1;
  767. outBuffer.size = buffer1Size;
  768. outBuffer.pos = 0;
  769. Py_BEGIN_ALLOW_THREADS
  770. zresult = ZSTD_decompressStream(self->dctx, &outBuffer, &inBuffer);
  771. Py_END_ALLOW_THREADS
  772. if (ZSTD_isError(zresult)) {
  773. PyErr_Format(ZstdError, "could not decompress chunk %zd: %s",
  774. chunkIndex, ZSTD_getErrorName(zresult));
  775. goto finally;
  776. }
  777. else if (zresult) {
  778. PyErr_Format(ZstdError, "chunk %zd did not decompress full frame",
  779. chunkIndex);
  780. goto finally;
  781. }
  782. buffer1ContentSize = outBuffer.pos;
  783. }
  784. }
  785. result = PyBytes_FromStringAndSize(parity ? buffer2 : buffer1,
  786. parity ? buffer2ContentSize : buffer1ContentSize);
  787. finally:
  788. if (buffer2) {
  789. PyMem_Free(buffer2);
  790. }
  791. if (buffer1) {
  792. PyMem_Free(buffer1);
  793. }
  794. return result;
  795. }
  796. typedef struct {
  797. void* sourceData;
  798. size_t sourceSize;
  799. size_t destSize;
  800. } FramePointer;
  801. typedef struct {
  802. FramePointer* frames;
  803. Py_ssize_t framesSize;
  804. unsigned long long compressedSize;
  805. } FrameSources;
  806. typedef struct {
  807. void* dest;
  808. Py_ssize_t destSize;
  809. BufferSegment* segments;
  810. Py_ssize_t segmentsSize;
  811. } DestBuffer;
  812. typedef enum {
  813. WorkerError_none = 0,
  814. WorkerError_zstd = 1,
  815. WorkerError_memory = 2,
  816. WorkerError_sizeMismatch = 3,
  817. WorkerError_unknownSize = 4,
  818. } WorkerError;
  819. typedef struct {
  820. /* Source records and length */
  821. FramePointer* framePointers;
  822. /* Which records to process. */
  823. Py_ssize_t startOffset;
  824. Py_ssize_t endOffset;
  825. unsigned long long totalSourceSize;
  826. /* Compression state and settings. */
  827. ZSTD_DCtx* dctx;
  828. int requireOutputSizes;
  829. /* Output storage. */
  830. DestBuffer* destBuffers;
  831. Py_ssize_t destCount;
  832. /* Item that error occurred on. */
  833. Py_ssize_t errorOffset;
  834. /* If an error occurred. */
  835. WorkerError error;
  836. /* result from zstd decompression operation */
  837. size_t zresult;
  838. } WorkerState;
  839. static void decompress_worker(WorkerState* state) {
  840. size_t allocationSize;
  841. DestBuffer* destBuffer;
  842. Py_ssize_t frameIndex;
  843. Py_ssize_t localOffset = 0;
  844. Py_ssize_t currentBufferStartIndex = state->startOffset;
  845. Py_ssize_t remainingItems = state->endOffset - state->startOffset + 1;
  846. void* tmpBuf;
  847. Py_ssize_t destOffset = 0;
  848. FramePointer* framePointers = state->framePointers;
  849. size_t zresult;
  850. unsigned long long totalOutputSize = 0;
  851. assert(NULL == state->destBuffers);
  852. assert(0 == state->destCount);
  853. assert(state->endOffset - state->startOffset >= 0);
  854. /* We could get here due to the way work is allocated. Ideally we wouldn't
  855. get here. But that would require a bit of a refactor in the caller. */
  856. if (state->totalSourceSize > SIZE_MAX) {
  857. state->error = WorkerError_memory;
  858. state->errorOffset = 0;
  859. return;
  860. }
  861. /*
  862. * We need to allocate a buffer to hold decompressed data. How we do this
  863. * depends on what we know about the output. The following scenarios are
  864. * possible:
  865. *
  866. * 1. All structs defining frames declare the output size.
  867. * 2. The decompressed size is embedded within the zstd frame.
  868. * 3. The decompressed size is not stored anywhere.
  869. *
  870. * For now, we only support #1 and #2.
  871. */
  872. /* Resolve ouput segments. */
  873. for (frameIndex = state->startOffset; frameIndex <= state->endOffset; frameIndex++) {
  874. FramePointer* fp = &framePointers[frameIndex];
  875. unsigned long long decompressedSize;
  876. if (0 == fp->destSize) {
  877. decompressedSize = ZSTD_getFrameContentSize(fp->sourceData, fp->sourceSize);
  878. if (ZSTD_CONTENTSIZE_ERROR == decompressedSize) {
  879. state->error = WorkerError_unknownSize;
  880. state->errorOffset = frameIndex;
  881. return;
  882. }
  883. else if (ZSTD_CONTENTSIZE_UNKNOWN == decompressedSize) {
  884. if (state->requireOutputSizes) {
  885. state->error = WorkerError_unknownSize;
  886. state->errorOffset = frameIndex;
  887. return;
  888. }
  889. /* This will fail the assert for .destSize > 0 below. */
  890. decompressedSize = 0;
  891. }
  892. if (decompressedSize > SIZE_MAX) {
  893. state->error = WorkerError_memory;
  894. state->errorOffset = frameIndex;
  895. return;
  896. }
  897. fp->destSize = (size_t)decompressedSize;
  898. }
  899. totalOutputSize += fp->destSize;
  900. }
  901. state->destBuffers = calloc(1, sizeof(DestBuffer));
  902. if (NULL == state->destBuffers) {
  903. state->error = WorkerError_memory;
  904. return;
  905. }
  906. state->destCount = 1;
  907. destBuffer = &state->destBuffers[state->destCount - 1];
  908. assert(framePointers[state->startOffset].destSize > 0); /* For now. */
  909. allocationSize = roundpow2((size_t)state->totalSourceSize);
  910. if (framePointers[state->startOffset].destSize > allocationSize) {
  911. allocationSize = roundpow2(framePointers[state->startOffset].destSize);
  912. }
  913. destBuffer->dest = malloc(allocationSize);
  914. if (NULL == destBuffer->dest) {
  915. state->error = WorkerError_memory;
  916. return;
  917. }
  918. destBuffer->destSize = allocationSize;
  919. destBuffer->segments = calloc(remainingItems, sizeof(BufferSegment));
  920. if (NULL == destBuffer->segments) {
  921. /* Caller will free state->dest as part of cleanup. */
  922. state->error = WorkerError_memory;
  923. return;
  924. }
  925. destBuffer->segmentsSize = remainingItems;
  926. for (frameIndex = state->startOffset; frameIndex <= state->endOffset; frameIndex++) {
  927. ZSTD_outBuffer outBuffer;
  928. ZSTD_inBuffer inBuffer;
  929. const void* source = framePointers[frameIndex].sourceData;
  930. const size_t sourceSize = framePointers[frameIndex].sourceSize;
  931. void* dest;
  932. const size_t decompressedSize = framePointers[frameIndex].destSize;
  933. size_t destAvailable = destBuffer->destSize - destOffset;
  934. assert(decompressedSize > 0); /* For now. */
  935. /*
  936. * Not enough space in current buffer. Finish current before and allocate and
  937. * switch to a new one.
  938. */
  939. if (decompressedSize > destAvailable) {
  940. /*
  941. * Shrinking the destination buffer is optional. But it should be cheap,
  942. * so we just do it.
  943. */
  944. if (destAvailable) {
  945. tmpBuf = realloc(destBuffer->dest, destOffset);
  946. if (NULL == tmpBuf) {
  947. state->error = WorkerError_memory;
  948. return;
  949. }
  950. destBuffer->dest = tmpBuf;
  951. destBuffer->destSize = destOffset;
  952. }
  953. /* Truncate segments buffer. */
  954. tmpBuf = realloc(destBuffer->segments,
  955. (frameIndex - currentBufferStartIndex) * sizeof(BufferSegment));
  956. if (NULL == tmpBuf) {
  957. state->error = WorkerError_memory;
  958. return;
  959. }
  960. destBuffer->segments = tmpBuf;
  961. destBuffer->segmentsSize = frameIndex - currentBufferStartIndex;
  962. /* Grow space for new DestBuffer. */
  963. tmpBuf = realloc(state->destBuffers, (state->destCount + 1) * sizeof(DestBuffer));
  964. if (NULL == tmpBuf) {
  965. state->error = WorkerError_memory;
  966. return;
  967. }
  968. state->destBuffers = tmpBuf;
  969. state->destCount++;
  970. destBuffer = &state->destBuffers[state->destCount - 1];
  971. /* Don't take any chances will non-NULL pointers. */
  972. memset(destBuffer, 0, sizeof(DestBuffer));
  973. allocationSize = roundpow2((size_t)state->totalSourceSize);
  974. if (decompressedSize > allocationSize) {
  975. allocationSize = roundpow2(decompressedSize);
  976. }
  977. destBuffer->dest = malloc(allocationSize);
  978. if (NULL == destBuffer->dest) {
  979. state->error = WorkerError_memory;
  980. return;
  981. }
  982. destBuffer->destSize = allocationSize;
  983. destAvailable = allocationSize;
  984. destOffset = 0;
  985. localOffset = 0;
  986. destBuffer->segments = calloc(remainingItems, sizeof(BufferSegment));
  987. if (NULL == destBuffer->segments) {
  988. state->error = WorkerError_memory;
  989. return;
  990. }
  991. destBuffer->segmentsSize = remainingItems;
  992. currentBufferStartIndex = frameIndex;
  993. }
  994. dest = (char*)destBuffer->dest + destOffset;
  995. outBuffer.dst = dest;
  996. outBuffer.size = decompressedSize;
  997. outBuffer.pos = 0;
  998. inBuffer.src = source;
  999. inBuffer.size = sourceSize;
  1000. inBuffer.pos = 0;
  1001. zresult = ZSTD_decompressStream(state->dctx, &outBuffer, &inBuffer);
  1002. if (ZSTD_isError(zresult)) {
  1003. state->error = WorkerError_zstd;
  1004. state->zresult = zresult;
  1005. state->errorOffset = frameIndex;
  1006. return;
  1007. }
  1008. else if (zresult || outBuffer.pos != decompressedSize) {
  1009. state->error = WorkerError_sizeMismatch;
  1010. state->zresult = outBuffer.pos;
  1011. state->errorOffset = frameIndex;
  1012. return;
  1013. }
  1014. destBuffer->segments[localOffset].offset = destOffset;
  1015. destBuffer->segments[localOffset].length = outBuffer.pos;
  1016. destOffset += outBuffer.pos;
  1017. localOffset++;
  1018. remainingItems--;
  1019. }
  1020. if (destBuffer->destSize > destOffset) {
  1021. tmpBuf = realloc(destBuffer->dest, destOffset);
  1022. if (NULL == tmpBuf) {
  1023. state->error = WorkerError_memory;
  1024. return;
  1025. }
  1026. destBuffer->dest = tmpBuf;
  1027. destBuffer->destSize = destOffset;
  1028. }
  1029. }
  1030. ZstdBufferWithSegmentsCollection* decompress_from_framesources(ZstdDecompressor* decompressor, FrameSources* frames,
  1031. Py_ssize_t threadCount) {
  1032. Py_ssize_t i = 0;
  1033. int errored = 0;
  1034. Py_ssize_t segmentsCount;
  1035. ZstdBufferWithSegments* bws = NULL;
  1036. PyObject* resultArg = NULL;
  1037. Py_ssize_t resultIndex;
  1038. ZstdBufferWithSegmentsCollection* result = NULL;
  1039. FramePointer* framePointers = frames->frames;
  1040. unsigned long long workerBytes = 0;
  1041. Py_ssize_t currentThread = 0;
  1042. Py_ssize_t workerStartOffset = 0;
  1043. POOL_ctx* pool = NULL;
  1044. WorkerState* workerStates = NULL;
  1045. unsigned long long bytesPerWorker;
  1046. /* Caller should normalize 0 and negative values to 1 or larger. */
  1047. assert(threadCount >= 1);
  1048. /* More threads than inputs makes no sense under any conditions. */
  1049. threadCount = frames->framesSize < threadCount ? frames->framesSize
  1050. : threadCount;
  1051. /* TODO lower thread count if input size is too small and threads would just
  1052. add overhead. */
  1053. if (decompressor->dict) {
  1054. if (ensure_ddict(decompressor->dict)) {
  1055. return NULL;
  1056. }
  1057. }
  1058. /* If threadCount==1, we don't start a thread pool. But we do leverage the
  1059. same API for dispatching work. */
  1060. workerStates = PyMem_Malloc(threadCount * sizeof(WorkerState));
  1061. if (NULL == workerStates) {
  1062. PyErr_NoMemory();
  1063. goto finally;
  1064. }
  1065. memset(workerStates, 0, threadCount * sizeof(WorkerState));
  1066. if (threadCount > 1) {
  1067. pool = POOL_create(threadCount, 1);
  1068. if (NULL == pool) {
  1069. PyErr_SetString(ZstdError, "could not initialize zstd thread pool");
  1070. goto finally;
  1071. }
  1072. }
  1073. bytesPerWorker = frames->compressedSize / threadCount;
  1074. if (bytesPerWorker > SIZE_MAX) {
  1075. PyErr_SetString(ZstdError, "too much data per worker for this platform");
  1076. goto finally;
  1077. }
  1078. for (i = 0; i < threadCount; i++) {
  1079. size_t zresult;
  1080. workerStates[i].dctx = ZSTD_createDCtx();
  1081. if (NULL == workerStates[i].dctx) {
  1082. PyErr_NoMemory();
  1083. goto finally;
  1084. }
  1085. ZSTD_copyDCtx(workerStates[i].dctx, decompressor->dctx);
  1086. if (decompressor->dict) {
  1087. zresult = ZSTD_DCtx_refDDict(workerStates[i].dctx, decompressor->dict->ddict);
  1088. if (zresult) {
  1089. PyErr_Format(ZstdError, "unable to reference prepared dictionary: %s",
  1090. ZSTD_getErrorName(zresult));
  1091. goto finally;
  1092. }
  1093. }
  1094. workerStates[i].framePointers = framePointers;
  1095. workerStates[i].requireOutputSizes = 1;
  1096. }
  1097. Py_BEGIN_ALLOW_THREADS
  1098. /* There are many ways to split work among workers.
  1099. For now, we take a simple approach of splitting work so each worker
  1100. gets roughly the same number of input bytes. This will result in more
  1101. starvation than running N>threadCount jobs. But it avoids complications
  1102. around state tracking, which could involve extra locking.
  1103. */
  1104. for (i = 0; i < frames->framesSize; i++) {
  1105. workerBytes += frames->frames[i].sourceSize;
  1106. /*
  1107. * The last worker/thread needs to handle all remaining work. Don't
  1108. * trigger it prematurely. Defer to the block outside of the loop.
  1109. * (But still process this loop so workerBytes is correct.
  1110. */
  1111. if (currentThread == threadCount - 1) {
  1112. continue;
  1113. }
  1114. if (workerBytes >= bytesPerWorker) {
  1115. workerStates[currentThread].startOffset = workerStartOffset;
  1116. workerStates[currentThread].endOffset = i;
  1117. workerStates[currentThread].totalSourceSize = workerBytes;
  1118. if (threadCount > 1) {
  1119. POOL_add(pool, (POOL_function)decompress_worker, &workerStates[currentThread]);
  1120. }
  1121. else {
  1122. decompress_worker(&workerStates[currentThread]);
  1123. }
  1124. currentThread++;
  1125. workerStartOffset = i + 1;
  1126. workerBytes = 0;
  1127. }
  1128. }
  1129. if (workerBytes) {
  1130. workerStates[currentThread].startOffset = workerStartOffset;
  1131. workerStates[currentThread].endOffset = frames->framesSize - 1;
  1132. workerStates[currentThread].totalSourceSize = workerBytes;
  1133. if (threadCount > 1) {
  1134. POOL_add(pool, (POOL_function)decompress_worker, &workerStates[currentThread]);
  1135. }
  1136. else {
  1137. decompress_worker(&workerStates[currentThread]);
  1138. }
  1139. }
  1140. if (threadCount > 1) {
  1141. POOL_free(pool);
  1142. pool = NULL;
  1143. }
  1144. Py_END_ALLOW_THREADS
  1145. for (i = 0; i < threadCount; i++) {
  1146. switch (workerStates[i].error) {
  1147. case WorkerError_none:
  1148. break;
  1149. case WorkerError_zstd:
  1150. PyErr_Format(ZstdError, "error decompressing item %zd: %s",
  1151. workerStates[i].errorOffset, ZSTD_getErrorName(workerStates[i].zresult));
  1152. errored = 1;
  1153. break;
  1154. case WorkerError_memory:
  1155. PyErr_NoMemory();
  1156. errored = 1;
  1157. break;
  1158. case WorkerError_sizeMismatch:
  1159. PyErr_Format(ZstdError, "error decompressing item %zd: decompressed %zu bytes; expected %zu",
  1160. workerStates[i].errorOffset, workerStates[i].zresult,
  1161. framePointers[workerStates[i].errorOffset].destSize);
  1162. errored = 1;
  1163. break;
  1164. case WorkerError_unknownSize:
  1165. PyErr_Format(PyExc_ValueError, "could not determine decompressed size of item %zd",
  1166. workerStates[i].errorOffset);
  1167. errored = 1;
  1168. break;
  1169. default:
  1170. PyErr_Format(ZstdError, "unhandled error type: %d; this is a bug",
  1171. workerStates[i].error);
  1172. errored = 1;
  1173. break;
  1174. }
  1175. if (errored) {
  1176. break;
  1177. }
  1178. }
  1179. if (errored) {
  1180. goto finally;
  1181. }
  1182. segmentsCount = 0;
  1183. for (i = 0; i < threadCount; i++) {
  1184. segmentsCount += workerStates[i].destCount;
  1185. }
  1186. resultArg = PyTuple_New(segmentsCount);
  1187. if (NULL == resultArg) {
  1188. goto finally;
  1189. }
  1190. resultIndex = 0;
  1191. for (i = 0; i < threadCount; i++) {
  1192. Py_ssize_t bufferIndex;
  1193. WorkerState* state = &workerStates[i];
  1194. for (bufferIndex = 0; bufferIndex < state->destCount; bufferIndex++) {
  1195. DestBuffer* destBuffer = &state->destBuffers[bufferIndex];
  1196. bws = BufferWithSegments_FromMemory(destBuffer->dest, destBuffer->destSize,
  1197. destBuffer->segments, destBuffer->segmentsSize);
  1198. if (NULL == bws) {
  1199. goto finally;
  1200. }
  1201. /*
  1202. * Memory for buffer and segments was allocated using malloc() in worker
  1203. * and the memory is transferred to the BufferWithSegments instance. So
  1204. * tell instance to use free() and NULL the reference in the state struct
  1205. * so it isn't freed below.
  1206. */
  1207. bws->useFree = 1;
  1208. destBuffer->dest = NULL;
  1209. destBuffer->segments = NULL;
  1210. PyTuple_SET_ITEM(resultArg, resultIndex++, (PyObject*)bws);
  1211. }
  1212. }
  1213. result = (ZstdBufferWithSegmentsCollection*)PyObject_CallObject(
  1214. (PyObject*)&ZstdBufferWithSegmentsCollectionType, resultArg);
  1215. finally:
  1216. Py_CLEAR(resultArg);
  1217. if (workerStates) {
  1218. for (i = 0; i < threadCount; i++) {
  1219. Py_ssize_t bufferIndex;
  1220. WorkerState* state = &workerStates[i];
  1221. if (state->dctx) {
  1222. ZSTD_freeDCtx(state->dctx);
  1223. }
  1224. for (bufferIndex = 0; bufferIndex < state->destCount; bufferIndex++) {
  1225. if (state->destBuffers) {
  1226. /*
  1227. * Will be NULL if memory transfered to a BufferWithSegments.
  1228. * Otherwise it is left over after an error occurred.
  1229. */
  1230. free(state->destBuffers[bufferIndex].dest);
  1231. free(state->destBuffers[bufferIndex].segments);
  1232. }
  1233. }
  1234. free(state->destBuffers);
  1235. }
  1236. PyMem_Free(workerStates);
  1237. }
  1238. POOL_free(pool);
  1239. return result;
  1240. }
  1241. PyDoc_STRVAR(Decompressor_multi_decompress_to_buffer__doc__,
  1242. "Decompress multiple frames to output buffers\n"
  1243. "\n"
  1244. "Receives a ``BufferWithSegments``, a ``BufferWithSegmentsCollection`` or a\n"
  1245. "list of bytes-like objects. Each item in the passed collection should be a\n"
  1246. "compressed zstd frame.\n"
  1247. "\n"
  1248. "Unless ``decompressed_sizes`` is specified, the content size *must* be\n"
  1249. "written into the zstd frame header. If ``decompressed_sizes`` is specified,\n"
  1250. "it is an object conforming to the buffer protocol that represents an array\n"
  1251. "of 64-bit unsigned integers in the machine's native format. Specifying\n"
  1252. "``decompressed_sizes`` avoids a pre-scan of each frame to determine its\n"
  1253. "output size.\n"
  1254. "\n"
  1255. "Returns a ``BufferWithSegmentsCollection`` containing the decompressed\n"
  1256. "data. All decompressed data is allocated in a single memory buffer. The\n"
  1257. "``BufferWithSegments`` instance tracks which objects are at which offsets\n"
  1258. "and their respective lengths.\n"
  1259. "\n"
  1260. "The ``threads`` argument controls how many threads to use for operations.\n"
  1261. "Negative values will use the same number of threads as logical CPUs on the\n"
  1262. "machine.\n"
  1263. );
  1264. static ZstdBufferWithSegmentsCollection* Decompressor_multi_decompress_to_buffer(ZstdDecompressor* self, PyObject* args, PyObject* kwargs) {
  1265. static char* kwlist[] = {
  1266. "frames",
  1267. "decompressed_sizes",
  1268. "threads",
  1269. NULL
  1270. };
  1271. PyObject* frames;
  1272. Py_buffer frameSizes;
  1273. int threads = 0;
  1274. Py_ssize_t frameCount;
  1275. Py_buffer* frameBuffers = NULL;
  1276. FramePointer* framePointers = NULL;
  1277. unsigned long long* frameSizesP = NULL;
  1278. unsigned long long totalInputSize = 0;
  1279. FrameSources frameSources;
  1280. ZstdBufferWithSegmentsCollection* result = NULL;
  1281. Py_ssize_t i;
  1282. memset(&frameSizes, 0, sizeof(frameSizes));
  1283. #if PY_MAJOR_VERSION >= 3
  1284. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|y*i:multi_decompress_to_buffer",
  1285. #else
  1286. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|s*i:multi_decompress_to_buffer",
  1287. #endif
  1288. kwlist, &frames, &frameSizes, &threads)) {
  1289. return NULL;
  1290. }
  1291. if (frameSizes.buf) {
  1292. if (!PyBuffer_IsContiguous(&frameSizes, 'C') || frameSizes.ndim > 1) {
  1293. PyErr_SetString(PyExc_ValueError, "decompressed_sizes buffer should be contiguous and have a single dimension");
  1294. goto finally;
  1295. }
  1296. frameSizesP = (unsigned long long*)frameSizes.buf;
  1297. }
  1298. if (threads < 0) {
  1299. threads = cpu_count();
  1300. }
  1301. if (threads < 2) {
  1302. threads = 1;
  1303. }
  1304. if (PyObject_TypeCheck(frames, &ZstdBufferWithSegmentsType)) {
  1305. ZstdBufferWithSegments* buffer = (ZstdBufferWithSegments*)frames;
  1306. frameCount = buffer->segmentCount;
  1307. if (frameSizes.buf && frameSizes.len != frameCount * (Py_ssize_t)sizeof(unsigned long long)) {
  1308. PyErr_Format(PyExc_ValueError, "decompressed_sizes size mismatch; expected %zd, got %zd",
  1309. frameCount * sizeof(unsigned long long), frameSizes.len);
  1310. goto finally;
  1311. }
  1312. framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
  1313. if (!framePointers) {
  1314. PyErr_NoMemory();
  1315. goto finally;
  1316. }
  1317. for (i = 0; i < frameCount; i++) {
  1318. void* sourceData;
  1319. unsigned long long sourceSize;
  1320. unsigned long long decompressedSize = 0;
  1321. if (buffer->segments[i].offset + buffer->segments[i].length > buffer->dataSize) {
  1322. PyErr_Format(PyExc_ValueError, "item %zd has offset outside memory area", i);
  1323. goto finally;
  1324. }
  1325. sourceData = (char*)buffer->data + buffer->segments[i].offset;
  1326. sourceSize = buffer->segments[i].length;
  1327. totalInputSize += sourceSize;
  1328. if (frameSizesP) {
  1329. decompressedSize = frameSizesP[i];
  1330. }
  1331. if (sourceSize > SIZE_MAX) {
  1332. PyErr_Format(PyExc_ValueError,
  1333. "item %zd is too large for this platform", i);
  1334. goto finally;
  1335. }
  1336. if (decompressedSize > SIZE_MAX) {
  1337. PyErr_Format(PyExc_ValueError,
  1338. "decompressed size of item %zd is too large for this platform", i);
  1339. goto finally;
  1340. }
  1341. framePointers[i].sourceData = sourceData;
  1342. framePointers[i].sourceSize = (size_t)sourceSize;
  1343. framePointers[i].destSize = (size_t)decompressedSize;
  1344. }
  1345. }
  1346. else if (PyObject_TypeCheck(frames, &ZstdBufferWithSegmentsCollectionType)) {
  1347. Py_ssize_t offset = 0;
  1348. ZstdBufferWithSegments* buffer;
  1349. ZstdBufferWithSegmentsCollection* collection = (ZstdBufferWithSegmentsCollection*)frames;
  1350. frameCount = BufferWithSegmentsCollection_length(collection);
  1351. if (frameSizes.buf && frameSizes.len != frameCount) {
  1352. PyErr_Format(PyExc_ValueError,
  1353. "decompressed_sizes size mismatch; expected %zd; got %zd",
  1354. frameCount * sizeof(unsigned long long), frameSizes.len);
  1355. goto finally;
  1356. }
  1357. framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
  1358. if (NULL == framePointers) {
  1359. PyErr_NoMemory();
  1360. goto finally;
  1361. }
  1362. /* Iterate the data structure directly because it is faster. */
  1363. for (i = 0; i < collection->bufferCount; i++) {
  1364. Py_ssize_t segmentIndex;
  1365. buffer = collection->buffers[i];
  1366. for (segmentIndex = 0; segmentIndex < buffer->segmentCount; segmentIndex++) {
  1367. unsigned long long decompressedSize = frameSizesP ? frameSizesP[offset] : 0;
  1368. if (buffer->segments[segmentIndex].offset + buffer->segments[segmentIndex].length > buffer->dataSize) {
  1369. PyErr_Format(PyExc_ValueError, "item %zd has offset outside memory area",
  1370. offset);
  1371. goto finally;
  1372. }
  1373. if (buffer->segments[segmentIndex].length > SIZE_MAX) {
  1374. PyErr_Format(PyExc_ValueError,
  1375. "item %zd in buffer %zd is too large for this platform",
  1376. segmentIndex, i);
  1377. goto finally;
  1378. }
  1379. if (decompressedSize > SIZE_MAX) {
  1380. PyErr_Format(PyExc_ValueError,
  1381. "decompressed size of item %zd in buffer %zd is too large for this platform",
  1382. segmentIndex, i);
  1383. goto finally;
  1384. }
  1385. totalInputSize += buffer->segments[segmentIndex].length;
  1386. framePointers[offset].sourceData = (char*)buffer->data + buffer->segments[segmentIndex].offset;
  1387. framePointers[offset].sourceSize = (size_t)buffer->segments[segmentIndex].length;
  1388. framePointers[offset].destSize = (size_t)decompressedSize;
  1389. offset++;
  1390. }
  1391. }
  1392. }
  1393. else if (PyList_Check(frames)) {
  1394. frameCount = PyList_GET_SIZE(frames);
  1395. if (frameSizes.buf && frameSizes.len != frameCount * (Py_ssize_t)sizeof(unsigned long long)) {
  1396. PyErr_Format(PyExc_ValueError, "decompressed_sizes size mismatch; expected %zd, got %zd",
  1397. frameCount * sizeof(unsigned long long), frameSizes.len);
  1398. goto finally;
  1399. }
  1400. framePointers = PyMem_Malloc(frameCount * sizeof(FramePointer));
  1401. if (!framePointers) {
  1402. PyErr_NoMemory();
  1403. goto finally;
  1404. }
  1405. frameBuffers = PyMem_Malloc(frameCount * sizeof(Py_buffer));
  1406. if (NULL == frameBuffers) {
  1407. PyErr_NoMemory();
  1408. goto finally;
  1409. }
  1410. memset(frameBuffers, 0, frameCount * sizeof(Py_buffer));
  1411. /* Do a pass to assemble info about our input buffers and output sizes. */
  1412. for (i = 0; i < frameCount; i++) {
  1413. unsigned long long decompressedSize = frameSizesP ? frameSizesP[i] : 0;
  1414. if (0 != PyObject_GetBuffer(PyList_GET_ITEM(frames, i),
  1415. &frameBuffers[i], PyBUF_CONTIG_RO)) {
  1416. PyErr_Clear();
  1417. PyErr_Format(PyExc_TypeError, "item %zd not a bytes like object", i);
  1418. goto finally;
  1419. }
  1420. if (decompressedSize > SIZE_MAX) {
  1421. PyErr_Format(PyExc_ValueError,
  1422. "decompressed size of item %zd is too large for this platform", i);
  1423. goto finally;
  1424. }
  1425. totalInputSize += frameBuffers[i].len;
  1426. framePointers[i].sourceData = frameBuffers[i].buf;
  1427. framePointers[i].sourceSize = frameBuffers[i].len;
  1428. framePointers[i].destSize = (size_t)decompressedSize;
  1429. }
  1430. }
  1431. else {
  1432. PyErr_SetString(PyExc_TypeError, "argument must be list or BufferWithSegments");
  1433. goto finally;
  1434. }
  1435. /* We now have an array with info about our inputs and outputs. Feed it into
  1436. our generic decompression function. */
  1437. frameSources.frames = framePointers;
  1438. frameSources.framesSize = frameCount;
  1439. frameSources.compressedSize = totalInputSize;
  1440. result = decompress_from_framesources(self, &frameSources, threads);
  1441. finally:
  1442. if (frameSizes.buf) {
  1443. PyBuffer_Release(&frameSizes);
  1444. }
  1445. PyMem_Free(framePointers);
  1446. if (frameBuffers) {
  1447. for (i = 0; i < frameCount; i++) {
  1448. PyBuffer_Release(&frameBuffers[i]);
  1449. }
  1450. PyMem_Free(frameBuffers);
  1451. }
  1452. return result;
  1453. }
  1454. static PyMethodDef Decompressor_methods[] = {
  1455. { "copy_stream", (PyCFunction)Decompressor_copy_stream, METH_VARARGS | METH_KEYWORDS,
  1456. Decompressor_copy_stream__doc__ },
  1457. { "decompress", (PyCFunction)Decompressor_decompress, METH_VARARGS | METH_KEYWORDS,
  1458. Decompressor_decompress__doc__ },
  1459. { "decompressobj", (PyCFunction)Decompressor_decompressobj, METH_VARARGS | METH_KEYWORDS,
  1460. Decompressor_decompressobj__doc__ },
  1461. { "read_to_iter", (PyCFunction)Decompressor_read_to_iter, METH_VARARGS | METH_KEYWORDS,
  1462. Decompressor_read_to_iter__doc__ },
  1463. /* TODO Remove deprecated API */
  1464. { "read_from", (PyCFunction)Decompressor_read_to_iter, METH_VARARGS | METH_KEYWORDS,
  1465. Decompressor_read_to_iter__doc__ },
  1466. { "stream_reader", (PyCFunction)Decompressor_stream_reader,
  1467. METH_VARARGS | METH_KEYWORDS, Decompressor_stream_reader__doc__ },
  1468. { "stream_writer", (PyCFunction)Decompressor_stream_writer, METH_VARARGS | METH_KEYWORDS,
  1469. Decompressor_stream_writer__doc__ },
  1470. /* TODO remove deprecated API */
  1471. { "write_to", (PyCFunction)Decompressor_stream_writer, METH_VARARGS | METH_KEYWORDS,
  1472. Decompressor_stream_writer__doc__ },
  1473. { "decompress_content_dict_chain", (PyCFunction)Decompressor_decompress_content_dict_chain,
  1474. METH_VARARGS | METH_KEYWORDS, Decompressor_decompress_content_dict_chain__doc__ },
  1475. { "multi_decompress_to_buffer", (PyCFunction)Decompressor_multi_decompress_to_buffer,
  1476. METH_VARARGS | METH_KEYWORDS, Decompressor_multi_decompress_to_buffer__doc__ },
  1477. { "memory_size", (PyCFunction)Decompressor_memory_size, METH_NOARGS,
  1478. Decompressor_memory_size__doc__ },
  1479. { NULL, NULL }
  1480. };
  1481. PyTypeObject ZstdDecompressorType = {
  1482. PyVarObject_HEAD_INIT(NULL, 0)
  1483. "zstd.ZstdDecompressor", /* tp_name */
  1484. sizeof(ZstdDecompressor), /* tp_basicsize */
  1485. 0, /* tp_itemsize */
  1486. (destructor)Decompressor_dealloc, /* tp_dealloc */
  1487. 0, /* tp_print */
  1488. 0, /* tp_getattr */
  1489. 0, /* tp_setattr */
  1490. 0, /* tp_compare */
  1491. 0, /* tp_repr */
  1492. 0, /* tp_as_number */
  1493. 0, /* tp_as_sequence */
  1494. 0, /* tp_as_mapping */
  1495. 0, /* tp_hash */
  1496. 0, /* tp_call */
  1497. 0, /* tp_str */
  1498. 0, /* tp_getattro */
  1499. 0, /* tp_setattro */
  1500. 0, /* tp_as_buffer */
  1501. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1502. Decompressor__doc__, /* tp_doc */
  1503. 0, /* tp_traverse */
  1504. 0, /* tp_clear */
  1505. 0, /* tp_richcompare */
  1506. 0, /* tp_weaklistoffset */
  1507. 0, /* tp_iter */
  1508. 0, /* tp_iternext */
  1509. Decompressor_methods, /* tp_methods */
  1510. 0, /* tp_members */
  1511. 0, /* tp_getset */
  1512. 0, /* tp_base */
  1513. 0, /* tp_dict */
  1514. 0, /* tp_descr_get */
  1515. 0, /* tp_descr_set */
  1516. 0, /* tp_dictoffset */
  1517. (initproc)Decompressor_init, /* tp_init */
  1518. 0, /* tp_alloc */
  1519. PyType_GenericNew, /* tp_new */
  1520. };
  1521. void decompressor_module_init(PyObject* mod) {
  1522. Py_TYPE(&ZstdDecompressorType) = &PyType_Type;
  1523. if (PyType_Ready(&ZstdDecompressorType) < 0) {
  1524. return;
  1525. }
  1526. Py_INCREF((PyObject*)&ZstdDecompressorType);
  1527. PyModule_AddObject(mod, "ZstdDecompressor",
  1528. (PyObject*)&ZstdDecompressorType);
  1529. }