Merge remote-tracking branch 'remotes/quic/tags/pull-hex-20210725' into staging
[qemu.git] / qapi / qapi-util.c
blob3c24bb3d4548c2f1740078dea3bf5b7cb3f5cf16
1 /*
2 * QAPI util functions
4 * Authors:
5 * Hu Tao <hutao@cn.fujitsu.com>
6 * Peter Lieven <pl@kamp.de>
7 *
8 * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
9 * See the COPYING.LIB file in the top-level directory.
13 #include "qemu/osdep.h"
14 #include "qapi/error.h"
15 #include "qemu/ctype.h"
16 #include "qapi/qmp/qerror.h"
18 const char *qapi_enum_lookup(const QEnumLookup *lookup, int val)
20 assert(val >= 0 && val < lookup->size);
22 return lookup->array[val];
25 int qapi_enum_parse(const QEnumLookup *lookup, const char *buf,
26 int def, Error **errp)
28 int i;
30 if (!buf) {
31 return def;
34 for (i = 0; i < lookup->size; i++) {
35 if (!strcmp(buf, lookup->array[i])) {
36 return i;
40 error_setg(errp, "invalid parameter value: %s", buf);
41 return def;
44 bool qapi_bool_parse(const char *name, const char *value, bool *obj, Error **errp)
46 if (g_str_equal(value, "on") ||
47 g_str_equal(value, "yes") ||
48 g_str_equal(value, "true") ||
49 g_str_equal(value, "y")) {
50 *obj = true;
51 return true;
53 if (g_str_equal(value, "off") ||
54 g_str_equal(value, "no") ||
55 g_str_equal(value, "false") ||
56 g_str_equal(value, "n")) {
57 *obj = false;
58 return true;
61 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, name,
62 "'on' or 'off'");
63 return false;
67 * Parse a valid QAPI name from @str.
68 * A valid name consists of letters, digits, hyphen and underscore.
69 * It may be prefixed by __RFQDN_ (downstream extension), where RFQDN
70 * may contain only letters, digits, hyphen and period.
71 * The special exception for enumeration names is not implemented.
72 * See docs/devel/qapi-code-gen.txt for more on QAPI naming rules.
73 * Keep this consistent with scripts/qapi.py!
74 * If @complete, the parse fails unless it consumes @str completely.
75 * Return its length on success, -1 on failure.
77 int parse_qapi_name(const char *str, bool complete)
79 const char *p = str;
81 if (*p == '_') { /* Downstream __RFQDN_ */
82 p++;
83 if (*p != '_') {
84 return -1;
86 while (*++p) {
87 if (!qemu_isalnum(*p) && *p != '-' && *p != '.') {
88 break;
92 if (*p != '_') {
93 return -1;
95 p++;
98 if (!qemu_isalpha(*p)) {
99 return -1;
101 while (*++p) {
102 if (!qemu_isalnum(*p) && *p != '-' && *p != '_') {
103 break;
107 if (complete && *p) {
108 return -1;
110 return p - str;