/* $Id: msg.c,v 1.666 2004/09/20 10:50:19 shrike Exp $ */
/************************************************************************************
* Copyright 2004 Astrum Metaphora consortium *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
************************************************************************************/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "const.h"
#include "typedef.h"
#include "mlstring.h"
#include "varr.h"
#include "db.h"
#include "msg.h"
#include "str.h"
#include "util.h"
varr msg_hash_table[MAX_MSG_HASH];
#define msghash(s) hashstr(s, 32, MAX_MSG_HASH)
static int cmpmsg(const void*, const void*);
static int cmpmlstr(const void*, const void*);
void load_msgdb(void)
{
int i;
FILE *fp;
mlstring *ml;
line_number = 0;
if ((fp = dfopen(ETC_PATH, MSG_FILE, "r")) == NULL)
exit(1);
for (i = 0; i < MAX_MSG_HASH; i++) {
varr *v = msg_hash_table+i;
v->nsize = sizeof(mlstring*);
v->nstep = 4;
}
for (;;) {
ml = mlstr_fread(fp);
if (mlstr_null(ml)) {
db_error("msgdb_load", "no '$' found");
exit(1);
}
if (!strcmp(mlstr_mval(ml), "$")) {
mlstr_free(ml);
break;
}
msg_add(ml);
}
fclose(fp);
}
mlstring **msg_add(mlstring *ml)
{
mlstring **mlp;
varr *v;
const char *name = mlstr_mval(ml);
if (IS_NULLSTR(name))
return NULL;
v = msg_hash_table+msghash(name);
if (varr_bsearch(v, name, cmpmsg)) {
db_error("msg_add", "%s: duplicate entry", name);
return NULL;
}
mlp = varr_enew(v);
*mlp = ml;
varr_qsort(v, cmpmlstr);
return varr_bsearch(v, name, cmpmsg);
}
mlstring **msg_lookup(const char *name)
{
if (IS_NULLSTR(name))
return NULL;
return varr_bsearch(msg_hash_table+msghash(name), name, cmpmsg);
}
mlstring *msg_del(const char *name)
{
varr *v;
mlstring **mlp;
mlstring *ml;
v = msg_hash_table+msghash(name);
mlp = varr_bsearch(v, name, cmpmsg);
if (mlp == NULL)
return NULL;
ml = *mlp;
*mlp = NULL;
varr_qsort(v, cmpmlstr);
v->nused--;
return ml;
}
const char *GETMSG(const char *msg, int lang)
{
mlstring **mlp = msg_lookup(msg);
if (mlp == NULL)
return msg;
return mlstr_val(*mlp, lang);
}
/* reverse order (otherwise msg_del will not work) */
static int cmpmsg(const void* p1, const void* p2)
{
return -strcmp((char*)p1, mlstr_mval(*(mlstring**)p2));
}
/* reverse order (otherwise msg_del will not work) */
static int cmpmlstr(const void* p1, const void* p2)
{
return -strcmp(mlstr_mval(*(mlstring**)p1), mlstr_mval(*(mlstring**)p2));
}