Line | Count | Source (jump to first uncovered line) |
1 | | #include <fstream> |
2 | | |
3 | | #include "zserio/CppRuntimeException.h" |
4 | | #include "zserio/FileUtil.h" |
5 | | #include "zserio/StringView.h" |
6 | | |
7 | | namespace zserio |
8 | | { |
9 | | |
10 | | void writeBufferToFile(const uint8_t* buffer, size_t bitSize, BitsTag, const std::string& fileName) |
11 | 8 | { |
12 | 8 | std::ofstream stream(fileName.c_str(), std::ofstream::binary | std::ofstream::trunc); |
13 | 8 | if (!stream) |
14 | 1 | { |
15 | 1 | throw CppRuntimeException("writeBufferToFile: Failed to open '") << fileName << "' for writing!"; |
16 | 1 | } |
17 | | |
18 | 7 | const size_t byteSize = (bitSize + 7) / 8; |
19 | 7 | if (!stream.write(reinterpret_cast<const char*>(buffer), static_cast<std::streamsize>(byteSize))) |
20 | 0 | { |
21 | 0 | throw CppRuntimeException("writeBufferToFile: Failed to write '") << fileName << "'!"; |
22 | 0 | } |
23 | 7 | } |
24 | | |
25 | | BitBuffer readBufferFromFile(const std::string& fileName) |
26 | 8 | { |
27 | 8 | std::ifstream stream(fileName.c_str(), std::ifstream::binary); |
28 | 8 | if (!stream) |
29 | 1 | { |
30 | 1 | throw CppRuntimeException("readBufferFromFile: Cannot open '") << fileName << "' for reading!"; |
31 | 1 | } |
32 | | |
33 | 7 | stream.seekg(0, stream.end); |
34 | 7 | const std::streampos fileSize = stream.tellg(); |
35 | 7 | stream.seekg(0); |
36 | | |
37 | 7 | if (static_cast<int>(fileSize) == -1) |
38 | 0 | { |
39 | 0 | throw CppRuntimeException("readBufferFromFile: Failed to get file size of '") << fileName << "'!"; |
40 | 0 | } |
41 | | |
42 | 7 | const size_t sizeLimit = std::numeric_limits<size_t>::max() / 8; |
43 | 7 | if (static_cast<uint64_t>(fileSize) > sizeLimit) |
44 | 0 | { |
45 | 0 | throw CppRuntimeException("readBufferFromFile: File size exceeds limit '") << sizeLimit << "'!"; |
46 | 0 | } |
47 | | |
48 | 7 | zserio::BitBuffer bitBuffer(static_cast<size_t>(fileSize) * 8); |
49 | 7 | if (!stream.read(reinterpret_cast<char*>(bitBuffer.getBuffer()), |
50 | 7 | static_cast<std::streamsize>(bitBuffer.getByteSize()))) |
51 | 0 | { |
52 | 0 | throw CppRuntimeException("readBufferFromFile: Failed to read '") << fileName << "'!"; |
53 | 0 | } |
54 | | |
55 | 7 | return bitBuffer; |
56 | 7 | } |
57 | | |
58 | | } // namespace zserio |