diff --git a/doc/en/dev/plugin_c_api.en.xml b/doc/en/dev/plugin_c_api.en.xml index 3b35e5713..f4eb5b150 100644 --- a/doc/en/dev/plugin_c_api.en.xml +++ b/doc/en/dev/plugin_c_api.en.xml @@ -1545,6 +1545,42 @@ char *weechat_utf8_pos (const char *string, int real_pos); +
+ weechat_utf8_strndup + + + Prototype: + +char *weechat_utf8_strndup (const char *string, int max_chars); + + + + Return duplicate string, with max N chars. + + + Arguments: + + + + : string + + + + + : max chars + + + + + + Return value: duplicated string, NULL if error. + + + Example: + char *string = weechat_utf8_strndup ("chĂȘne", 3); /* returns "chĂȘ" */ + +
+ diff --git a/src/core/wee-utf8.c b/src/core/wee-utf8.c index 9e134b69a..65e73d92f 100644 --- a/src/core/wee-utf8.c +++ b/src/core/wee-utf8.c @@ -452,3 +452,26 @@ utf8_pos (const char *string, int real_pos) } return count; } + +/* + * utf8_strndup: return duplicate string, with max N UTF-8 chars + */ + +char * +utf8_strndup (const char *string, int max_chars) +{ + const char *end; + char *result; + + if (!string || (max_chars < 0)) + return NULL; + + if (max_chars == 0) + return strdup (""); + + end = utf8_add_offset (string, max_chars); + if (!end || (end == string)) + return strdup (string); + + return string_strndup (string, end - string); +} diff --git a/src/core/wee-utf8.h b/src/core/wee-utf8.h index 219a9fd82..dd48ab31e 100644 --- a/src/core/wee-utf8.h +++ b/src/core/wee-utf8.h @@ -47,5 +47,6 @@ extern int utf8_char_size_screen (const char *string); extern char *utf8_add_offset (const char *string, int offset); extern int utf8_real_pos (const char *string, int pos); extern int utf8_pos (const char *string, int real_pos); +extern char *utf8_strndup (const char *string, int max_chars); #endif /* wee-utf8.h */ diff --git a/src/plugins/plugin.c b/src/plugins/plugin.c index 782232492..8b0ff44fb 100644 --- a/src/plugins/plugin.c +++ b/src/plugins/plugin.c @@ -360,6 +360,7 @@ plugin_load (const char *filename) new_plugin->utf8_add_offset = &utf8_add_offset; new_plugin->utf8_real_pos = &utf8_real_pos; new_plugin->utf8_pos = &utf8_pos; + new_plugin->utf8_strndup = &utf8_strndup; new_plugin->mkdir_home = &util_mkdir_home; new_plugin->mkdir = &util_mkdir; diff --git a/src/plugins/weechat-plugin.h b/src/plugins/weechat-plugin.h index bc3725399..e772308bf 100644 --- a/src/plugins/weechat-plugin.h +++ b/src/plugins/weechat-plugin.h @@ -171,6 +171,7 @@ struct t_weechat_plugin char *(*utf8_add_offset) (const char *string, int offset); int (*utf8_real_pos) (const char *string, int pos); int (*utf8_pos) (const char *string, int real_pos); + char *(*utf8_strndup) (const char *string, int max_chars); /* directories */ int (*mkdir_home) (const char *directory, int mode);