Implemented left-justification in SDL_PrintString()

Fixes https://github.com/libsdl-org/SDL/issues/10310
This commit is contained in:
Sam Lantinga 2024-08-04 19:21:06 -07:00
parent 6212497ea3
commit f59d66f4b1
2 changed files with 29 additions and 9 deletions

View File

@ -1796,7 +1796,7 @@ typedef enum
typedef struct
{
SDL_bool left_justify; /* for now: ignored. */
SDL_bool left_justify;
SDL_bool force_sign;
SDL_bool force_type; /* for now: used only by float printer, ignored otherwise. */
SDL_bool pad_zeroes;
@ -1808,6 +1808,9 @@ typedef struct
static size_t SDL_PrintString(char *text, size_t maxlen, SDL_FormatInfo *info, const char *string)
{
const char fill = (info && info->pad_zeroes) ? '0' : ' ';
size_t width = 0;
size_t filllen = 0;
size_t length = 0;
size_t slen, sz;
@ -1817,24 +1820,29 @@ static size_t SDL_PrintString(char *text, size_t maxlen, SDL_FormatInfo *info, c
sz = SDL_strlen(string);
if (info && info->width > 0 && (size_t)info->width > sz) {
const char fill = info->pad_zeroes ? '0' : ' ';
size_t width = info->width - sz;
size_t filllen;
width = info->width - sz;
if (info->precision >= 0 && (size_t)info->precision < sz) {
width += sz - (size_t)info->precision;
}
filllen = SDL_min(width, maxlen);
SDL_memset(text, fill, filllen);
text += filllen;
maxlen -= filllen;
length += width;
if (!info->left_justify) {
SDL_memset(text, fill, filllen);
text += filllen;
maxlen -= filllen;
length += width;
filllen = 0;
}
}
SDL_strlcpy(text, string, maxlen);
length += sz;
if (filllen > 0) {
SDL_memset(text + sz, fill, filllen);
length += width;
}
if (info) {
if (info->precision >= 0 && (size_t)info->precision < sz) {
slen = (size_t)info->precision;

View File

@ -150,6 +150,18 @@ static int stdlib_snprintf(void *arg)
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int)SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%10sA", "foo");
expected = " fooA";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%10sA\", \"foo\")");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int)SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%-10sA", "foo");
expected = "foo A";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%-10sA\", \"foo\")");
SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
SDLTest_AssertCheck(result == SDL_strlen(text), "Check result value, expected: %d, got: %d", (int)SDL_strlen(text), result);
result = SDL_snprintf(text, sizeof(text), "%S", L"foo");
expected = "foo";
SDLTest_AssertPass("Call to SDL_snprintf(\"%%S\", \"foo\")");