#include "error_to_string.h"
#include "platform_errors.h"
#include "src/__support/CPP/span.h"
#include "src/__support/CPP/string_view.h"
#include "src/__support/CPP/stringstream.h"
#include "src/__support/StringUtil/message_mapper.h"
#include "src/__support/integer_to_string.h"
#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
#include <stddef.h>
namespace LIBC_NAMESPACE_DECL {
namespace internal {
constexpr size_t max_buff_size() {
constexpr size_t unknown_str_len = sizeof("Unknown error");
return (unknown_str_len + 1 + IntegerToString<int>::buffer_size()) *
sizeof(char);
}
constexpr size_t ERR_BUFFER_SIZE = max_buff_size();
LIBC_THREAD_LOCAL char error_buffer[ERR_BUFFER_SIZE];
constexpr size_t TOTAL_STR_LEN = total_str_len(PLATFORM_ERRORS);
constexpr size_t ERR_ARRAY_SIZE = max_key_val(PLATFORM_ERRORS) + 1;
constexpr MessageMapper<ERR_ARRAY_SIZE, TOTAL_STR_LEN>
error_mapper(PLATFORM_ERRORS);
cpp::string_view build_error_string(int err_num, cpp::span<char> buffer) {
if (buffer.size() <
(sizeof("Unknown error") + 1 + IntegerToString<int>::buffer_size()))
return const_cast<char *>("Unknown error");
cpp::StringStream buffer_stream(
{const_cast<char *>(buffer.data()), buffer.size()});
buffer_stream << "Unknown error" << ' ' << err_num << '\0';
return buffer_stream.str();
}
}
cpp::string_view get_error_string(int err_num) {
return get_error_string(err_num,
{internal::error_buffer, internal::ERR_BUFFER_SIZE});
}
cpp::string_view get_error_string(int err_num, cpp::span<char> buffer) {
auto opt_str = internal::error_mapper.get_str(err_num);
if (opt_str)
return *opt_str;
else
return internal::build_error_string(err_num, buffer);
}
}