diff mbox series

[3/5] util: add function to get a substring from a string

Message ID 20190624092712.13143-3-sbabic@denx.de
State Accepted
Headers show
Series None | expand

Commit Message

Stefano Babic June 24, 2019, 9:27 a.m. UTC
substring(string, len)

Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 core/util.c    | 22 ++++++++++++++++++++++
 include/util.h |  1 +
 2 files changed, 23 insertions(+)
diff mbox series

Patch

diff --git a/core/util.c b/core/util.c
index ea4ad8a..2855b4f 100644
--- a/core/util.c
+++ b/core/util.c
@@ -171,6 +171,28 @@  char *mstrcat(const char **nodes, const char *delim)
 	return dest;
 }
 
+/*
+ * Alocate and return a string as part of
+ * another string
+ * s = substring(src, n)
+ * the returned string is allocated on the heap
+ * and must be freed by the caller
+ */
+char *substring(const char *src, int first, int len) {
+	char *s;
+	if (len > strlen(src))
+		len = strlen(src);
+	if (first > len)
+		return NULL;
+	s = malloc(len + 1);
+	if (!s)
+		return NULL;
+	memcpy(s, &src[first], len);
+	s[len] = '\0';
+	return s;
+}
+
+
 int openfileoutput(const char *filename)
 {
 	int fdout;
diff --git a/include/util.h b/include/util.h
index 445e9f2..4ec0b8d 100644
--- a/include/util.h
+++ b/include/util.h
@@ -181,6 +181,7 @@  int syslog_init(void);
 char **splitargs(char *args, int *argc);
 char *mstrcat(const char **nodes, const char *delim);
 char** string_split(const char* a_str, const char a_delim);
+char *substring(const char *src, int first, int len);
 void freeargs (char **argv);
 int get_hw_revision(struct hw_type *hw);
 void get_sw_versions(char *cfgfname, struct swupdate_cfg *sw);