lib/string_helpers: Introduce kasprintf_strarray()
authorAndy Shevchenko <andriy.shevchenko@linux.intel.com>
Fri, 5 Nov 2021 12:42:24 +0000 (14:42 +0200)
committerAndy Shevchenko <andriy.shevchenko@linux.intel.com>
Thu, 18 Nov 2021 16:40:08 +0000 (18:40 +0200)
We have a few users already that basically want to have array of
sequential strings to be allocated and filled.

Provide a helper for them (basically adjusted version from gpio-mockup.c).

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Reviewed-by: Linus Walleij <linus.walleij@linaro.org>
include/linux/string_helpers.h
lib/string_helpers.c

index 4ba39e1..f67a940 100644 (file)
@@ -100,6 +100,7 @@ char *kstrdup_quotable(const char *src, gfp_t gfp);
 char *kstrdup_quotable_cmdline(struct task_struct *task, gfp_t gfp);
 char *kstrdup_quotable_file(struct file *file, gfp_t gfp);
 
+char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n);
 void kfree_strarray(char **array, size_t n);
 
 #endif
index d5d008f..9758997 100644 (file)
@@ -675,6 +675,39 @@ char *kstrdup_quotable_file(struct file *file, gfp_t gfp)
 EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
 
 /**
+ * kasprintf_strarray - allocate and fill array of sequential strings
+ * @gfp: flags for the slab allocator
+ * @prefix: prefix to be used
+ * @n: amount of lines to be allocated and filled
+ *
+ * Allocates and fills @n strings using pattern "%s-%zu", where prefix
+ * is provided by caller. The caller is responsible to free them with
+ * kfree_strarray() after use.
+ *
+ * Returns array of strings or NULL when memory can't be allocated.
+ */
+char **kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
+{
+       char **names;
+       size_t i;
+
+       names = kcalloc(n + 1, sizeof(char *), gfp);
+       if (!names)
+               return NULL;
+
+       for (i = 0; i < n; i++) {
+               names[i] = kasprintf(gfp, "%s-%zu", prefix, i);
+               if (!names[i]) {
+                       kfree_strarray(names, i);
+                       return NULL;
+               }
+       }
+
+       return names;
+}
+EXPORT_SYMBOL_GPL(kasprintf_strarray);
+
+/**
  * kfree_strarray - free a number of dynamically allocated strings contained
  *                  in an array and the array itself
  *