]> git.draconx.ca Git - dxcommon.git/blobdiff - t/nls/mbswidth.c
help_print_optstring: Test fullwidth/halfwidth character output.
[dxcommon.git] / t / nls / mbswidth.c
diff --git a/t/nls/mbswidth.c b/t/nls/mbswidth.c
new file mode 100644 (file)
index 0000000..e8e7c33
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright © 2023 Nick Bowler
+ *
+ * Simplified mbsnwidth for test purposes.
+ *
+ * License WTFPL2: Do What The Fuck You Want To Public License, version 2.
+ * This is free software: you are free to do what the fuck you want to.
+ * There is NO WARRANTY, to the extent permitted by law.
+ */
+
+#include <string.h>
+#include <locale.h>
+#include <wchar.h>
+
+#include "mbswidth.h"
+
+int mbsnwidth(const char *buf, size_t buflen, int flags)
+{
+       static int initialized;
+       mbstate_t ps;
+       int ret = 0;
+
+       if (!initialized) {
+               setlocale(LC_CTYPE, "");
+               initialized = 1;
+       }
+
+       memset(&ps, 0, sizeof ps);
+       while (buflen > 0) {
+               wchar_t wc;
+               size_t l;
+               int w;
+
+               l = mbrtowc(&wc, buf, buflen, &ps);
+               if (l == (size_t)-1 || l == (size_t)-2)
+                       return -1;
+               else if (l == 0)
+                       break;
+
+               buflen -= l;
+               buf += l;
+
+               w = wcwidth(wc);
+               if (w < 0)
+                       return -1;
+               ret += w;
+       }
+
+       return ret;
+}