From d6fb797b11aa6dd031032faf425be3ce5a69661d Mon Sep 17 00:00:00 2001 From: Curtis McEnroe Date: Mon, 6 Aug 2018 14:19:52 -0400 Subject: Use wchar_t strings for all of UI vaswprintf is a nightmare. --- pls.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 pls.c (limited to 'pls.c') diff --git a/pls.c b/pls.c new file mode 100644 index 0000000..bd40dbd --- /dev/null +++ b/pls.c @@ -0,0 +1,67 @@ +/* Copyright (C) 2018 Curtis McEnroe + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +wchar_t *wcssep(wchar_t **stringp, const wchar_t *delim) { + wchar_t *orig = *stringp; + if (!orig) return NULL; + size_t i = wcscspn(orig, delim); + *stringp = NULL; + if (orig[i]) { + orig[i] = '\0'; + *stringp = &orig[i + 1]; + } + return orig; +} + +// From : +// +// While narrow strings provide snprintf, which makes it possible to determine +// the required output buffer size, there is no equivalent for wide strings +// (until C11's snwprintf_s), and in order to determine the buffer size, the +// program may need to call swprintf, check the result value, and reallocate a +// larger buffer, trying again until successful. +// +// snwprintf_s, unlike swprintf_s, will truncate the result to fit within the +// array pointed to by buffer, even though truncation is treated as an error by +// most bounds-checked functions. +int vaswprintf(wchar_t **ret, const wchar_t *format, va_list ap) { + *ret = NULL; + + for (size_t cap = 2 * wcslen(format);; cap *= 2) { + wchar_t *buf = realloc(*ret, 1 + cap); + if (!buf) goto fail; + *ret = buf; + + va_list _ap; + va_copy(_ap, ap); + int len = vswprintf(*ret, 1 + cap, format, _ap); + va_end(_ap); + + if (len >= 0) return len; + if (errno != EOVERFLOW) goto fail; + } + +fail: + free(*ret); + *ret = NULL; + return -1; +} -- cgit 1.4.1