[PATCH v2 01/41] lib: Add a way to find the postiion of a trailing number

Simon Glass sjg at chromium.org
Sun Oct 24 01:25:55 CEST 2021


At present it is not possible to find out which part of the string is the
number part and which is before it. Add a new variant which provides this
feature, so we can separate the two in the caller.

Signed-off-by: Simon Glass <sjg at chromium.org>
---

(no changes since v1)

 include/vsprintf.h | 18 ++++++++++++++++++
 lib/strto.c        | 14 ++++++++++++--
 2 files changed, 30 insertions(+), 2 deletions(-)

diff --git a/include/vsprintf.h b/include/vsprintf.h
index b4746301462..8230e7a5126 100644
--- a/include/vsprintf.h
+++ b/include/vsprintf.h
@@ -118,6 +118,24 @@ long trailing_strtol(const char *str);
  */
 long trailing_strtoln(const char *str, const char *end);
 
+/**
+ * trailing_strtoln() - extract a trailing integer from a fixed-length string
+ *
+ * Given a fixed-length string this finds a trailing number on the string
+ * and returns it. For example, "abc123" would return 123. Only the
+ * characters between @str and @end - 1 are examined. If @end is NULL, it is
+ * set to str + strlen(str).
+ *
+ * @str:	String to exxamine
+ * @end:	Pointer to end of string to examine, or NULL to use the
+ *		whole string
+ * @lenp:	If non-NULL, this is set to the number of characters before the
+ *	number starts, e.g. for "mmc0" this would be 3; if no trailing number is
+ *	found, it is set to the length of the whole string
+ * @return training number if found, else -1
+ */
+long trailing_strtoln_len(const char *str, const char *end, int *lenp);
+
 /**
  * panic() - Print a message and reset/hang
  *
diff --git a/lib/strto.c b/lib/strto.c
index 7bba1e3e549..13ae22a87a1 100644
--- a/lib/strto.c
+++ b/lib/strto.c
@@ -183,7 +183,7 @@ long long simple_strtoll(const char *cp, char **endp, unsigned int base)
 	return simple_strtoull(cp, endp, base);
 }
 
-long trailing_strtoln(const char *str, const char *end)
+long trailing_strtoln_len(const char *str, const char *end, int *lenp)
 {
 	const char *p;
 
@@ -191,14 +191,24 @@ long trailing_strtoln(const char *str, const char *end)
 		end = str + strlen(str);
 	if (isdigit(end[-1])) {
 		for (p = end - 1; p > str; p--) {
-			if (!isdigit(*p))
+			if (!isdigit(*p)) {
+				if (lenp)
+					*lenp = p - str + 1;
 				return dectoul(p + 1, NULL);
+			}
 		}
 	}
+	if (lenp)
+		*lenp = end - str;
 
 	return -1;
 }
 
+long trailing_strtoln(const char *str, const char *end)
+{
+	return trailing_strtoln_len(str, end, NULL);
+}
+
 long trailing_strtol(const char *str)
 {
 	return trailing_strtoln(str, NULL);
-- 
2.33.0.1079.g6e70778dc9-goog



More information about the U-Boot mailing list