Skip to content

Commit

Permalink
refactor(serialize): improve exception message
Browse files Browse the repository at this point in the history
  • Loading branch information
RimuruChan committed Nov 22, 2023
1 parent e943d16 commit a47a743
Show file tree
Hide file tree
Showing 55 changed files with 806 additions and 290 deletions.
2 changes: 1 addition & 1 deletion .clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ AlignConsecutiveBitFields:
AcrossEmptyLines: false
AcrossComments: false
AllowShortLambdasOnASingleLine: All
AllowShortBlocksOnASingleLine: Always
AllowShortBlocksOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
Expand Down
8 changes: 6 additions & 2 deletions src/ll/api/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,12 @@ inline bool loadConfig(T& config, std::string_view path, bool overwriteAfterFail
} else {
res = false;
}
} catch (...) { res = false; }
if (!res && overwriteAfterFail) { saveConfig<T, J>(config, path); }
} catch (...) {
res = false;
}
if (!res && overwriteAfterFail) {
saveConfig<T, J>(config, path);
}
return res;
}

Expand Down
24 changes: 13 additions & 11 deletions src/ll/api/Logger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ void Logger::OutputStream::print(std::string_view s) const noexcept {
applyTextStyle(style[2], fmt::format(fmt::runtime(consoleFormat[3]), logger->title)),
applyTextStyle(style[3], fmt::format(fmt::runtime(consoleFormat[4]), replaceMcToAnsiCode(s)))
);
if (!ll::globalConfig.logger.colorLog) { str = removeEscapeCode(str); }
if (!ll::globalConfig.logger.colorLog) {
str = removeEscapeCode(str);
}
fmt::print("{}\r\n", str);
}
if (logger->getFile().is_open() && checkLogLevel(logger->fileLevel, level)) {
Expand Down Expand Up @@ -113,8 +115,7 @@ Logger::Logger(std::string_view title)
fmt::fg(fmt::color::light_sea_green),
{},
{},
}
}),
}}),
warn(OutputStream{
*this,
"WARN",
Expand All @@ -124,8 +125,7 @@ Logger::Logger(std::string_view title)
fmt::fg(fmt::terminal_color::bright_yellow),
fmt::fg(fmt::terminal_color::bright_yellow),
fmt::fg(fmt::terminal_color::bright_yellow) | fmt::emphasis::bold,
}
}),
}}),
error(OutputStream{
*this,
"ERROR",
Expand All @@ -135,8 +135,7 @@ Logger::Logger(std::string_view title)
fmt::fg(fmt::terminal_color::bright_red),
fmt::fg(fmt::terminal_color::bright_red),
fmt::fg(fmt::terminal_color::bright_red) | fmt::emphasis::bold,
}
}),
}}),
fatal(OutputStream{
*this,
"FATAL",
Expand All @@ -146,8 +145,7 @@ Logger::Logger(std::string_view title)
fmt::fg(fmt::color::red),
fmt::fg(fmt::color::red),
fmt::fg(fmt::color::red) | fmt::emphasis::bold,
}
}) {}
}}) {}

void Logger::resetFile() {
if (ofs) {
Expand All @@ -159,7 +157,9 @@ void Logger::resetFile() {

bool Logger::setFile(std::string const& logFile, bool appendMode) {
resetFile();
if (logFile.empty()) { return true; }
if (logFile.empty()) {
return true;
}

std::error_code ec;
std::filesystem::create_directories(file_utils::u8path(logFile).remove_filename(), ec);
Expand All @@ -169,7 +169,9 @@ bool Logger::setFile(std::string const& logFile, bool appendMode) {

bool Logger::setDefaultFile(std::string const& logFile, bool appendMode) {
if (logFile.empty()) {
if (defaultFile.is_open()) { defaultFile.close(); }
if (defaultFile.is_open()) {
defaultFile.close();
}
return true;
}

Expand Down
4 changes: 3 additions & 1 deletion src/ll/api/Logger.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ class Logger {
LLAPI static void setDefaultPlayerOutputFunc(PlayerOutputFunc const& func) { defaultPlayerOutputCallback = func; }

std::ofstream& getFile() {
if (ofs) { return ofs.value(); }
if (ofs) {
return ofs.value();
}
return defaultFile;
}

Expand Down
12 changes: 9 additions & 3 deletions src/ll/api/base/Base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ inline size_t getEncodeLength(std::string const& str) { return getEncodeLength(s
inline size_t getDecodeLength(std::string const& in) {
uchar count = 0;
size_t input_size = in.size();
for (auto it = in.rbegin(); *it == '='; ++it) { ++count; }
for (auto it = in.rbegin(); *it == '='; ++it) {
++count;
}
input_size -= count; // remove padding size
count = 0; // reset padding counter
while (input_size % 4) { // redo padding
Expand Down Expand Up @@ -52,10 +54,14 @@ inline std::string encode(std::string const& text_input) {
}
}

if (j > -6) { result += base64Table[((i << 8) >> (j + 8)) & 0x3F]; }
if (j > -6) {
result += base64Table[((i << 8) >> (j + 8)) & 0x3F];
}

// padding
while (result.size() % 4) { result.push_back('='); }
while (result.size() % 4) {
result.push_back('=');
}

return result;
}
Expand Down
34 changes: 25 additions & 9 deletions src/ll/api/base/ErrorInfo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ struct u8system_category : public std::_System_error_category {
const std::_System_error_message msg(static_cast<ulong>(errCode));
if (msg._Length) {
std::string res{string_utils::str2str({msg._Str, msg._Length})};
if (res.ends_with('\n')) { res.pop_back(); }
if (res.ends_with('\r')) { res.pop_back(); }
if (res.ends_with('\n')) {
res.pop_back();
}
if (res.ends_with('\r')) {
res.pop_back();
}
return string_utils::replaceAll(res, "\r\n", ", ");
}
return "unknown error";
Expand Down Expand Up @@ -70,8 +74,12 @@ struct ntstatus_category : public std::error_category {
if (size) {
std::string res{string_utils::wstr2str({msg, size})};
LocalFree(msg);
if (res.ends_with('\n')) { res.pop_back(); }
if (res.ends_with('\r')) { res.pop_back(); }
if (res.ends_with('\n')) {
res.pop_back();
}
if (res.ends_with('\r')) {
res.pop_back();
}
return string_utils::replaceAll(res, "\r\n", ", ");
}
return "unknown error";
Expand Down Expand Up @@ -162,13 +170,17 @@ static std::exception_ptr getNested(T const& e) {

if constexpr (can_use_dynamic_cast) {
const auto n = dynamic_cast<std::nested_exception const*>(std::addressof(e));
if (n) { return n->nested_ptr(); }
if (n) {
return n->nested_ptr();
}
}
return nullptr;
}

std::string makeExceptionString(std::exception_ptr ePtr) {
if (!ePtr) { throw std::bad_exception(); }
if (!ePtr) {
throw std::bad_exception();
}

std::string res;

Expand All @@ -191,7 +203,7 @@ std::string makeExceptionString(std::exception_ptr ePtr) {
}
auto expTypeName = exc.getNumCatchableTypes() > 0 ? exc.getTypeInfo(0)->name() : "unknown exception";
if (expTypeName == typeid(seh_exception).name()) {
res += fmt::format("Translated Seh Exception, from <{}>:\n", handleName);
res += fmt::format("Seh Exception, from <{}>:\n", handleName);
} else {
res += fmt::format(
"C++ Exception: {}, from <{}>:\n",
Expand All @@ -218,7 +230,9 @@ std::string makeExceptionString(std::exception_ptr ePtr) {
} catch (const std::exception& e) {
res += string_utils::tou8str(e.what());
ePtr = getNested(e);
} catch (const std::string& e) { res += string_utils::tou8str(e); } catch (char const* e) {
} catch (const std::string& e) {
res += string_utils::tou8str(e);
} catch (char const* e) {
res += string_utils::tou8str(e);
} catch (...) {
auto unkExc = current_exception();
Expand All @@ -245,7 +259,9 @@ void printCurrentException(optional_ref<ll::Logger> l, std::exception_ptr const&
auto& rlogger = l.value_or(logger);
try {
auto res = makeExceptionString(e);
for (auto& sv : string_utils::splitByPattern(res, "\n")) { rlogger.error(sv); }
for (auto& sv : string_utils::splitByPattern(res, "\n")) {
rlogger.error(sv);
}
return;
} catch (...) {}
rlogger.error("unknown error");
Expand Down
16 changes: 12 additions & 4 deletions src/ll/api/base/KeyValueDB.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ class KeyValueDB::KeyValueDBImpl {
options.reuse_logs = true; // @warning: experimental
options.create_if_missing = create;

if (cacheSize) { options.block_cache = leveldb::NewLRUCache(cacheSize); }
if (filterBit) { options.filter_policy = leveldb::NewBloomFilterPolicy(filterBit); }
if (cacheSize) {
options.block_cache = leveldb::NewLRUCache(cacheSize);
}
if (filterBit) {
options.filter_policy = leveldb::NewBloomFilterPolicy(filterBit);
}

leveldb::DB* database = nullptr;
status = leveldb::DB::Open(options, path, &database);
Expand All @@ -52,7 +56,9 @@ class KeyValueDB::KeyValueDBImpl {
[[nodiscard]] std::optional<std::string> get(std::string_view key) const {
std::string result;
auto s = db->Get(readOptions, leveldb::Slice(key.data(), key.size()), &result);
if (!s.ok()) { return std::nullopt; }
if (!s.ok()) {
return std::nullopt;
}
return result;
}

Expand All @@ -79,7 +85,9 @@ class KeyValueDB::KeyValueDBImpl {
for (it->SeekToFirst(); it->Valid(); it->Next()) {
auto k = it->key();
auto v = it->value();
if (!fn({k.data(), k.size()}, {v.data(), v.size()})) { break; }
if (!fn({k.data(), k.size()}, {v.data(), v.size()})) {
break;
}
}
delete it;
}
Expand Down
64 changes: 48 additions & 16 deletions src/ll/api/base/Version.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ constexpr std::uint16_t to_digit(char c) noexcept { return static_cast<std::uint
constexpr char const* from_chars(char const* first, char const* last, std::uint16_t& d) noexcept {
if (first != last && is_digit(*first)) {
std::int32_t t = 0;
for (; first != last && is_digit(*first); ++first) { t = t * 10 + to_digit(*first); }
for (; first != last && is_digit(*first); ++first) {
t = t * 10 + to_digit(*first);
}
if (t <= (std::numeric_limits<std::uint16_t>::max)()) {
d = static_cast<std::uint16_t>(t);
return first;
Expand All @@ -39,7 +41,9 @@ constexpr char const* from_chars(char const* first, char const* last, std::uint1
constexpr char const* from_chars(char const* first, char const* last, std::optional<std::uint16_t>& d) noexcept {
if (first != last && is_digit(*first)) {
std::int32_t t = 0;
for (; first != last && is_digit(*first); ++first) { t = t * 10 + to_digit(*first); }
for (; first != last && is_digit(*first); ++first) {
t = t * 10 + to_digit(*first);
}
if (t <= (std::numeric_limits<std::uint16_t>::max)()) {
d = static_cast<std::uint16_t>(t);
return first;
Expand Down Expand Up @@ -96,7 +100,9 @@ struct PreRelease {

constexpr detail::from_chars_result from_chars(char const* first, char const* last) noexcept {
auto begin = first;
while (first != last && !detail::is_plus(*first)) { first++; }
while (first != last && !detail::is_plus(*first)) {
first++;
}
std::string s{begin, first};
std::vector<std::string_view> tokens;
tokens = ll::utils::string_utils::splitByPattern(s, ".");
Expand All @@ -116,7 +122,9 @@ struct PreRelease {
}

constexpr PreRelease& from_string(std::string_view str) {
if (!from_string_noexcept(str)) { throw VersionParseError("Invalid version string."); }
if (!from_string_noexcept(str)) {
throw VersionParseError("Invalid version string.");
}
return *this;
}

Expand All @@ -130,7 +138,9 @@ struct PreRelease {
}
str += '.';
}
if (str.ends_with('.')) { str.pop_back(); }
if (str.ends_with('.')) {
str.pop_back();
}
return str;
}
};
Expand Down Expand Up @@ -181,28 +191,38 @@ struct Version {
auto next = first;
if (next = detail::from_chars(next, last, major); detail::check_delimiter(next, last, '.')) {
if (next = detail::from_chars(++next, last, minor); detail::check_delimiter(next, last, '.')) {
if (next = detail::from_chars(++next, last, patch); next == last) { return {next, std::errc{}}; }
if (!next) { return {nullptr, std::errc::invalid_argument}; }
if (next = detail::from_chars(++next, last, patch); next == last) {
return {next, std::errc{}};
}
if (!next) {
return {nullptr, std::errc::invalid_argument};
}
if (detail::check_delimiter(next, last, '-')) {
PreRelease pre;
auto result = pre.from_chars(++next, last);
if (!result) return result;
if (pre.values.empty()) return {next, std::errc::invalid_argument};
preRelease = pre;
next = result.ptr;
if (result && next == last) { return {next, std::errc{}}; }
if (result && next == last) {
return {next, std::errc{}};
}
}
if (detail::check_delimiter(next, last, '+')) {
build = {++next, static_cast<size_t>(last - next)};
if (build->empty()) { return {nullptr, std::errc::invalid_argument}; }
if (build->empty()) {
return {nullptr, std::errc::invalid_argument};
}
next = last;
if (std::any_of(build->begin(), build->end(), [](char c) {
return !detail::is_digit(c) && !detail::is_letter(c);
})) {
return {nullptr, std::errc::invalid_argument};
}
}
if (next == last) { return {next, std::errc{}}; }
if (next == last) {
return {next, std::errc{}};
}
}
}
return {first, std::errc::invalid_argument};
Expand All @@ -213,7 +233,9 @@ struct Version {
}

constexpr Version& from_string(std::string_view str) {
if (!from_string_noexcept(str)) { throw VersionParseError("Invalid version string."); }
if (!from_string_noexcept(str)) {
throw VersionParseError("Invalid version string.");
}
return *this;
}

Expand All @@ -232,11 +254,19 @@ struct Version {
}

[[nodiscard]] constexpr std::strong_ordering operator<=>(Version const& other) const noexcept {
if (major != other.major) { return major <=> other.major; }
if (minor != other.minor) { return minor <=> other.minor; }
if (patch != other.patch) { return patch <=> other.patch; }
if (major != other.major) {
return major <=> other.major;
}
if (minor != other.minor) {
return minor <=> other.minor;
}
if (patch != other.patch) {
return patch <=> other.patch;
}
if (preRelease.has_value()) {
if (other.preRelease.has_value()) { return preRelease.value() <=> other.preRelease.value(); }
if (other.preRelease.has_value()) {
return preRelease.value() <=> other.preRelease.value();
}
return std::strong_ordering::less;
} else if (other.preRelease.has_value()) {
return std::strong_ordering::greater;
Expand All @@ -259,7 +289,9 @@ inline J serialize(Version const& ver) {
}
template <class J>
inline void deserialize(Version& ver, J const& j) {
if (j.is_string()) { ver.from_string(j.template get<std::string>()); }
if (j.is_string()) {
ver.from_string(j.template get<std::string>());
}
}

namespace literals {
Expand Down
Loading

0 comments on commit a47a743

Please sign in to comment.