From 32c1dba829a9f01f6bd66d6f65e237913ccbc073 Mon Sep 17 00:00:00 2001 From: "K. Lange" Date: Sat, 6 Aug 2022 12:17:32 +0900 Subject: [PATCH] Add krk_stringFromFormat --- src/kuroko/util.h | 1 + src/obj_str.c | 9 +++++++++ src/sys.c | 15 +++------------ 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/kuroko/util.h b/src/kuroko/util.h index 1c6c166..02fdcb1 100644 --- a/src/kuroko/util.h +++ b/src/kuroko/util.h @@ -316,3 +316,4 @@ extern int krk_parseArgs_impl( extern int krk_pushStringBuilderFormatV(struct StringBuilder * sb, const char * fmt, va_list args); extern int krk_pushStringBuilderFormat(struct StringBuilder * sb, const char * fmt, ...); +extern KrkValue krk_stringFromFormat(const char * fmt, ...); diff --git a/src/obj_str.c b/src/obj_str.c index c00f74f..8b1a623 100644 --- a/src/obj_str.c +++ b/src/obj_str.c @@ -1213,6 +1213,15 @@ int krk_pushStringBuilderFormat(struct StringBuilder * sb, const char * fmt, ... return result; } +KrkValue krk_stringFromFormat(const char * fmt, ...) { + struct StringBuilder sb = {0}; + va_list args; + va_start(args, fmt); + int result = krk_pushStringBuilderFormatV(&sb,fmt,args); + va_end(args); + if (!result) return krk_discardStringBuilder(&sb); + return krk_finishStringBuilder(&sb); +} _noexport void _createAndBind_strClass(void) { diff --git a/src/sys.c b/src/sys.c index 6f7abac..d938923 100644 --- a/src/sys.c +++ b/src/sys.c @@ -245,23 +245,14 @@ void krk_module_init_kuroko(void) { if (strstr(dir,"/bin") == (dir + strlen(dir) - 4)) { slash = strrchr(dir,'/'); if (slash) *slash = '\0'; - size_t allocSize = sizeof("/lib/kuroko/") + strlen(dir); - char * out = malloc(allocSize); - size_t len = snprintf(out, allocSize, "%s/lib/kuroko/", dir); - krk_writeValueArray(AS_LIST(module_paths), OBJECT_VAL(krk_takeString(out, len))); + krk_writeValueArray(AS_LIST(module_paths), krk_stringFromFormat("%s/lib/kuroko/", dir)); } else { - size_t allocSize = sizeof("/modules/") + strlen(dir); - char * out = malloc(allocSize); - size_t len = snprintf(out, allocSize, "%s/modules/", dir); - krk_writeValueArray(AS_LIST(module_paths), OBJECT_VAL(krk_takeString(out, len))); + krk_writeValueArray(AS_LIST(module_paths), krk_stringFromFormat("%s/modules/", dir)); } #else char * backslash = strrchr(dir,'\\'); if (backslash) *backslash = '\0'; - size_t allocSize = sizeof("\\modules\\") + strlen(dir); - char * out = malloc(allocSize); - size_t len = snprintf(out, allocSize, "%s\\modules\\", dir); - krk_writeValueArray(AS_LIST(module_paths), OBJECT_VAL(krk_takeString(out,len))); + krk_writeValueArray(AS_LIST(module_paths), krk_stringFromFormat("%s\\modules\\", dir)); #endif free(dir); }