xref: /openbmc/qemu/include/qapi/qmp/qnum.h (revision d30b5bc9)
1 /*
2  * QNum Module
3  *
4  * Copyright (C) 2009 Red Hat Inc.
5  *
6  * Authors:
7  *  Luiz Capitulino <lcapitulino@redhat.com>
8  *  Anthony Liguori <aliguori@us.ibm.com>
9  *  Marc-André Lureau <marcandre.lureau@redhat.com>
10  *
11  * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
12  * See the COPYING.LIB file in the top-level directory.
13  */
14 
15 #ifndef QNUM_H
16 #define QNUM_H
17 
18 #include "qapi/qmp/qobject.h"
19 
20 typedef enum {
21     QNUM_I64,
22     QNUM_U64,
23     QNUM_DOUBLE
24 } QNumKind;
25 
26 /*
27  * QNum encapsulates how our dialect of JSON fills in the blanks left
28  * by the JSON specification (RFC 8259) regarding numbers.
29  *
30  * Conceptually, we treat number as an abstract type with three
31  * concrete subtypes: floating-point, signed integer, unsigned
32  * integer.  QNum implements this as a discriminated union of double,
33  * int64_t, uint64_t.
34  *
35  * The JSON parser picks the subtype as follows.  If the number has a
36  * decimal point or an exponent, it is floating-point.  Else if it
37  * fits into int64_t, it's signed integer.  Else if it fits into
38  * uint64_t, it's unsigned integer.  Else it's floating-point.
39  *
40  * Any number can serve as double: qnum_get_double() converts under
41  * the hood.
42  *
43  * An integer can serve as signed / unsigned integer as long as it is
44  * in range: qnum_get_try_int() / qnum_get_try_uint() check range and
45  * convert under the hood.
46  */
47 struct QNum {
48     struct QObjectBase_ base;
49     QNumKind kind;
50     union {
51         int64_t i64;
52         uint64_t u64;
53         double dbl;
54     } u;
55 };
56 
57 void qnum_unref(QNum *q);
58 
59 G_DEFINE_AUTOPTR_CLEANUP_FUNC(QNum, qnum_unref)
60 
61 QNum *qnum_from_int(int64_t value);
62 QNum *qnum_from_uint(uint64_t value);
63 QNum *qnum_from_double(double value);
64 
65 bool qnum_get_try_int(const QNum *qn, int64_t *val);
66 int64_t qnum_get_int(const QNum *qn);
67 
68 bool qnum_get_try_uint(const QNum *qn, uint64_t *val);
69 uint64_t qnum_get_uint(const QNum *qn);
70 
71 double qnum_get_double(QNum *qn);
72 
73 char *qnum_to_string(QNum *qn);
74 
75 #endif /* QNUM_H */
76