From 5bd23aa6ed6cc2780bc5b5ceb6114afec126eab7 Mon Sep 17 00:00:00 2001 From: modeco80 Date: Sun, 19 Nov 2023 20:54:58 -0500 Subject: [PATCH] Implement library magic checking & error handling --- src/main.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e588a76..c6f2e62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,12 +4,12 @@ #include #include #include +#include #include #include +#include #include -#include - namespace fs = std::filesystem; std::vector BoltDecompress(u8* input, usize decompressedSize) { @@ -72,6 +72,41 @@ std::vector BoltDecompress(u8* input, usize decompressedSize) { return res; } +// error code boilerplate. This should be moved later +enum class BoltErrc { InvalidMagic = 1 }; + +struct BoltErrorCategory : std::error_category { + const char* name() const noexcept override { return "boltio"; } + std::string message(i32 ev) const override { + switch(static_cast(ev)) { + case BoltErrc::InvalidMagic: return "invalid bolt library file magic"; + default: return "unknown error"; + } + } +}; + +const BoltErrorCategory boltCategory {}; + +std::error_code make_error_code(BoltErrc errc) { + return { static_cast(errc), boltCategory }; +} + +namespace std { + template <> + struct is_error_code_enum : true_type {}; + + /// Custom formatter for std::error_code. As far as I know, this is + /// Not going to be added in C++23, despite the fact fmt already has a specialization for it, + /// so I have to implement one myself. At least it's not that awful to. + template <> + struct formatter : formatter { + template + inline auto format(const error_code& ec, FormatContext& ctx) const { + return std::format_to(ctx.out(), "{} [{}.{}]", ec.message(), ec.category().name(), ec.value()); + } + }; +} // namespace std + struct BoltReader { struct ParsedTableEntry { std::string_view filename; @@ -98,6 +133,15 @@ struct BoltReader { BoltReader() {} ErrorOr OpenBolt(const fs::path& path) { + // Load the BOLT file + if(auto error = boltFile.Open(path); error.HasError()) + return error; + + lib = std::bit_cast(boltFile.GetMapping()); + + if(!lib->Validate()) + return make_error_code(BoltErrc::InvalidMagic); + auto p = path; p.replace_filename("SLUS_201.14"); @@ -107,11 +151,6 @@ struct BoltReader { // Load table entries. GetTableEntries(); - // Load the BOLT file - if(auto error = boltFile.Open(path); error.HasError()) - return error; - - lib = std::bit_cast(boltFile.GetMapping()); return {}; } @@ -169,7 +208,7 @@ struct BoltReader { int main() { BoltReader reader; if(auto error = reader.OpenBolt(fs::current_path() / "ASSETS.BLT"); error.HasError()) { - std::cout << "Error opening Bolt file: " << error.Error(); + std::cout << std::format("Error initalizing bolt reader: {}\n", error.Error()); } reader.ForEachFile([](BoltReader::ParsedTableEntry& ent) {