BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
BmnReaderCacheManager.h
Go to the documentation of this file.
1#pragma once
2#ifndef BmnReaderCacheManager_h
3#define BmnReaderCacheManager_h
4
5// headers from this target
7// std:: headers
8#include <array>
9#include <cassert>
10#include <cstring>
11#include <filesystem>
12#include <fstream>
13// FairLogger headers
14#include <fairlogger/Logger.h>
15
16// 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
17// ================== BmnReaderCacheManager class ==================
18// 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
19
20/*
21 * This class should be used for easier management of various compression formats. That is, it
22 * handles input-file reads, keeps the needed data in cache for optimal (fast) reads in subsequent
23 * read calls while still relying on an owner class that inherits from `BmnIArchiveLibRead`.
24 */
25template<size_t SourceBufferSize = 32 * 1024ull, size_t DestinationBufferSize = 64 * 1024ull>
27{
28 static_assert(SourceBufferSize >= 32 * 1024ull && DestinationBufferSize >= 32 * 1024ull,
29 "Don't reduce buffer sizes too much as you will lose efficiency!");
30 static_assert(SourceBufferSize <= DestinationBufferSize,
31 "For uncompressing, uncompressed buffers are expected to be bigger than compressed buffers!");
32
33 public:
37 // We also don't want to copy the data
40 // removing move constructor/assignment as I'm using arrays, i.e., I don't want to jump all over the heap for no
41 // reason. One should use the class without any pointers (no need for them), while the owner class should be
42 // allocated on the heap
45
46 public:
47 // @return The number of bytes that are read from an input stream and fed into an underlying decompression system
48 [[nodiscard]] constexpr size_t GetSourceBufferSize() const noexcept;
49
50 // @return The number of bytes that are used for caching decompressed data - the data is used for fast reading
51 [[nodiscard]] constexpr size_t GetDestinationBufferSize() const noexcept;
52
53 // inline methods - based around a reading stream
54
55 [[nodiscard]] inline bool IsOpen() const noexcept;
56 [[nodiscard]] inline bool IsGood() const noexcept;
57 [[nodiscard]] inline bool IsEOF() const noexcept;
58 [[nodiscard]] inline int64_t Tell() noexcept;
59 inline void Clear();
60 // inline methods - some getters
61
62 [[nodiscard]] inline size_t GetCurrentOutputBufferPosition() const noexcept;
63 [[nodiscard]] inline size_t GetTotalOutputBufferFilledSize() const noexcept;
64 [[nodiscard]] inline size_t GetCurrentInputBufferPosition() const noexcept;
65 [[nodiscard]] inline size_t GetTotalInputBufferFilledSize() const noexcept;
66
67 public:
68 /*
69 * A method for opening an input stream from a compressed file.
70 * @param inputFile A path to the file that should be opened
71 * @param inputOpenMode Appropriate std::ios::openmode flags related to the reading (mostly, those should be
72 * `std::ios::in | std::ios::binary`)
73 */
74 void Open(const std::filesystem::path& inputFile, const std::ios::openmode inputOpenMode);
75
76 /*
77 * Safely closes a stream and removes unnecessary data so a new stream can be opened
78 */
79 void Close();
80
81 /*
82 * Handles reading of a next data chunk. Before calling using decompression calls, it will forward
83 * all unused data from the caching buffer.
84 * @param dataToFill A pointer to the data that should be filled in this method
85 * @param sizeToFill A number of bytes that should be filled in `dataToFill`
86 * @return A number of successfully filled bytes. If `sizeOfFill != returnSize`, the stream either reached the end,
87 * or a fatal error has occurred
88 */
89 [[nodiscard]] int64_t Read(void* dataToFill, int64_t sizeToFill);
90
91 /*
92 * Seeks a new reading points in an input file
93 * @param value A new reading point from an input file
94 * @warning While using archives, it can be dangerous trying to access file bytes randomly
95 */
96 void Seek(int64_t value);
97
98 /*
99 * A method that helps to move to a specific place in the reading file. This method must move
100 * the output stream forward. If backward move is needed, the owner should handle it, mostly by
101 * reopening the stream.
102 * @param value A value in an output (decompressed) stream to which one wants to jump
103 * @warning This method may not be efficient and it would be best if jumping is not used while
104 * decompressing. Still, it can be used efficiently if one has compressed data with proper tactics
105 */
106 void MoveToDecompressingLocation(int64_t value);
107
108 private:
109 /*
110 * Handles extraction and decompression of the next data chunk. The decompression should be performed by
111 * the owner
112 */
113 [[nodiscard]] bool UncompressNextDataChunk();
114
115 private:
116 std::array<uint8_t, SourceBufferSize> fArchiveSourceBuffer;
117 std::array<uint8_t, DestinationBufferSize> fArchiveOutputBuffer;
119 std::ifstream fFileBeingProcessed;
125 /*
126 * keeping it as signed so `0 - 1` wouldn't go to
127 * `std::numeric_limits<size_t>::max()` and cause some unexpected error
128 */
130};
131
132// 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
133// ================== BmnReaderCacheManager inline methods ==================
134// 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
135
136template<size_t src, size_t dst>
137constexpr size_t BmnReaderCacheManager<src, dst>::GetSourceBufferSize() const noexcept
138{
139 return src;
140}
141
142template<size_t src, size_t dst>
144{
145 return dst;
146}
147
148template<size_t src, size_t dst>
150{
151 return fFileBeingProcessed.is_open();
152}
153
154template<size_t src, size_t dst>
156{
157 return fFileBeingProcessed.good();
158}
159
160template<size_t src, size_t dst>
167
168template<size_t src, size_t dst>
170{
171 if (!fFileBeingProcessed.is_open() || !fFileBeingProcessed.good())
172 return -1ll;
173 // tellg is not const o.O
175}
176
177template<size_t src, size_t dst>
182
183template<size_t src, size_t dst>
188
189template<size_t src, size_t dst>
194
195template<size_t src, size_t dst>
200
201template<size_t src, size_t dst>
206
207// 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
208// ================== BmnReaderCacheManager public methods ==================
209// 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
210
211template<size_t src, size_t dst>
224
225template<size_t src, size_t dst>
226void BmnReaderCacheManager<src, dst>::Open(const std::filesystem::path& inputFile,
227 const std::ios::openmode inputOpenMode)
228{
229 try {
230 if (!std::filesystem::exists(inputFile) || !std::filesystem::is_regular_file(inputFile)) {
231 LOG(error) << "`BmnReaderCacheManager<src, dst>::Open` expects an actual existing file! Passed path: "
232 << inputFile << '\n';
233 return;
234 }
235 if (fFileBeingProcessed.is_open()) {
236 LOG(warning) << "You are about to open a new file in `BmnReaderCacheManager<src, dst>::Open` while the "
237 "previous one wasn't closed - implicitly calling `Close()`!\n";
238 }
239 Close();
240 fTotalSizeOfAnInputFile = std::filesystem::file_size(inputFile);
242 } catch (const std::bad_alloc& errorDescription) {
243 LOG(error) << "Filesystem failure! Reason: " << errorDescription.what() << '\n';
244 return;
245 } catch (const std::filesystem::filesystem_error& errorDescription) {
246 LOG(error) << "Filesystem failure! Reason: " << errorDescription.what() << '\n';
247 return;
248 }
249 fFileBeingProcessed.open(inputFile, inputOpenMode);
250}
251
252template<size_t src, size_t dst>
265
266template<size_t tSrcSize, size_t tDstSize>
267int64_t BmnReaderCacheManager<tSrcSize, tDstSize>::Read(void* dataToFill, int64_t sizeToFill)
268{
269 if (!fFileBeingProcessed.is_open()) {
270 LOG(error) << "Calling `BmnReaderCacheManager::Read` while the input file is not ready for it!\n";
271 return 0ll;
272 }
273 // As we work with decompression here, we won't be able to know how many raw bytes will be obtained
274 // from N compressed bytes (even if we knew the compression ratio, it'd still be just an average).
275 // Thus, no matter what, we will be always reading the data into the output buffer, and only then
276 // copy them into `dataToFill`
277 if (sizeToFill <= 0ll) {
278 LOG(error) << "Calling `BmnReaderCacheManager::Read` with `sizeToFill < 0`!\n";
279 return 0ll;
280 }
281 size_t dataToFillOffset = 0ull;
282 auto fillTheBuffer = [this, &dataToFillOffset, dataToFill, &sizeToFill]() {
283 // we might encounter a few extra operations here for large `sizeToFill`, but it doesn't matter
285 size_t bytesToCopy = unreadBuffer > (size_t)sizeToFill ? (size_t)sizeToFill : unreadBuffer;
286 std::memcpy((uint8_t*)dataToFill + dataToFillOffset, fArchiveOutputBuffer.data() + fCurrentOutputBufferPosition,
287 bytesToCopy);
288 fCurrentOutputBufferPosition += bytesToCopy;
292 }
293 sizeToFill -= (int64_t)bytesToCopy;
294 dataToFillOffset += bytesToCopy;
295 };
297 fillTheBuffer();
298 while (sizeToFill > 0ll && !IsEOF()) {
299 // at this point we will either skip the loop as `sizeToFill == 0` or `fTotalOutputBufferFilledSize ==
300 // fCurrentOutputBufferPosition`
302 LOG(error) << "Encountered an error while uncompressing in `BmnReaderCacheManager::Read`... breaking "
303 "unhandled read!\nError reason: "
304 << fOwnerArchiveReference.GetLastUncompressErrorDescription() << '\n';
305 return 0ll;
306 }
307 // and we keep filling till we are done
308 fillTheBuffer();
309 }
310 return (int64_t)dataToFillOffset;
311}
312
313template<size_t src, size_t dst>
315{
316 assert(value >= 0ll);
317 if ((size_t)value >= fTotalSizeOfAnInputFile) {
318 LOG(warning) << "Cannot seek out of file scope!\n";
319 return;
320 }
321 fFileBeingProcessed.seekg(value);
327}
328
329template<size_t src, size_t dst>
331{
332 if (!fFileBeingProcessed.is_open()) {
333 LOG(warning) << "Calling `BmnReaderCacheManager::MoveToDecompressingLocation` while the input file is not "
334 "ready for it!\n";
335 return;
336 }
337 assert(value > 0ll);
338 assert(fTotalInputBufferFilledSize + (size_t)value >= fOwnerArchiveReference.GetNumberOfDecompressedBytes());
339 while (true) {
340 if ((size_t)value <= fOwnerArchiveReference.GetNumberOfDecompressedBytes()) {
342 fTotalOutputBufferFilledSize + value - fOwnerArchiveReference.GetNumberOfDecompressedBytes();
343 return;
344 }
345 if (IsEOF())
346 return;
348 return;
349 }
350}
351
352// 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 o
353// ================== BmnReaderCacheManager private methods ==================
354// 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 o
355
356template<size_t tSrcSize, size_t tDstSize>
358{
359 if (!fFileBeingProcessed.good()) {
360 // we can expect that different underlying libraries handle EOF differently, so we need to add
361 // `IsStreamInGoodState` as well
363 && !fOwnerArchiveReference.IsStreamInGoodState())
364 {
365 LOG(error) << "Calling `BmnReaderCacheManager::UncompressNextDataChunk` while the stream is not good!\n";
366 return false;
367 }
368 }
369 // Here we must be very carful as some libraries might not consume entire input buffer while uncompressing,
370 // i.e., the compressed data might be split into segments (packets). In that case, libraries might need entire
371 // segments or they won't process the data at all
372 bool shouldReadMoreStreamData = false;
374 // if we used only a small portion of the input buffer, there's no need to move it around the memory and load
375 // more... it would have reduced the code efficiency
378 {
379 shouldReadMoreStreamData = true;
380 // using memmove here as we might encounter some overlapping while it internally handles such cases if
381 // needed. if no overlapping, it will practically memcpy
383 std::memmove(fArchiveSourceBuffer.data(),
384 (uint8_t*)fArchiveSourceBuffer.data() + fCurrentInputBufferPosition, nextMax);
387 }
388 } else {
391 shouldReadMoreStreamData = true;
392 }
393 if (!fFileBeingProcessed.eof() && shouldReadMoreStreamData) {
394 // Now we read the raw data from the stream
395 fFileBeingProcessed.read(reinterpret_cast<char*>(fArchiveSourceBuffer.data()) + fTotalInputBufferFilledSize,
396 (int64_t)(tSrcSize - fTotalInputBufferFilledSize));
397 // std::ofstream internally checks the file size and stops reading when EOF is reached, even when we ask
398 // additional bytes -> `gcount()`
401 }
402 size_t noOfUsedBytes = 0ull;
403 BmnFileStreamResults decompressStatus =
407 fCurrentInputBufferPosition += noOfUsedBytes;
408 if (decompressStatus == BmnFileStreamResults::Success || decompressStatus == BmnFileStreamResults::ReachedEOF) {
409 return true;
410 }
411 LOG(error) << "Encountered an error while uncompressing in `BmnReaderCacheManager::Read`... breaking unhandled "
412 "read!\nError reason: "
413 << fOwnerArchiveReference.GetLastUncompressErrorDescription() << '\n';
414 return false;
415}
416
417#endif // BmnReaderCacheManager_h
BmnReaderCacheManager()=delete
BmnReaderCacheManager(const BmnReaderCacheManager &)=delete
BmnReaderCacheManager & operator==(BmnReaderCacheManager &&)=delete
BmnIArchiveLibRead & fOwnerArchiveReference
void Open(const std::filesystem::path &inputFile, const std::ios::openmode inputOpenMode)
constexpr size_t GetSourceBufferSize() const noexcept
BmnReaderCacheManager & operator=(const BmnReaderCacheManager &)=delete
BmnReaderCacheManager(BmnReaderCacheManager &&)=delete
std::array< uint8_t, SourceBufferSize > fArchiveSourceBuffer
int64_t Read(void *dataToFill, int64_t sizeToFill)
~BmnReaderCacheManager()=default
std::array< uint8_t, DestinationBufferSize > fArchiveOutputBuffer