MCPcopy Create free account
hub / github.com/crosspoint-reader/crosspoint-reader / readFileToMemory

Method readFileToMemory

lib/ZipFile/ZipFile.cpp:367–439  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

365}
366
367uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const bool trailingNullByte) {
368 const ScopedOpenClose zip{*this};
369 if (!zip) return nullptr;
370
371 FileStatSlim fileStat = {};
372 if (!loadFileStatSlim(filename, &fileStat)) return nullptr;
373
374 const long fileOffset = getDataOffset(fileStat);
375 if (fileOffset < 0) return nullptr;
376
377 file.seek(fileOffset);
378
379 const auto deflatedDataSize = fileStat.compressedSize;
380 const auto inflatedDataSize = fileStat.uncompressedSize;
381 const auto dataSize = trailingNullByte ? inflatedDataSize + 1 : inflatedDataSize;
382 const auto data = static_cast<uint8_t*>(malloc(dataSize));
383 if (data == nullptr) {
384 LOG_ERR("ZIP", "Failed to allocate memory for output buffer (%zu bytes)", dataSize);
385 return nullptr;
386 }
387
388 if (fileStat.method == ZIP_METHOD_STORED) {
389 // no deflation, just read content
390 const size_t dataRead = file.read(data, inflatedDataSize);
391
392 if (dataRead != inflatedDataSize) {
393 LOG_ERR("ZIP", "Failed to read data");
394 free(data);
395 return nullptr;
396 }
397
398 // Continue out of block with data set
399 } else if (fileStat.method == ZIP_METHOD_DEFLATED) {
400 auto* fileReadBuffer = static_cast<uint8_t*>(malloc(1024));
401 if (!fileReadBuffer) {
402 LOG_ERR("ZIP", "Failed to allocate memory for zip file read buffer");
403 free(data);
404 return nullptr;
405 }
406
407 ZipInflateCtx ctx;
408 ctx.file = &file;
409 ctx.fileRemaining = deflatedDataSize;
410 ctx.readBuf = fileReadBuffer;
411 ctx.readBufSize = 1024;
412
413 if (!ctx.reader.init(true)) {
414 LOG_ERR("ZIP", "Failed to init inflate reader");
415 free(fileReadBuffer);
416 free(data);
417 return nullptr;
418 }
419 ctx.reader.setReadCallback(zipReadCallback);
420
421 if (!ctx.reader.read(data, inflatedDataSize)) {
422 LOG_ERR("ZIP", "Failed to inflate file");
423 free(fileReadBuffer);
424 free(data);

Callers 1

Calls 4

seekMethod · 0.80
setReadCallbackMethod · 0.80
readMethod · 0.45
initMethod · 0.45

Tested by

no test coverage detected