basic/string-util: add a convenience function to cescape mostly-ascii fields

It's not supposed to be the most efficient, but instead fast and simple to use.

I kept the logic in ellipsize_mem() to use unicode ellipsis even in non-unicode
locales. I'm not quite convinced things should be this way, especially that with
this patch it'd actually be simpler to always use "…" in unicode locale and "..."
otherwise, but Lennart wanted it this way for some reason.
This commit is contained in:
Zbigniew Jędrzejewski-Szmek
2018-05-31 14:27:07 +02:00
parent b778252b4a
commit 8409f68858
3 changed files with 80 additions and 16 deletions
+25
View File
@@ -6,6 +6,7 @@
***/
#include "alloc-util.h"
#include "locale-util.h"
#include "macro.h"
#include "string-util.h"
#include "strv.h"
@@ -77,6 +78,29 @@ static void test_ascii_strcasecmp_nn(void) {
assert_se(ascii_strcasecmp_nn("BBbb", 4, "aaaa", 4) > 0);
}
static void test_cellescape(void) {
char buf[40];
assert_se(streq(cellescape(buf, 10, "1"), "1"));
assert_se(streq(cellescape(buf, 10, "12"), "12"));
assert_se(streq(cellescape(buf, 10, "123"), is_locale_utf8() ? "1…" : "1..."));
assert_se(streq(cellescape(buf, 10, "1\011"), "1\\t"));
assert_se(streq(cellescape(buf, 10, "1\020"), "1\\020"));
assert_se(streq(cellescape(buf, 10, "1\020x"), is_locale_utf8() ? "1…" : "1..."));
assert_se(streq(cellescape(buf, 40, "1\020"), "1\\020"));
assert_se(streq(cellescape(buf, 40, "1\020x"), "1\\020x"));
assert_se(streq(cellescape(buf, 40, "\a\b\f\n\r\t\v\\\"'"), "\\a\\b\\f\\n\\r\\t\\v\\\\\\\"\\'"));
assert_se(streq(cellescape(buf, 10, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a..."));
assert_se(streq(cellescape(buf, 11, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a…" : "\\a..."));
assert_se(streq(cellescape(buf, 12, "\a\b\f\n\r\t\v\\\"'"), is_locale_utf8() ? "\\a\\b…" : "\\a\\b..."));
assert_se(streq(cellescape(buf, sizeof buf, "1\020"), "1\\020"));
assert_se(streq(cellescape(buf, sizeof buf, "1\020x"), "1\\020x"));
}
static void test_streq_ptr(void) {
assert_se(streq_ptr(NULL, NULL));
assert_se(!streq_ptr("abc", "cdef"));
@@ -422,6 +446,7 @@ int main(int argc, char *argv[]) {
test_string_erase();
test_ascii_strcasecmp_n();
test_ascii_strcasecmp_nn();
test_cellescape();
test_streq_ptr();
test_strstrip();
test_strextend();