lib/string_helpers: Don't copy a tail in kstrdup_and_replace() if 'new' is \0
Subsystems (2)
PATCH 1/1 lib/string_helpers: Don't copy a tail in kstrdup_and_replace() if 'new' is \0
The kstrdup_and_replace() takes two characters, old and new, to replace former with latter after the copying of the original string. But in case when new is a NUL, there is no point to copy the rest of the string, the contract with the callers is that that the function returns a NUL-terminated string and not a buffer of the size filled with a given data. With this we can optimize the memory consumption by copying only meaningful part of the original string and drop the rest.
---
The first user of this is pending:
https://lore.kernel.org/platform-driver-x86/[email protected]/
lib/string_helpers.c | 6 ++++++ 1 file changed, 6 insertions(+)
lib/string_helpers.c +6 -0
@@ -723,11 +723,17 @@ EXPORT_SYMBOL_GPL(kstrdup_quotable_file);/* * Returns duplicate string in which the @old characters are replaced by @new. +* +* If @new is NUL, copy the string up to the first occurrence of @old, which +* will be replaced by a NUL. */ char *kstrdup_and_replace (const char *src,char old,char new,gfp_t gfp) {char *dst; +if (new =='\0' ) +return kmemdup_nul (src,strchrnul (src, old) - src, gfp); + dst =kstrdup (src, gfp);if (!dst)return NULL ;
Signature · 1 line
2.40.0.1.gaa8946217a0b
Quoted 7 lines · Andy Shevchenko
The
kstrdup_and_replace()takes two characters, old and new, to replace former with latter after the copying of the original string. But in case when new is a NUL, there is no point to copy the rest of the string, the contract with the callers is that that the function returns a NUL-terminated string and not a buffer of the size filled with a given data. With this we can optimize the memory consumption by copying only meaningful part of the original string and drop the rest.
Thinking about this more, I self NAK this.
If the caller knows the size of the original message it can be handy to make a copy and replace all occurrences of old by NUL. This will be an optimized implementation of strsep(str, "$OLD").
Signature · 2 lines
With Best Regards, Andy Shevchenko