qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Qemu-devel] [PATCH v4 02/14] qapi: Move to_c_string() to common.py


From: Max Reitz
Subject: [Qemu-devel] [PATCH v4 02/14] qapi: Move to_c_string() to common.py
Date: Mon, 24 Jun 2019 19:39:22 +0200

This function will be useful for code generation once we allow default
values, so move it to the other "C helper functions".  In the process,
rewrite it so it supports all nonprintable and non-ASCII characters.

Signed-off-by: Max Reitz <address@hidden>
---
 scripts/qapi/common.py     | 26 ++++++++++++++++++++++++++
 scripts/qapi/introspect.py |  4 ----
 2 files changed, 26 insertions(+), 4 deletions(-)

diff --git a/scripts/qapi/common.py b/scripts/qapi/common.py
index 3396ea4a09..c6754a5856 100644
--- a/scripts/qapi/common.py
+++ b/scripts/qapi/common.py
@@ -2208,6 +2208,32 @@ def c_fname(filename):
     return re.sub(r'[^A-Za-z0-9_]', '_', filename)
 
 
+# Translates a string to a valid C constant
+def to_c_string(string):
+    result = '"'
+
+    python2 = isinstance(string, bytes)
+    if not python2:
+        # Will return integers when iterated over
+        string = string.encode()
+
+    for c in string:
+        value = ord(c) if python2 else c
+        if value < 0x20 or value > 0x7e:
+            result += '\\%03o' % value
+        else:
+            c = chr(value)
+            if c == '"':
+                result += '\\"'
+            elif c == '\\':
+                result += '\\\\'
+            else:
+                result += c
+
+    result += '"'
+    return result
+
+
 def guardstart(name):
     return mcgen('''
 #ifndef %(name)s
diff --git a/scripts/qapi/introspect.py b/scripts/qapi/introspect.py
index 6a61dd831f..572e0b8331 100644
--- a/scripts/qapi/introspect.py
+++ b/scripts/qapi/introspect.py
@@ -66,10 +66,6 @@ def to_qlit(obj, level=0, suppress_first_indent=False):
     return ret
 
 
-def to_c_string(string):
-    return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
-
-
 class QAPISchemaGenIntrospectVisitor(QAPISchemaMonolithicCVisitor):
 
     def __init__(self, prefix, unmask):
-- 
2.21.0




reply via email to

[Prev in Thread] Current Thread [Next in Thread]