Coverage Report

Created: 2023-12-13 14:58

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