READMEのCASL II仕様書へのリンクを修正
[YACASL2.git] / src / cmem.c
1 #include "cmem.h"
2
3 void *malloc_chk(size_t size, const char *tag)
4 {
5     void *p = NULL;
6
7     if((p = malloc(size)) == NULL) {
8         fprintf(stderr, "%s: cannot allocate memory\n", tag);
9         exit(1);
10     }
11     return memset(p, 0, size);
12 }
13
14 void *calloc_chk(size_t nmemb, size_t size, const char *tag)
15 {
16     void *p = NULL;
17
18     if((p = calloc(nmemb, size)) == NULL) {
19         fprintf(stderr, "%s: cannot allocate memory\n", tag);
20         exit(1);
21     }
22     return p;
23 }
24
25 char *strdup_chk(const char *s, const char *tag)
26 {
27     assert(s != NULL);
28     char *t = malloc_chk(strlen(s) + 1, tag);
29     strcpy(t, s);
30     return t;
31 }
32
33 char *strndup_chk(const char *s, size_t len, const char *tag)
34 {
35     assert(s != NULL);
36     char *t = NULL;
37
38     if(len < strlen(s)) {
39         t = malloc_chk(len + 1, tag);
40         strncpy(t, s, len);
41         t[len] = '\0';
42     } else {
43         t = strdup_chk(s, tag);
44     }
45     return t;
46 }
47
48 void strip_end(char *s)
49 {
50     for(int i = strlen(s) - 1; i > 0 && (s[i] == '\n' || s[i] == '\r' || s[i] == ' ' || s[i] == '\t'); i--) {
51         s[i] = '\0';
52     }
53 }
54
55 void strip_casl2_comment(char *s)
56 {
57     bool quoting = false;
58
59     for(int i = 0; s[i]; i++) {
60         /* 「'」で囲まれた文字列の場合。「''」は無視 */
61         if(s[i] == '\'' && s[i+1] != '\'' && (quoting == false || s[i-1] != '\'')) {
62             quoting = !quoting;
63         /* 「'」で囲まれた文字列でない場合、文字列末尾の「;」以降を削除 */
64         } else if(quoting == false && s[i] == ';') {
65             s[i] = '\0';
66             break;
67         }
68     }
69 }
70
71 char *strrev(const char *s)
72 {
73     char *t = strdup_chk(s, "strrev.t");
74     int l = strlen(t);
75
76     for(int i = 0; i < l-1-i; i++) {
77         char tmp = t[i];
78         t[i] = t[l-1-i];
79         t[l-1-i] = tmp;
80     }
81     return t;
82 }