From 7e23a61e720b3c26941ccf1542297eb69df98fc8 Mon Sep 17 00:00:00 2001 From: Vsevolod Stakhov Date: Thu, 26 Nov 2015 15:30:04 +0000 Subject: [PATCH] Add is_uppercase utility for utf8 strings --- src/lua/lua_util.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/lua/lua_util.c b/src/lua/lua_util.c index 32fc23fc1..5568b874a 100644 --- a/src/lua/lua_util.c +++ b/src/lua/lua_util.c @@ -124,6 +124,15 @@ LUA_FUNCTION_DEF (util, parse_addr); */ LUA_FUNCTION_DEF (util, fold_header); +/*** + * @function util.is_uppercase(str) + * Returns true if a string is all uppercase + * + * @param {string} str input string + * @return {bool} true if a string is all uppercase + */ +LUA_FUNCTION_DEF (util, is_uppercase); + static const struct luaL_reg utillib_f[] = { LUA_INTERFACE_DEF (util, create_event_base), LUA_INTERFACE_DEF (util, load_rspamd_config), @@ -137,6 +146,7 @@ static const struct luaL_reg utillib_f[] = { LUA_INTERFACE_DEF (util, levenshtein_distance), LUA_INTERFACE_DEF (util, parse_addr), LUA_INTERFACE_DEF (util, fold_header), + LUA_INTERFACE_DEF (util, is_uppercase), {NULL, NULL} }; @@ -625,6 +635,49 @@ lua_util_fold_header (lua_State *L) return 1; } +static gint +lua_util_is_uppercase (lua_State *L) +{ + const gchar *str, *p; + gsize sz, remain; + gunichar uc; + guint nlc = 0, nuc = 0; + + str = luaL_checklstring (L, 1, &sz); + remain = sz; + + if (str && remain > 0) { + while (remain > 0) { + uc = g_utf8_get_char_validated (str, remain); + p = g_utf8_next_char (str); + + if (p - str > (gint) remain) { + break; + } + + remain -= p - str; + + if (g_unichar_isupper (uc)) { + nuc++; + } + else if (g_unichar_islower (uc)) { + nlc++; + } + + str = p; + } + } + + if (nuc > 0 && nlc == 0) { + lua_pushboolean (L, TRUE); + } + else { + lua_pushboolean (L, FALSE); + } + + return 1; +} + static gint lua_load_util (lua_State * L) { -- 2.39.5