X-Git-Url: http://j8takagi.net/cgi-bin/gitweb.cgi?p=YACASL2.git;a=blobdiff_plain;f=src%2Fcmem.c;h=bd6328d94ef80bdfadc72153fc51b5c2105cb6a6;hp=b83c79c3dc546166d7208b95da0bf3bcb0525df6;hb=HEAD;hpb=555c5e8b851becc08ba661a9cb19f617d5a00c12;ds=sidebyside diff --git a/src/cmem.c b/src/cmem.c index b83c79c..bd6328d 100644 --- a/src/cmem.c +++ b/src/cmem.c @@ -1,47 +1,82 @@ #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); - exit(-1); + exit(1); } 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); - exit(-1); + exit(1); } 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; - - t = malloc_chk(strlen(s) + 1, tag); + char *t = malloc_chk(strlen(s) + 1, tag); strcpy(t, s); return t; } -/* メモリがNULLの場合は解放 */ -void free_chk(void *ptr, char *tag) +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; +} + +void strip_end(char *s) { - if(ptr != NULL) { - free(ptr); + for(int i = strlen(s) - 1; i > 0 && (s[i] == '\n' || s[i] == '\r' || s[i] == ' ' || s[i] == '\t'); i--) { + s[i] = '\0'; } } + +void 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; + } + } +} + +char *strrev(const char *s) +{ + char *t = strdup_chk(s, "strrev.t"); + int l = strlen(t); + + for(int i = 0; i < l-1-i; i++) { + char tmp = t[i]; + t[i] = t[l-1-i]; + t[l-1-i] = tmp; + } + return t; +}