Skip to content

Commit

Permalink
CRT_degreeSign code shrink
Browse files Browse the repository at this point in the history
Make "CRT_degreeSign" a writable buffer that will be updated after the
initDegreeSign() function. This avoids needing a static buffer in the
function.

Also use (MB_LEN_MAX + 1) for the buffer size, which is more
appropriate than the magic number 4.

One side effect of this change is that "CRT_degreeSign" will lose the
const qualifier in the header (CRT.h).

Signed-off-by: Kang-Che Sung <[email protected]>
  • Loading branch information
Explorer09 committed Feb 19, 2025
1 parent 658926e commit 15d95be
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
29 changes: 20 additions & 9 deletions CRT.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ in the source distribution for its full text.
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
Expand Down Expand Up @@ -94,21 +95,31 @@ const char* const* CRT_treeStr = CRT_treeStrAscii;

static const Settings* CRT_settings;

const char* CRT_degreeSign;
#ifdef HAVE_LIBNCURSESW
# if MB_LEN_MAX >= 3 // Minimum required to support UTF-8 BMP subset
char CRT_degreeSign[MB_LEN_MAX + 1] = "\xc2\xb0";
# else
char CRT_degreeSign[MB_LEN_MAX + 1] = "";
# endif
#else
char CRT_degreeSign[] = "";
#endif

static const char* initDegreeSign(void) {
static void initDegreeSign(void) {
#ifdef HAVE_LIBNCURSESW
# if MB_LEN_MAX >= 3
if (CRT_utf8)
return "\xc2\xb0";
return;
# endif

static char buffer[4];
// this might fail if the current locale does not support wide characters
int r = snprintf(buffer, sizeof(buffer), "%lc", 176);
if (r > 0)
return buffer;
int r = snprintf(CRT_degreeSign, sizeof(CRT_degreeSign), "%lc", 176);
if (r <= 0)
CRT_degreeSign[0] = '\0';
#endif

return "";
// No-op
return;
}

const int* CRT_colors;
Expand Down Expand Up @@ -1145,7 +1156,7 @@ IGNORE_WCASTQUAL_END

CRT_setMouse(settings->enableMouse);

CRT_degreeSign = initDegreeSign();
initDegreeSign();
}

void CRT_done(void) {
Expand Down
2 changes: 1 addition & 1 deletion CRT.h
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ void CRT_handleSIGSEGV(int signal) ATTR_NORETURN;
#define KEY_FOCUS_IN (KEY_MAX + 'I')
#define KEY_FOCUS_OUT (KEY_MAX + 'O')

extern const char* CRT_degreeSign;
extern char CRT_degreeSign[];

#ifdef HAVE_LIBNCURSESW

Expand Down

0 comments on commit 15d95be

Please sign in to comment.