aboutsummaryrefslogtreecommitdiffstats
path: root/common/stringhelp.c
diff options
context:
space:
mode:
authorWerner Koch <[email protected]>2025-11-18 14:54:47 +0000
committerWerner Koch <[email protected]>2025-11-18 14:54:47 +0000
commitbe9b1404e66157ac00bf3ae488ad2af1becffe25 (patch)
tree0bcadacebbe332986ad12154dc7ef5cd5452735e /common/stringhelp.c
parentgpg: Include ADSK keys in a key listing with fingerprints. (diff)
downloadgnupg-be9b1404e66157ac00bf3ae488ad2af1becffe25.tar.gz
gnupg-be9b1404e66157ac00bf3ae488ad2af1becffe25.zip
common: New function replace_substr.
* common/stringhelp.c (replace_substr): New. * common/t-stringhelp.c (test_replace_substr): New test.
Diffstat (limited to 'common/stringhelp.c')
-rw-r--r--common/stringhelp.c33
1 files changed, 32 insertions, 1 deletions
diff --git a/common/stringhelp.c b/common/stringhelp.c
index 9347c3551..8bbc68ab1 100644
--- a/common/stringhelp.c
+++ b/common/stringhelp.c
@@ -2,7 +2,7 @@
* Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
* 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright (C) 2014 Werner Koch
- * Copyright (C) 2015, 2021 g10 Code GmbH
+ * Copyright (C) 2015, 2021, 2025 g10 Code GmbH
*
* This file is part of GnuPG.
*
@@ -1721,6 +1721,37 @@ format_text (const char *text_in, int target_cols, int max_cols)
}
+/* In STRING replace the first occurance of SUBSTR by the string
+ * REPLACE. Return a new malloced string or set ERRNO and set NULL on
+ * error. If SUBSTR is not found a verbatim copy of STRING is
+ * returned. */
+char *
+replace_substr (const char *string, const char *substr, const char *replace)
+{
+ size_t stringlen, substrlen, replacelen, n;
+ const char *s;
+ char *buffer;
+
+ stringlen = strlen (string);
+ substrlen = strlen (substr);
+ replacelen = strlen (replace);
+
+ if (stringlen < substrlen || !(s = strstr (string, substr)))
+ return xtrystrdup (string);
+
+ stringlen -= substrlen; /* Found thus sryinglen >= substrlen */
+ buffer = xtrymalloc (stringlen + replacelen +1);
+ if (!buffer)
+ return NULL;
+ memcpy (buffer, string, n=(s-string));
+ memcpy (buffer+n, replace, replacelen);
+ strcpy (buffer+n+replacelen, s+substrlen);
+
+
+ return buffer;
+}
+
+
/* Substitute variables in STRING and return a new string. GETVAL is
* a function which maps NAME to its value; that value is a string
* which may not change during the execution time of this function.