2 * String printing Visitor
4 * Copyright Red Hat, Inc. 2012
6 * Author: Paolo Bonzini <pbonzini@redhat.com>
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-common.h"
14 #include "qapi/string-output-visitor.h"
15 #include "qapi/visitor-impl.h"
16 #include "qapi/qmp/qerror.h"
17 #include "qemu/host-utils.h"
20 struct StringOutputVisitor
27 static void string_output_set(StringOutputVisitor
*sov
, char *string
)
33 static void print_type_int(Visitor
*v
, int64_t *obj
, const char *name
,
36 StringOutputVisitor
*sov
= DO_UPCAST(StringOutputVisitor
, visitor
, v
);
40 out
= g_strdup_printf("%lld (%#llx)", (long long) *obj
, (long long) *obj
);
42 out
= g_strdup_printf("%lld", (long long) *obj
);
44 string_output_set(sov
, out
);
47 static void print_type_size(Visitor
*v
, uint64_t *obj
, const char *name
,
50 StringOutputVisitor
*sov
= DO_UPCAST(StringOutputVisitor
, visitor
, v
);
51 static const char suffixes
[] = { 'B', 'K', 'M', 'G', 'T', 'P', 'E' };
57 out
= g_strdup_printf("%"PRIu64
, *obj
);
58 string_output_set(sov
, out
);
64 /* The exponent (returned in i) minus one gives us
65 * floor(log2(val * 1024 / 1000). The correction makes us
66 * switch to the higher power when the integer part is >= 1000.
68 frexp(val
/ (1000.0 / 1024.0), &i
);
70 assert(i
< ARRAY_SIZE(suffixes
));
71 div
= 1ULL << (i
* 10);
73 out
= g_strdup_printf("%"PRIu64
" (%0.3g %c%s)", val
,
74 (double)val
/div
, suffixes
[i
], i
? "iB" : "");
75 string_output_set(sov
, out
);
78 static void print_type_bool(Visitor
*v
, bool *obj
, const char *name
,
81 StringOutputVisitor
*sov
= DO_UPCAST(StringOutputVisitor
, visitor
, v
);
82 string_output_set(sov
, g_strdup(*obj
? "true" : "false"));
85 static void print_type_str(Visitor
*v
, char **obj
, const char *name
,
88 StringOutputVisitor
*sov
= DO_UPCAST(StringOutputVisitor
, visitor
, v
);
92 out
= *obj
? g_strdup_printf("\"%s\"", *obj
) : g_strdup("<null>");
94 out
= g_strdup(*obj
? *obj
: "");
96 string_output_set(sov
, out
);
99 static void print_type_number(Visitor
*v
, double *obj
, const char *name
,
102 StringOutputVisitor
*sov
= DO_UPCAST(StringOutputVisitor
, visitor
, v
);
103 string_output_set(sov
, g_strdup_printf("%f", *obj
));
106 char *string_output_get_string(StringOutputVisitor
*sov
)
108 char *string
= sov
->string
;
113 Visitor
*string_output_get_visitor(StringOutputVisitor
*sov
)
115 return &sov
->visitor
;
118 void string_output_visitor_cleanup(StringOutputVisitor
*sov
)
124 StringOutputVisitor
*string_output_visitor_new(bool human
)
126 StringOutputVisitor
*v
;
128 v
= g_malloc0(sizeof(*v
));
131 v
->visitor
.type_enum
= output_type_enum
;
132 v
->visitor
.type_int
= print_type_int
;
133 v
->visitor
.type_size
= print_type_size
;
134 v
->visitor
.type_bool
= print_type_bool
;
135 v
->visitor
.type_str
= print_type_str
;
136 v
->visitor
.type_number
= print_type_number
;