Ubuntu 10.04 PPC版で判明した問題を修正
[YACASL2.git] / src / cerr.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include <stdbool.h>
6 #include "cerr.h"
7
8 /**
9  * エラーの初期化
10  */
11 void cerr_init()
12 {
13     cerr = malloc_chk(sizeof(CERR), "cerr");
14     cerr->num = 0;
15 }
16
17 /**
18  * 現在のエラー
19  */
20 CERR *cerr;
21
22 /**
23  * エラーリスト
24  */
25 CERRLIST *cerrlist;
26
27 /**
28  * エラーリストを作成または追加する
29  */
30 bool addcerrlist(int newerrc, CERR newerrv[])
31 {
32     int i;
33     CERRLIST *p, *q;
34
35     assert(newerrc > 0 && newerrv != NULL);
36     if(cerrlist == NULL) {
37         p = cerrlist = malloc_chk(sizeof(CERRLIST), "cerrlist");
38     } else {
39         for(p = cerrlist; p != NULL; p = p->next) {
40             q = p;
41         }
42         p = q->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
43     }
44     for(i = 0; i < newerrc; i++) {
45         p->cerr = &(newerrv[i]);
46         p->next = malloc_chk(sizeof(CERRLIST), "cerrlist.next");
47         q = p;
48         p = p->next;
49     }
50     q->next = NULL;
51     return true;
52 }
53
54 /**
55  * エラーリストを表示する
56  */
57 void printcerrlist()
58 {
59     CERRLIST *p;
60
61     if(cerrlist == NULL) {
62         puts("error list is null.");
63     } else {
64         for(p = cerrlist; p != NULL; p = p->next) {
65             printf("%d: %s\n", p->cerr->num, p->cerr->msg);
66         }
67     }
68 }
69
70 /**
71  * 現在のエラーを設定する
72  */
73 void setcerr(int num, const char *str)
74 {
75     /* 現在のエラー番号を設定  */
76     cerr->num = num;
77     /* 現在のエラーメッセージを設定 */
78     cerr->msg = malloc_chk(CERRMSGSIZE + 1, "cerr.msg");
79     if(str != NULL && strlen(str) <= CERRSTRSIZE) {
80         sprintf(cerr->msg, "%s: %s", str, getcerrmsg(cerr->num));
81     } else {
82         strcpy(cerr->msg, getcerrmsg(cerr->num));
83     }
84 }
85
86 /**
87  * エラーリストから、エラー番号に対応するメッセージを返す
88  */
89 char *getcerrmsg(int num)
90 {
91     CERRLIST *p;
92
93     for(p = cerrlist; p != NULL; p = p->next) {
94         if(num == p->cerr->num) {
95             return p->cerr->msg;
96         }
97     }
98     return "unknown error";
99 }
100
101 /**
102  * エラーリストと現在のエラーを解放する
103  */
104 void freecerr()
105 {
106     CERRLIST *p = cerrlist, *q;
107
108     /* エラーリストを解放 */
109     while(p != NULL) {
110         q = p->next;
111         free_chk(p, "freecerr.p");
112         p = q;
113     }
114     /* 現在のエラーメッセージを解放 */
115     /* free_chk(cerr->msg, "cerr->msg"); */
116     /* 現在のエラーを解放 */
117     free_chk(cerr, "cerr");
118 }