From 9f240c191c86f3e869f7471c1528ebe2a8774b73 Mon Sep 17 00:00:00 2001 From: Yuichi Nishiwaki Date: Sun, 23 Feb 2014 11:25:39 +0900 Subject: [PATCH] add pic_str_new_fill --- include/picrin/string.h | 1 + src/string.c | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/include/picrin/string.h b/include/picrin/string.h index 14d0caa8..66ccd374 100644 --- a/include/picrin/string.h +++ b/include/picrin/string.h @@ -20,6 +20,7 @@ struct pic_string { pic_str *pic_str_new(pic_state *, const char * /* nullable */, size_t); pic_str *pic_str_new_cstr(pic_state *, const char *); +pic_str *pic_str_new_fill(pic_state *, size_t, char); char pic_str_ref(pic_state *, pic_str *, size_t); pic_str *pic_strcat(pic_state *, pic_str *, pic_str *); diff --git a/src/string.c b/src/string.c index c132d4db..d35bedfb 100644 --- a/src/string.c +++ b/src/string.c @@ -33,6 +33,21 @@ pic_str_new_cstr(pic_state *pic, const char *cstr) return pic_str_new(pic, cstr, strlen(cstr)); } +pic_str * +pic_str_new_fill(pic_state *pic, size_t len, char fill) +{ + size_t i; + char *cstr; + + cstr = (char *)pic_alloc(pic, len + 1); + for (i = 0; i < len; ++i) { + cstr[i] = fill; + } + cstr[len] = '\0'; + + return pic_str_new(pic, cstr, len); +} + char pic_str_ref(pic_state *pic, pic_str *str, size_t n) { @@ -178,18 +193,12 @@ pic_str_string_p(pic_state *pic) static pic_value pic_str_make_string(pic_state *pic) { - int k, i; - char c = ' ', *cstr; + int len; + char c = ' '; - pic_get_args(pic, "i|c", &k, &c); + pic_get_args(pic, "i|c", &len, &c); - cstr = (char *)pic_alloc(pic, k + 1); - for (i = 0; i < k; ++i) { - cstr[i] = c; - } - cstr[k] = '\0'; - - return pic_obj_value(pic_str_new(pic, cstr, k)); + return pic_obj_value(pic_str_new_fill(pic, len, c)); } static pic_value