@COMMENT@

#include <string.h>
#if __has_include("soc/soc.h")
#include "soc/soc.h"
#endif
@HEADERS@

#ifdef CONFIG_ESP_ERR_TO_NAME_LOOKUP
#define ERR_TBL_IT(err)    {err, #err}

typedef struct {
    esp_err_t code;
    const char *msg;
} esp_err_msg_t;

static const esp_err_msg_t esp_err_msg_table[] = {
@ERROR_ITEMS@
};
#endif //CONFIG_ESP_ERR_TO_NAME_LOOKUP

static const char esp_unknown_msg[] =
#ifdef CONFIG_ESP_ERR_TO_NAME_LOOKUP
    "ERROR";
#else
    "UNKNOWN ERROR";
#endif //CONFIG_ESP_ERR_TO_NAME_LOOKUP

const char *esp_err_to_name(esp_err_t code)
{
#ifdef CONFIG_ESP_ERR_TO_NAME_LOOKUP
    int i;

    for (i = 0; i < sizeof(esp_err_msg_table)/sizeof(esp_err_msg_table[0]); ++i) {
        if (esp_err_msg_table[i].code == code) {
            return esp_err_msg_table[i].msg;
        }
    }
#endif //CONFIG_ESP_ERR_TO_NAME_LOOKUP

    return esp_unknown_msg;
}

const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen)
{
#ifdef CONFIG_ESP_ERR_TO_NAME_LOOKUP
    int i;

    for (i = 0; i < sizeof(esp_err_msg_table)/sizeof(esp_err_msg_table[0]); ++i) {
        if (esp_err_msg_table[i].code == code) {
            strlcpy(buf, esp_err_msg_table[i].msg, buflen);
            return buf;
        }
    }
#endif //CONFIG_ESP_ERR_TO_NAME_LOOKUP

    if (strerror_r(code, buf, buflen) == 0) {
        return buf;
    }

    snprintf(buf, buflen, "%s 0x%x(%d)", esp_unknown_msg, code, code);

    return buf;
}
