Skip to contentSkip to conversation

block: Use a GString in bdrv_perm_names()

PATCH Applied Alberto Garcia 4 participants 4 messages Jan 10, 2020 – Jan 14, 2020

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 block: Use a GString in bdrv_perm_names()

This is a bit more efficient than having to allocate and free memory for each new permission.

The default size (30) is enough for "consistent read, write, resize".

---
 block.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
block.c +6 -5
index 1b6f7c86e8..2bc9e58392 100644
@@ -1976,18 +1976,19 @@ char *bdrv_perm_names(uint64_t perm)
         { 0, NULL }
     };
 
-    char *result = g_strdup("");
+    GString *result = g_string_sized_new(30);
     struct perm_name *p;
 
     for (p = permissions; p->name; p++) {
         if (perm & p->perm) {
-            char *old = result;
-            result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
-            g_free(old);
+            if (result->len > 0) {
+                g_string_append(result, ", ");
+            }
+            g_string_append(result, p->name);
         }
     }
 
-    return result;
+    return g_string_free(result, FALSE);
 }
 
 /*
Signature · 1 line
2.20.1
Reviewed-by on v1 1/1
#1 lore raw
Quoted 10 lines · Alberto Garcia

This is a bit more efficient than having to allocate and free memory for each new permission.

The default size (30) is enough for "consistent read, write, resize".

---
  block.c | 11 ++++++-----
  1 file changed, 6 insertions(+), 5 deletions(-)
Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization:  qemu.org | libvirt.org
#3 lore raw
In reply to Alberto Garcia
Quoted 27 lines · Alberto Garcia

This is a bit more efficient than having to allocate and free memory for each new permission.

The default size (30) is enough for "consistent read, write, resize".

---
  block.c | 11 ++++++-----
  1 file changed, 6 insertions(+), 5 deletions(-)
block.c +1 -4
index 1b6f7c86e8..2bc9e58392 100644
@@ -1976,18 +1976,19 @@ char *bdrv_perm_names(uint64_t perm)
          { 0, NULL }
      };
 
-    char *result = g_strdup("");
+    GString *result = g_string_sized_new(30);
      struct perm_name *p;
 
      for (p = permissions; p->name; p++) {
          if (perm & p->perm) {
-            char *old = result;
-            result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
-            g_free(old);

block.c char *bdrv_perm_names(uint64_t perm) · line 1992

Quoted 10 lines
block.c +5 -1
+            if (result->len > 0) {
+                g_string_append(result, ", ");
+            }
+            g_string_append(result, p->name);
          }
      }
 
-    return result;
+    return g_string_free(result, FALSE);
  }

Maybe similar cleanup can be done to report_unsupported_feature() in block/qcow2.c.