log-e-sappho/src/spho/ctx.c

130 lines
2.4 KiB
C

#include <sys/queue.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spho/ctx.h"
static const char *spho_ctx_sys_strerror(struct spho_ctx *);
static const char *spho_ctx_intern_strerror(struct spho_ctx *);
struct spho_err {
int err;
const char *msg;
};
struct spho_err spho_errmsgs[] = {
{ SPHO_ERR_SYS, "spho system error" },
{ SPHO_ERR_INTERNAL, "spho internal error" },
{ SPHO_ERR_TOOBIG, "parameter size too big" },
{ SPHO_ERR_ARGINVAL, "invalid argument" },
{ SPHO_ERR_NAMEINUSE, "name in use" },
{ -1, NULL }
};
struct spho_ctx *
spho_ctx_create(void)
{
struct spho_ctx *c;
c = NULL;
if ((c = malloc(sizeof(struct spho_ctx))) == NULL)
return (NULL);
c->err = 0;
c->err_info = 0;
if (spho_scope_init(&c->glob, c, NULL) == -1) {
free(c);
return (NULL);
}
SPHO_POSTCOND(c != NULL);
return (c);
}
void
spho_ctx_destroy(struct spho_ctx *ctx)
{
SPHO_PRECOND(ctx != NULL);
spho_scope_term(&ctx->glob);
free(ctx);
}
const char *
spho_ctx_strerror(struct spho_ctx *ctx)
{
int res;
const char *msg;
SPHO_PRECOND(ctx != NULL);
msg = NULL;
if (SPHO_ERR_IS_SYSERR(ctx->err))
msg = spho_ctx_sys_strerror(ctx);
else
msg = spho_ctx_intern_strerror(ctx);
SPHO_POSTCOND(msg != NULL);
return (msg);
}
static const char *
spho_ctx_sys_strerror(struct spho_ctx *ctx)
{
int res;
SPHO_POSTCOND(ctx != NULL);
#ifdef SPHO_DEBUG
res = snprintf(ctx->errbuf, sizeof(ctx->errbuf),
"%s:%d:spho_syserr:%s (%d)", ctx->filebuf, ctx->errline,
strerror(ctx->err_info), ctx->err_info);
if (res >= sizeof(ctx->errbuf))
ctx->errbuf[sizeof(ctx->errbuf) - 1] = '\0';
#else
res = snprintf(ctx->errbuf, sizeof(ctx->errbuf),
"spho_syserr:%s (%d)", strerror(ctx->err_info),
ctx->err_info);
if (res >= sizeof(ctx->errbuf))
ctx->errbuf[sizeof(ctx->errbuf) - 1] = '\0';
#endif
return (ctx->errbuf);
}
static const char *
spho_ctx_intern_strerror(struct spho_ctx *ctx)
{
int i;
int res;
SPHO_PRECOND(ctx != NULL);
for (i = 0; spho_errmsgs[i].msg != NULL; i++) {
if (spho_errmsgs[i].err == ctx->err) {
#ifdef SPHO_DEBUG
res = snprintf(ctx->errbuf, sizeof(ctx->errbuf),
"%s:%d:spho_intern_err:%s", ctx->filebuf,
ctx->errline, spho_errmsgs[i].msg);
#else
res = snprintf(ctx->errbuf, sizeof(ctx->errbuf),
"spho_intern_err:%s", ctx->errbuf);
#endif
}
}
SPHO_POSTCOND(res != -1);
return (ctx->errbuf);
}