LibusbUtils: Create ErrorWrap

This commit is contained in:
Pokechu22 2022-06-02 13:32:30 -07:00
parent 0d8772ccbe
commit 457fcbaf5e
2 changed files with 44 additions and 1 deletions

View File

@ -23,7 +23,7 @@ public:
Impl() Impl()
{ {
const int ret = libusb_init(&m_context); const int ret = libusb_init(&m_context);
ASSERT_MSG(IOS_USB, ret == LIBUSB_SUCCESS, "Failed to init libusb: {}", libusb_error_name(ret)); ASSERT_MSG(IOS_USB, ret == LIBUSB_SUCCESS, "Failed to init libusb: {}", ErrorWrap(ret));
if (ret != LIBUSB_SUCCESS) if (ret != LIBUSB_SUCCESS)
return; return;
@ -118,4 +118,22 @@ ConfigDescriptor MakeConfigDescriptor(libusb_device* device, u8 config_num)
#endif #endif
return {nullptr, [](auto) {}}; return {nullptr, [](auto) {}};
} }
const char* ErrorWrap::GetName() const
{
#if defined(__LIBUSB__)
return libusb_error_name(m_error);
#else
return "__LIBUSB__ not defined";
#endif
}
const char* ErrorWrap::GetStrError() const
{
#if defined(__LIBUSB__)
return libusb_strerror(static_cast<libusb_error>(m_error));
#else
return "__LIBUSB__ not defined";
#endif
}
} // namespace LibusbUtils } // namespace LibusbUtils

View File

@ -3,6 +3,7 @@
#pragma once #pragma once
#include <fmt/format.h>
#include <functional> #include <functional>
#include <memory> #include <memory>
@ -39,4 +40,28 @@ private:
using ConfigDescriptor = UniquePtr<libusb_config_descriptor>; using ConfigDescriptor = UniquePtr<libusb_config_descriptor>;
ConfigDescriptor MakeConfigDescriptor(libusb_device* device, u8 config_num = 0); ConfigDescriptor MakeConfigDescriptor(libusb_device* device, u8 config_num = 0);
// Wrapper for libusb_error to be used with fmt. Note that we can't create a fmt::formatter
// directly for libusb_error as it is a plain enum and most libusb functions actually return an
// int instead of a libusb_error.
struct ErrorWrap
{
constexpr explicit ErrorWrap(int error) : m_error(error) {}
const int m_error;
const char* GetStrError() const;
const char* GetName() const;
};
} // namespace LibusbUtils } // namespace LibusbUtils
template <>
struct fmt::formatter<LibusbUtils::ErrorWrap>
{
constexpr auto parse(fmt::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const LibusbUtils::ErrorWrap& wrap, FormatContext& ctx) const
{
return fmt::format_to(ctx.out(), "{} ({}: {})", wrap.GetStrError(), wrap.m_error,
wrap.GetName());
}
};