X-Git-Url: http://j8takagi.net/cgi-bin/gitweb.cgi?p=YACASL2.git;a=blobdiff_plain;f=src%2Fcmem.c;h=48bc632b9ae58728a2145fd8fa4961c01257a3f9;hp=b5f90332f3071c69d5c8a0b61740f8d9779d9d90;hb=86e559d164166966a797a1e5855871d48e087ddd;hpb=4a1d361916c660b63611a40520eaf7c78788f123 diff --git a/src/cmem.c b/src/cmem.c index b5f9033..48bc632 100644 --- a/src/cmem.c +++ b/src/cmem.c @@ -1,17 +1,8 @@ -#include -#include -#include -#include -#include #include "cmem.h" -/** - * mallocを実行し、0で初期化 - * メモリを確保できない場合はエラーを出力して終了 - */ -void *malloc_chk(size_t size, char *tag) +void *malloc_chk(size_t size, const char *tag) { - void *p; + void *p = NULL; if((p = malloc(size)) == NULL) { fprintf(stderr, "%s: cannot allocate memory\n", tag); @@ -20,13 +11,9 @@ void *malloc_chk(size_t size, char *tag) return memset(p, 0, size); } -/** - * callocを実行 - * メモリを確保できない場合はエラーを出力して終了 - */ -void *calloc_chk(size_t nmemb, size_t size, char *tag) +void *calloc_chk(size_t nmemb, size_t size, const char *tag) { - void *p; + void *p = NULL; if((p = calloc(nmemb, size)) == NULL) { fprintf(stderr, "%s: cannot allocate memory\n", tag); @@ -35,15 +22,52 @@ void *calloc_chk(size_t nmemb, size_t size, char *tag) return p; } -/** - * malloc_chkを実行してメモリを確保し、コピーした文字列を返す - */ -char *strdup_chk(const char *s, char *tag) +char *strdup_chk(const char *s, const char *tag) { assert(s != NULL); - char *t; + char *t = NULL; t = malloc_chk(strlen(s) + 1, tag); strcpy(t, s); return t; } + +char *strndup_chk(const char *s, size_t len, const char *tag) +{ + assert(s != NULL); + char *t = NULL; + + if(len < strlen(s)) { + t = malloc_chk(len + 1, tag); + strncpy(t, s, len); + t[len] = '\0'; + } else { + t = strdup_chk(s, tag); + } + return t; +} + +char *strip_end(char *s) +{ + for(int i = strlen(s) - 1; i > 0 && (s[i] == '\n' || s[i] == ' ' || s[i] == '\t'); i--) { + s[i] = '\0'; + } + return s; +} + +char *strip_casl2_comment(char *s) +{ + bool quoting = false; + + for(int i = 0; s[i]; i++) { + /* 「'」で囲まれた文字列の場合。「''」は無視 */ + if(s[i] == '\'' && s[i+1] != '\'' && (quoting == false || s[i-1] != '\'')) { + quoting = !quoting; + /* 「'」で囲まれた文字列でない場合、文字列末尾の「;」以降を削除 */ + } else if(quoting == false && s[i] == ';') { + s[i] = '\0'; + break; + } + } + return s; +}