chiark / gitweb /
tree-wide: remove Lennart's copyright lines
[elogind.git] / src / basic / utf8.c
index 0dc76eba21d80a42f6302fdacf77585442c7c514..d18dbc35280c827d5cc8e9ca24a9de34db3003e3 100644 (file)
@@ -1,9 +1,6 @@
 /* SPDX-License-Identifier: LGPL-2.1+ */
 /***
-  This file is part of systemd.
-
   Copyright 2008-2011 Kay Sievers
-  Copyright 2012 Lennart Poettering
 ***/
 
 /* Parts of this file are based on the GLIB utf8 validation functions. The
@@ -35,6 +32,7 @@
 #include <string.h>
 
 #include "alloc-util.h"
+//#include "gunicode.h"
 #include "hexdecoct.h"
 #include "macro.h"
 #include "utf8.h"
@@ -246,6 +244,9 @@ char *utf8_escape_non_printable(const char *str) {
 char *ascii_is_valid(const char *str) {
         const char *p;
 
+        /* Check whether the string consists of valid ASCII bytes,
+         * i.e values between 0 and 127, inclusive. */
+
         assert(str);
 
         for (p = str; *p; p++)
@@ -255,6 +256,21 @@ char *ascii_is_valid(const char *str) {
         return (char*) str;
 }
 
+char *ascii_is_valid_n(const char *str, size_t len) {
+        size_t i;
+
+        /* Very similar to ascii_is_valid(), but checks exactly len
+         * bytes and rejects any NULs in that range. */
+
+        assert(str);
+
+        for (i = 0; i < len; i++)
+                if ((unsigned char) str[i] >= 128 || str[i] == 0)
+                        return NULL;
+
+        return (char*) str;
+}
+
 /**
  * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8
  * @out_utf8: output buffer of at least 4 bytes or NULL
@@ -414,3 +430,23 @@ size_t utf8_n_codepoints(const char *str) {
 
         return n;
 }
+
+size_t utf8_console_width(const char *str) {
+        size_t n = 0;
+
+        /* Returns the approximate width a string will take on screen when printed on a character cell
+         * terminal/console. */
+
+        while (*str != 0) {
+                char32_t c;
+
+                if (utf8_encoded_to_unichar(str, &c) < 0)
+                        return (size_t) -1;
+
+                str = utf8_next_char(str);
+
+                n += unichar_iswide(c) ? 2 : 1;
+        }
+
+        return n;
+}