[Mesa-dev] [PATCH 7/8] util/ralloc: add ralloc_str_append() helper

Timothy Arceri tarceri at itsqueeze.com
Mon Aug 7 02:18:24 UTC 2017


This function differs from ralloc_strcat() and ralloc_strncat()
in that it  does not do any strlen() calls which can become
costly on large strings.
---
 src/util/ralloc.c | 17 +++++++++++++++++
 src/util/ralloc.h | 18 ++++++++++++++++++
 2 files changed, 35 insertions(+)

diff --git a/src/util/ralloc.c b/src/util/ralloc.c
index 821ee72fe8..b2b0315e65 100644
--- a/src/util/ralloc.c
+++ b/src/util/ralloc.c
@@ -396,20 +396,37 @@ ralloc_strcat(char **dest, const char *str)
 {
    return cat(dest, str, strlen(str));
 }
 
 bool
 ralloc_strncat(char **dest, const char *str, size_t n)
 {
    return cat(dest, str, strnlen(str, n));
 }
 
+bool
+ralloc_str_append(char **dest, size_t existing_length, const char *str,
+                  size_t n)
+{
+   char *both;
+   assert(dest != NULL && *dest != NULL);
+
+   both = resize(*dest, existing_length + n + 1);
+   if (unlikely(both == NULL))
+      return false;
+
+   memcpy(both + existing_length, str, n);
+   both[existing_length + n] = '\0';
+
+   *dest = both;
+}
+
 char *
 ralloc_asprintf(const void *ctx, const char *fmt, ...)
 {
    char *ptr;
    va_list args;
    va_start(args, fmt);
    ptr = ralloc_vasprintf(ctx, fmt, args);
    va_end(args);
    return ptr;
 }
diff --git a/src/util/ralloc.h b/src/util/ralloc.h
index 7d90651966..f2d3d3671e 100644
--- a/src/util/ralloc.h
+++ b/src/util/ralloc.h
@@ -286,20 +286,38 @@ bool ralloc_strcat(char **dest, const char *str);
  * new pointer unless allocation fails.
  *
  * The result will always be null-terminated; \p str does not need to be null
  * terminated if it is longer than \p n.
  *
  * \return True unless allocation failed.
  */
 bool ralloc_strncat(char **dest, const char *str, size_t n);
 
 /**
+ * Concatenate two strings, allocating the necessary space.
+ *
+ * This appends \p n bytes of \p str to \p *dest, using ralloc_resize
+ * to expand \p *dest to the appropriate size.  \p dest will be updated to the
+ * new pointer unless allocation fails.
+ *
+ * The result will always be null-terminated.
+ *
+ * This function differs from ralloc_strcat() and ralloc_strncat() in that it
+ * does not do any strlen() calls which can become costly on large strings.
+ *
+ * \return True unless allocation failed.
+ */
+bool
+ralloc_str_append(char **dest, size_t existing_length, const char *str,
+                  size_t n);
+
+/**
  * Print to a string.
  *
  * This is analogous to \c sprintf, but allocates enough space (using \p ctx
  * as the context) for the resulting string.
  *
  * \return The newly allocated string.
  */
 char *ralloc_asprintf (const void *ctx, const char *fmt, ...) PRINTFLIKE(2, 3) MALLOCLIKE;
 
 /**
-- 
2.13.3



More information about the mesa-dev mailing list