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