lib: Fix a few bugs in trailing_strtoln()
authorSimon Glass <sjg@chromium.org>
Mon, 25 Apr 2022 05:30:57 +0000 (23:30 -0600)
committerTom Rini <trini@konsulko.com>
Mon, 25 Apr 2022 14:00:03 +0000 (10:00 -0400)
At present this has a minor bug in that it reads the byte before the
start of the string, if it is empty. Also it doesn't handle a
non-numeric prefix which is only one character long.

Fix these bugs with a reworked implementation. Add a test for the second
case. The first one is hard to test.

Signed-off-by: Simon Glass <sjg@chromium.org>
include/vsprintf.h
lib/strto.c
test/str_ut.c

index d4bf321..5172cee 100644 (file)
@@ -98,6 +98,9 @@ long long simple_strtoll(const char *cp, char **endp, unsigned int base);
  * Given a string this finds a trailing number on the string and returns it.
  * For example, "abc123" would return 123.
  *
+ * Note that this does not handle a string without a prefix. See dectoul() for
+ * that case.
+ *
  * @str:       String to examine
  * Return: trailing number if found, else -1
  */
index f191884..b1d803a 100644 (file)
@@ -189,11 +189,12 @@ long trailing_strtoln(const char *str, const char *end)
 
        if (!end)
                end = str + strlen(str);
-       if (isdigit(end[-1])) {
-               for (p = end - 1; p > str; p--) {
-                       if (!isdigit(*p))
-                               return dectoul(p + 1, NULL);
-               }
+       p = end - 1;
+       if (p > str && isdigit(*p)) {
+               do {
+                       if (!isdigit(p[-1]))
+                               return dectoul(p, NULL);
+               } while (--p > str);
        }
 
        return -1;
index 9674a59..058b359 100644 (file)
@@ -257,6 +257,8 @@ static int str_trailing(struct unit_test_state *uts)
        ut_asserteq(123, trailing_strtoln(str1, str1 + 6));
        ut_asserteq(-1, trailing_strtoln(str1, str1 + 9));
 
+       ut_asserteq(3, trailing_strtol("a3"));
+
        return 0;
 }
 STR_TEST(str_trailing, 0);