Program Listing for File error.hpp

Return to documentation for file (mcfp/error.hpp)

// Copyright Maarten L. Hekkelman 2022-2025
//
// SPDX-License-Identifier: BSD-2-Clause

#pragma once

#ifndef MCFP_EXPORT
# error "Please include mcfp.hpp only"
#endif

#ifndef IN_MODULE_INTERFACE
# include <string>
# include <system_error>
# include <type_traits>
# include <utility>
#endif

namespace mcfp
{

// we use the new system_error stuff.

MCFP_EXPORT enum class config_error
{
    unknown_option = 1,
    option_does_not_accept_argument,
    missing_argument_for_option,
    option_not_specified,
    invalid_config_file,
    wrong_type_cast,
    wrong_type_cast_flag,
    config_file_not_found
};
MCFP_EXPORT class config_category_impl : public std::error_category
{
  public:
    [[nodiscard]] const char *name() const noexcept override
    {
        return "configuration";
    }

    [[nodiscard]] std::string message(int ev) const override
    {
        switch (static_cast<config_error>(ev))
        {
            case config_error::unknown_option:
                return "unknown option";
            case config_error::option_does_not_accept_argument:
                return "option does not accept argument";
            case config_error::missing_argument_for_option:
                return "missing argument for option";
            case config_error::option_not_specified:
                return "option was not specified";
            case config_error::invalid_config_file:
                return "config file contains a syntax error";
            case config_error::wrong_type_cast:
                return "the implementation contains a type cast error";
            case config_error::config_file_not_found:
                return "the specified config file was not found";
            case config_error::wrong_type_cast_flag:
                return "the value assigned in a config file to a flag option was not 'true', 'false' or an integral numerical value";
        }
        std::unreachable();
    }

    [[nodiscard]] bool equivalent(const std::error_code & /*code*/, int /*condition*/) const noexcept override
    {
        return false;
    }
};

MCFP_EXPORT MCFP_INLINE std::error_category &config_category()
{
    static config_category_impl instance;
    return instance;
}

MCFP_EXPORT MCFP_INLINE std::error_code make_error_code(config_error e)
{
    return { static_cast<int>(e), config_category() };
}

MCFP_EXPORT MCFP_INLINE std::error_condition make_error_condition(config_error e)
{
    return { static_cast<int>(e), config_category() };
}

} // namespace mcfp

// Make our error_codes implicitly convertible

namespace std
{

template <> // NOLINT(bugprone-std-namespace-modification,cert-dcl58-cpp)
struct is_error_condition_enum<mcfp::config_error>
    : public true_type
{
};

} // namespace std