summaryrefslogtreecommitdiff
path: root/source/fud_assert.cpp
blob: 749aa6bf13c50ea99941e44eb0fa27ad2b0b60cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "fud_assert.hpp"

#include "fud_array.hpp"
#include "fud_string_view.hpp"

#include <climits>
#include <cstdio>
#include <format>
#include <stdexcept>

namespace fud {

[[noreturn]] void assertFail(const char* assertion, const std::source_location sourceLocation)
{
    constexpr size_t MAX_FILE_CHARS = 256;
    constexpr size_t MAX_FUNCTION_CHARS = 256;
    constexpr size_t BITS_PER_OCTAL = 3;
    constexpr auto MAX_LINE_CHARS = BITS_PER_OCTAL * sizeof(decltype(sourceLocation.line())) + 3;
    constexpr size_t MAX_ASSERT_CHARS = 512 - MAX_LINE_CHARS;
    constexpr size_t ASSERT_MSG_SIZE = MAX_FILE_CHARS + MAX_LINE_CHARS + MAX_FUNCTION_CHARS + MAX_ASSERT_CHARS;

    auto lengthResult = cStringLength(sourceLocation.file_name());
    size_t filenameLength = 0;
    auto badLength = lengthResult < 1 || lengthResult > SSIZE_MAX;
    if (!badLength) {
        filenameLength = static_cast<size_t>(lengthResult);
    }
    const char* filename = nullptr;
    if (badLength) {
        constexpr const char invalidFile[] = "INVALID FILE";
        static_assert(sizeof(invalidFile) < MAX_FILE_CHARS);
        filenameLength = sizeof(invalidFile);
        filename = invalidFile;
    } else if (filenameLength > MAX_LINE_CHARS) {
        filename = sourceLocation.file_name() + filenameLength - MAX_LINE_CHARS;
        filenameLength = MAX_FILE_CHARS;
    }

    Array<char, ASSERT_MSG_SIZE> buffer{};
    // clang-format off
    static_cast<void>(std::format_to_n(
        buffer.data(), buffer.size() - 1U,
        "{:.{}s}:{}: {:.{}s}: Assertion `{:.{}s}` failed\n",
        filename, filenameLength,
        sourceLocation.line(),
        sourceLocation.function_name(), MAX_FUNCTION_CHARS,
        assertion, MAX_ASSERT_CHARS));
    // clang-format on
    buffer[buffer.size() - 1] = '\0';
    fputs(buffer.data(), stderr);
    std::abort();
}

} // namespace fud