BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnFileReaderBZip3.cxx
Go to the documentation of this file.
1// headers from this target
3
4// std:: headers
5#include <cassert>
6#include <cstring>
7#include <filesystem>
8
9// the main BZip3 header
10#ifdef BMNCOMPRESSION_WITH_BZIP3
11#include <libbz3.h>
12#endif // BMNCOMPRESSION_WITH_BZIP3
13
14#ifdef BMNCOMPRESSION_WITH_BZIP3
15constexpr const char* co_bzip3MagicByte = "BZ3v1";
16constexpr uint32_t co_allowedMin = 65u * 1024u;
17constexpr uint32_t co_allowedMax = 511u * 1024u * 1024u;
18
19constexpr const char* co_failedToReadBZip3BlockHeaderMessage = "Failed to read a BZip3-block header!\n";
20constexpr const char* co_unexpectedSizeofBZip3BlockMessage =
21 "Unexpected size of a compressed/uncompressed BZip3 block detected!\n";
22constexpr const char* co_failedToReadCompressedBZip3BlockMessage = "Failed to read a BZip3-compressed block!\n";
23constexpr const char* co_uncompressingBZip3ErrorMessage =
24 "Encountered an error while uncompressing in `BmnFileReaderBZip3::Read`... breaking unhandled read!\nError "
25 "reason: ";
26#endif // BMNCOMPRESSION_WITH_BZIP3
27
28// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
29// ================== BmnFileReaderBZip3 public methods ==================
30// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
31
32BmnFileReaderBZip3::BmnFileReaderBZip3([[maybe_unused]] const std::filesystem::path& aFilePath)
33 : fBZip3Stream(nullptr)
34 , fCacheBuffer()
36 , fTotalFileSize(0ull)
38 , fNumberOfReadBytes(0ull)
42{
43#ifdef BMNCOMPRESSION_WITH_BZIP3
44 if (aFilePath.empty())
45 return;
46 Open(aFilePath);
47#endif // BMNCOMPRESSION_WITH_BZIP3
48}
49
54
55// ========== BmnIFileReader Interface ==========
56
57void BmnFileReaderBZip3::Open([[maybe_unused]] const std::filesystem::path& aFilePath)
58{
59#ifdef BMNCOMPRESSION_WITH_BZIP3
60 /*
61 While we actually don't need so many comments and checks here, we are still performing them just to ensure
62 one doesn't make an accidental mistake - it might be easier to catch it
63 */
64 if (fBZip3Stream) {
65 LOG(error)
66 << "BZip3 stream is already valid! If you want to open a new one, first close the old one and then open!\n";
67 return;
68 }
70 return;
71 std::error_code anErrorCode{};
72 fTotalFileSize = std::filesystem::file_size(aFilePath, anErrorCode);
73 if (anErrorCode != std::error_code{}) {
74 LOG(error) << "File system error while opening BZip3!\n";
75 return;
76 }
78 fFileBeingProcessed.open(aFilePath, std::ios::in | std::ios::binary);
79 if (!fFileBeingProcessed.is_open()) {
80 LOG(error) << "Failed to open a BZip3 file for reading!\n";
81 return;
82 }
83 // In doc/bzip3_format one can find some info about the bz3 format and what can be found in a standard file
84 char fileHeaderMetadata[9ull];
85 fFileBeingProcessed.read(fileHeaderMetadata, sizeof(fileHeaderMetadata));
86 std::string_view magicByteView{fileHeaderMetadata, std::strlen(co_bzip3MagicByte)};
87 uint32_t maxDecompressedBlock = *reinterpret_cast<uint32_t*>(fileHeaderMetadata + magicByteView.size());
88 if (fFileBeingProcessed.gcount() != sizeof(fileHeaderMetadata) || magicByteView != co_bzip3MagicByte
89 || maxDecompressedBlock < co_allowedMin || maxDecompressedBlock > co_allowedMax)
90 {
91 LOG(error) << "Corrupted BZip3-header data!\n";
92 fFileBeingProcessed.close();
93 return;
94 }
95 fRemainingBytesToRead -= sizeof(fileHeaderMetadata);
96 try {
97 fCacheBuffer.resize(bz3_bound((int32_t)maxDecompressedBlock), 0u);
98 } catch ([[maybe_unused]] const std::bad_alloc& aBadAlloc) {
99 LOG(error) << "Failed to allocate a cache buffer of a BZip3 reader!\n";
100 fFileBeingProcessed.close();
101 return;
102 }
103 fBZip3Stream = bz3_new(maxDecompressedBlock);
104 if (!fBZip3Stream) {
105 LOG(error) << "Failed to allocate BZip3 internal data!\n";
106 fFileBeingProcessed.close();
107 fCacheBuffer = std::vector<uint8_t>{};
108 return;
109 }
110#else // !BMNCOMPRESSION_WITH_BZIP3
111 throw std::runtime_error{"Trying to use BZip3 while BMN is not compiled with it!"};
112#endif // BMNCOMPRESSION_WITH_BZIP3
113}
114
116{
117#ifdef BMNCOMPRESSION_WITH_BZIP3
118 if (!fBZip3Stream) {
119 assert(!fFileBeingProcessed.is_open());
120 return;
121 }
122 assert(fFileBeingProcessed.is_open());
123 fFileBeingProcessed.close();
124 bz3_free(fBZip3Stream);
125 fBZip3Stream = nullptr;
126 fCacheBuffer = std::vector<uint8_t>{};
127 fNumberOfReadBytes = 0ull;
130 fTotalFileSize = 0ull;
131 fLastErrorCode = 0;
132#endif // BMNCOMPRESSION_WITH_BZIP3
133}
134
135int64_t BmnFileReaderBZip3::Read([[maybe_unused]] void* dataToFill, [[maybe_unused]] int64_t sizeToFill)
136{
137#ifdef BMNCOMPRESSION_WITH_BZIP3
138 if (!IsGood())
139 return 0ull;
140 if (!IsOpen()) {
141 LOG(error) << "Trying to read a BZip3 stream that's not open!\n";
142 return 0ll;
143 }
144 if (sizeToFill <= 0ll) {
145 LOG(error) << "Calling `BmnReaderCacheManager::Read` with `sizeToFill < 0`!\n";
146 return 0ll;
147 }
148 size_t dataToFillOffset = 0ull;
149 auto fillTheBuffer = [this, &dataToFillOffset, dataToFill, &sizeToFill]() {
151 const size_t bytesToCopy = unreadBuffer > (size_t)sizeToFill ? (size_t)sizeToFill : unreadBuffer;
152 std::memcpy((void*)((uint8_t*)dataToFill + dataToFillOffset),
153 (void*)(fCacheBuffer.data() + fCurrentIterCacheBufferOffset), bytesToCopy);
154 fCurrentIterCacheBufferOffset += bytesToCopy;
158 }
159 sizeToFill -= (int64_t)bytesToCopy;
160 dataToFillOffset += bytesToCopy;
161 };
163 fillTheBuffer();
164 while (sizeToFill > 0ll && !IsEOF()) {
166 return 0ll;
167 fillTheBuffer();
168 }
169 return (int64_t)dataToFillOffset;
170#else // !BMNCOMPRESSION_WITH_BZIP3
171 throw std::runtime_error{"Trying to use BZip3 while BMN is not compiled with it!"};
172#endif // BMNCOMPRESSION_WITH_BZIP3
173}
174
179
180void BmnFileReaderBZip3::Seek([[maybe_unused]] int64_t value)
181{
182#ifdef BMNCOMPRESSION_WITH_BZIP3
183 if (value < 0ll || value == Tell())
184 return;
185 if (!IsOpen()) {
186 LOG(warning) << "Before calling `BmnFileReaderBZip3::Seek` ensure to open the stream!\n";
187 return;
188 }
189 if (!IsGood()) {
190 LOG(warning) << "Before calling `BmnFileReaderBZip3::Seek` ensure to clear bad flags!\n";
191 return;
192 }
193 if ((size_t)value < (fNumberOfReadBytes - fNumberOfValidCacheBufferBytes)) {
194 fNumberOfReadBytes = 0ull;
198 fFileBeingProcessed.seekg(9ll);
199 }
200 while (true) {
201 if (IsEOF()) {
202 LOG(warning) << "Reached the BZip3 EOF while seeking...\n";
203 return;
204 }
205 if ((size_t)value <= fNumberOfReadBytes) {
207 return;
208 }
209 // first -> size of compressed block; second -> size of uncompressed (before compression) block
210 uint32_t blockMetadata[2ull];
211 // While these small reads are not super efficient, they are negligible compared to the time BZip3 takes to
212 // decompress. Thus, in this case they can be used, without worrying about every every single us/ms
213 fFileBeingProcessed.read((char*)blockMetadata, sizeof(blockMetadata));
214 if (fFileBeingProcessed.gcount() != sizeof(blockMetadata)) {
215 LOG(error) << co_failedToReadBZip3BlockHeaderMessage;
216 return;
217 }
218 fRemainingBytesToRead -= sizeof(blockMetadata);
219 if (fCacheBuffer.size() < blockMetadata[0ull] || fCacheBuffer.size() < blockMetadata[1ull]
220 || blockMetadata[0ull] == 0ull || blockMetadata[1ull] == 0ull)
221 {
222 LOG(error) << co_unexpectedSizeofBZip3BlockMessage;
223 return;
224 }
225 if ((size_t)value > fNumberOfReadBytes + blockMetadata[1ull]) {
226 fNumberOfReadBytes += blockMetadata[1ull];
227 fRemainingBytesToRead -= blockMetadata[0ull];
229 continue;
230 }
231 fFileBeingProcessed.read((char*)fCacheBuffer.data(), blockMetadata[0ull]);
232 if (fFileBeingProcessed.gcount() != blockMetadata[0ull]) {
233 LOG(error) << co_failedToReadCompressedBZip3BlockMessage;
234 return;
235 }
236 fRemainingBytesToRead -= blockMetadata[0ull];
237 size_t aDummyInt = 0ull;
238 size_t uncompressedSize = blockMetadata[1ull];
239 BmnFileStreamResults aResult = Uncompress(nullptr, blockMetadata[0ull], aDummyInt, (void*)fCacheBuffer.data(),
240 fCacheBuffer.size(), uncompressedSize);
242 LOG(error) << co_uncompressingBZip3ErrorMessage << bz3_strerror(fBZip3Stream) << '\n';
243 return;
244 }
245 }
246#else // !BMNCOMPRESSION_WITH_BZIP3
247 throw std::runtime_error{"Trying to use BZip3 while BMN is not compiled with it!"};
248#endif // BMNCOMPRESSION_WITH_BZIP3
249}
250
251bool BmnFileReaderBZip3::IsGood() const noexcept
252{
253#ifdef BMNCOMPRESSION_WITH_BZIP3
254 return fLastErrorCode == 0 && fFileBeingProcessed.good();
255#else // !BMNCOMPRESSION_WITH_BZIP3
256 return false;
257#endif // BMNCOMPRESSION_WITH_BZIP3
258}
259
264
270
271bool BmnFileReaderBZip3::IsOpen() const noexcept
272{
273 return fBZip3Stream && fFileBeingProcessed.is_open();
274}
275
280
281// ========== BmnIArchiveLib Interface ==========
282
284{
285#ifdef BMNCOMPRESSION_WITH_BZIP3
286 if (!fBZip3Stream)
287 std::string{};
288 const char* lastError = bz3_strerror(fBZip3Stream);
289 if (!lastError)
290 std::string{};
291 return std::string{lastError};
292#else // !BMNCOMPRESSION_WITH_BZIP3
293 return std::string{"BMN NOT BUILT WITH BZIP3"};
294#endif // BMNCOMPRESSION_WITH_BZIP3
295}
296
298{
299 return fNumberOfReadBytes;
300}
301
303{
304 return fBZip3Stream && fRemainingBytesToRead != 0ull;
305}
306
308{
309 // BZip3 doesn't change the state of the stream - at least I didn't notice anything of that kind
310 if (fBZip3Stream)
311 return true;
312 return false;
313}
314
315// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
316// ================== BmnFileReaderBZip3 protected methods ==================
317// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
318
319BmnFileStreamResults BmnFileReaderBZip3::Uncompress([[maybe_unused]] const void* source,
320 [[maybe_unused]] const size_t sourceTotalSize,
321 [[maybe_unused]] size_t& numberOfReadBytes,
322 [[maybe_unused]] void* output,
323 [[maybe_unused]] const size_t outputTotalSize,
324 [[maybe_unused]] size_t& numberOfSetOutputBytes)
325{
326#ifdef BMNCOMPRESSION_WITH_BZIP3
327 assert(fBZip3Stream);
328 assert(fLastErrorCode == 0);
329 int32_t noOfDecompressedBytes = bz3_decode_block(fBZip3Stream, fCacheBuffer.data(), outputTotalSize,
330 (int32_t)sourceTotalSize, (int32_t)numberOfSetOutputBytes);
331 if (noOfDecompressedBytes < 0) {
332 fLastErrorCode = noOfDecompressedBytes;
334 }
335 numberOfSetOutputBytes = noOfDecompressedBytes;
336 fNumberOfValidCacheBufferBytes = noOfDecompressedBytes;
337 fNumberOfReadBytes += noOfDecompressedBytes;
338 if (fRemainingBytesToRead == 0ull)
341#else // !BMNCOMPRESSION_WITH_BZIP3
342 throw std::runtime_error{"Trying to use BZip3 while BMN is not compiled with it!"};
343#endif // BMNCOMPRESSION_WITH_BZIP3
344}
345
346// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
347// ================== BmnFileReaderBZip3 private methods ==================
348// o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
349
351{
352#ifdef BMNCOMPRESSION_WITH_BZIP3
354 // first -> size of compressed block; second -> size of uncompressed (before compression) block
355 uint32_t blockMetadata[2ull];
356 // While these small reads are not super efficient, they are negligible compared to the time BZip3 takes to
357 // decompress. Thus, in this case they can be used, without worrying about every every single us/ms
358 fFileBeingProcessed.read((char*)blockMetadata, sizeof(blockMetadata));
359 if (fFileBeingProcessed.gcount() != sizeof(blockMetadata)) {
360 LOG(error) << co_failedToReadBZip3BlockHeaderMessage;
361 return false;
362 }
363 fRemainingBytesToRead -= sizeof(blockMetadata);
364 if (fCacheBuffer.size() < blockMetadata[0ull] || fCacheBuffer.size() < blockMetadata[1ull]
365 || blockMetadata[0ull] == 0ull || blockMetadata[1ull] == 0ull)
366 {
367 LOG(error) << co_unexpectedSizeofBZip3BlockMessage;
368 return false;
369 }
370 fFileBeingProcessed.read((char*)fCacheBuffer.data(), blockMetadata[0ull]);
371 if (fFileBeingProcessed.gcount() != blockMetadata[0ull]) {
372 LOG(error) << co_failedToReadCompressedBZip3BlockMessage;
373 return false;
374 }
375 fRemainingBytesToRead -= blockMetadata[0ull];
376 size_t aDummyInt = 0ull;
377 size_t uncompressedSize = blockMetadata[1ull];
378 BmnFileStreamResults aResult = Uncompress(nullptr, blockMetadata[0ull], aDummyInt, (void*)fCacheBuffer.data(),
379 fCacheBuffer.size(), uncompressedSize);
381 LOG(error) << co_uncompressingBZip3ErrorMessage << bz3_strerror(fBZip3Stream) << '\n';
382 return false;
383 }
384 return true;
385#else // !BMNCOMPRESSION_WITH_BZIP3
386 return false;
387#endif // BMNCOMPRESSION_WITH_BZIP3
388}
std::ifstream fFileBeingProcessed
virtual bool IsGood() const noexcept override
virtual std::string GetLastUncompressErrorDescription() const override
virtual int64_t Read(void *dataToFill, int64_t sizeToFill) override
std::vector< uint8_t > fCacheBuffer
virtual void ClearStateFlags() override
BmnFileReaderBZip3(const std::filesystem::path &aFilePath="")
virtual BmnFileType GetFileType() const noexcept override
virtual void Close() noexcept override
virtual void Open(const std::filesystem::path &aFilePath) override
virtual ~BmnFileReaderBZip3() override
virtual bool HasReachedTheEndOfStream() const noexcept override
virtual bool IsStreamInGoodState() const noexcept override
virtual size_t GetNumberOfDecompressedBytes() const noexcept override
virtual int64_t Tell() const noexcept override
virtual bool IsEOF() const noexcept override
virtual void Seek(int64_t value) override
virtual BmnFileStreamResults Uncompress(const void *source, const size_t sourceTotalSize, size_t &numberOfReadBytes, void *output, const size_t outputTotalSize, size_t &numberOfSetOutputBytes) override
virtual bool IsOpen() const noexcept override
bool PerformStandardChecksBeforeOpening(const std::filesystem::path &aFilePath) const noexcept