qnum.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #ifndef QNUM_H
  15. #define QNUM_H
  16. #include "qobject/qobject.h"
  17. typedef enum {
  18. QNUM_I64,
  19. QNUM_U64,
  20. QNUM_DOUBLE
  21. } QNumKind;
  22. /*
  23. * QNum encapsulates how our dialect of JSON fills in the blanks left
  24. * by the JSON specification (RFC 8259) regarding numbers.
  25. *
  26. * Conceptually, we treat number as an abstract type with three
  27. * concrete subtypes: floating-point, signed integer, unsigned
  28. * integer. QNum implements this as a discriminated union of double,
  29. * int64_t, uint64_t.
  30. *
  31. * The JSON parser picks the subtype as follows. If the number has a
  32. * decimal point or an exponent, it is floating-point. Else if it
  33. * fits into int64_t, it's signed integer. Else if it fits into
  34. * uint64_t, it's unsigned integer. Else it's floating-point.
  35. *
  36. * Any number can serve as double: qnum_get_double() converts under
  37. * the hood.
  38. *
  39. * An integer can serve as signed / unsigned integer as long as it is
  40. * in range: qnum_get_try_int() / qnum_get_try_uint() check range and
  41. * convert under the hood.
  42. */
  43. struct QNum {
  44. struct QObjectBase_ base;
  45. QNumKind kind;
  46. union {
  47. int64_t i64;
  48. uint64_t u64;
  49. double dbl;
  50. } u;
  51. };
  52. void qnum_unref(QNum *q);
  53. G_DEFINE_AUTOPTR_CLEANUP_FUNC(QNum, qnum_unref)
  54. QNum *qnum_from_int(int64_t value);
  55. QNum *qnum_from_uint(uint64_t value);
  56. QNum *qnum_from_double(double value);
  57. bool qnum_get_try_int(const QNum *qn, int64_t *val);
  58. int64_t qnum_get_int(const QNum *qn);
  59. bool qnum_get_try_uint(const QNum *qn, uint64_t *val);
  60. uint64_t qnum_get_uint(const QNum *qn);
  61. double qnum_get_double(QNum *qn);
  62. char *qnum_to_string(QNum *qn);
  63. #endif /* QNUM_H */