From 795b0ca8d46c9a697fac1eec472a091a55f5676e Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 19 Jun 2023 01:05:32 +0200 Subject: [PATCH] libc/scanf: Some refactoring --- libc/src/scanf.cpp | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/libc/src/scanf.cpp b/libc/src/scanf.cpp index 472b99b5..acb9d7a5 100644 --- a/libc/src/scanf.cpp +++ b/libc/src/scanf.cpp @@ -108,6 +108,13 @@ static void write_parsed_unsigned_integer(size_t value, int flags, va_list ap) *va_arg(ap, unsigned int*) = (unsigned int)value; } +#define WHITESPACE_CHARACTERS " \t\f\r\n\v" + +static void skip_whitespace(const char** str) +{ + *str += strspn(*str, WHITESPACE_CHARACTERS); +} + extern "C" { int vsscanf(const char* str, const char* format, va_list ap) @@ -131,8 +138,8 @@ extern "C" continue; } - format += strspn(format, " \t\f\r\n\v"); - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&format); + skip_whitespace(&str); if (*str == 0) return parsed; continue; } @@ -141,7 +148,7 @@ extern "C" format++; if (*format == '%') { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); goto normal; } @@ -154,8 +161,8 @@ extern "C" switch (specifier) { case 's': { - str += strspn(str, " \t\f\r\n\v"); - size_t chars = strcspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); + size_t chars = strcspn(str, WHITESPACE_CHARACTERS); if (!chars) return parsed; if ((flags & FLAG_WIDTH) && chars > width) chars = width; if (!(flags & FLAG_DISCARD)) @@ -197,28 +204,28 @@ extern "C" break; } case 'd': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); ssize_t value = scan_signed_integer(&str, 10); if (!(flags & FLAG_DISCARD)) write_parsed_signed_integer(value, flags, ap); parsed++; break; } case 'i': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); ssize_t value = scan_signed_integer(&str, 0); if (!(flags & FLAG_DISCARD)) write_parsed_signed_integer(value, flags, ap); parsed++; break; } case 'o': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); size_t value = scan_unsigned_integer(&str, 8); if (!(flags & FLAG_DISCARD)) write_parsed_unsigned_integer(value, flags, ap); parsed++; break; } case 'u': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); size_t value = scan_unsigned_integer(&str, 10); if (!(flags & FLAG_DISCARD)) write_parsed_unsigned_integer(value, flags, ap); parsed++; @@ -226,14 +233,14 @@ extern "C" } case 'X': case 'x': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); size_t value = scan_unsigned_integer(&str, 16); if (!(flags & FLAG_DISCARD)) write_parsed_unsigned_integer(value, flags, ap); parsed++; break; } case 'p': { - str += strspn(str, " \t\f\r\n\v"); + skip_whitespace(&str); size_t value = scan_unsigned_integer(&str, 16); if (!(flags & FLAG_DISCARD)) *va_arg(ap, void**) = (void*)value; parsed++;