From a8aa6b2c5e570409d1c87a6bd42d652336f3b1ff Mon Sep 17 00:00:00 2001 From: Yuichi Nishiwaki Date: Fri, 21 Feb 2014 18:24:20 +0900 Subject: [PATCH] add some string utility functions --- include/picrin.h | 3 +++ src/string.c | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/include/picrin.h b/include/picrin.h index 1da8a491..5246acee 100644 --- a/include/picrin.h +++ b/include/picrin.h @@ -166,6 +166,9 @@ char *pic_strdup(pic_state *, const char *); char *pic_strndup(pic_state *, const char *, size_t); pic_str *pic_str_new(pic_state *, const char * /* nullable */, size_t); pic_str *pic_str_new_cstr(pic_state *, const char *); +char pic_str_ref(pic_state *, pic_str *, size_t); +pic_str *pic_strcat(pic_state *, pic_str *, pic_str *); +pic_str *pic_substr(pic_state *, pic_str *, size_t, size_t); pic_value pic_format(pic_state *, const char *, ...); pic_value pic_vformat(pic_state *, const char *, va_list); diff --git a/src/string.c b/src/string.c index f7437c37..a491e4c8 100644 --- a/src/string.c +++ b/src/string.c @@ -32,6 +32,45 @@ pic_str_new_cstr(pic_state *pic, const char *cstr) return pic_str_new(pic, cstr, strlen(cstr)); } +char +pic_str_ref(pic_state *pic, pic_str *str, size_t n) +{ + UNUSED(pic); + + return str->str[n]; +} + +pic_str * +pic_strcat(pic_state *pic, pic_str *a, pic_str *b) +{ + size_t len; + char *buf; + + len = a->len + b->len; + buf = pic_alloc(pic, len + 1); + + memcpy(buf, a->str, a->len); + memcpy(buf + a->len, b->str, b->len); + buf[len] = '\0'; + + return pic_str_new(pic, buf, len); +} + +pic_str * +pic_substr(pic_state *pic, pic_str *str, size_t s, size_t e) +{ + size_t len; + char *buf; + + len = e - s; + buf = pic_alloc(pic, len + 1); + + memcpy(buf, str->str + s, len); + buf[len] = '\0'; + + return pic_str_new(pic, buf, len); +} + pic_value pic_vfformat(pic_state *pic, XFILE *file, const char *fmt, va_list ap) {