chiark / gitweb /
json: fix a mem leak
[elogind.git] / src / shared / json.h
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 #pragma once
4
5 /***
6   This file is part of systemd.
7
8   Copyright 2014 Lennart Poettering
9
10   systemd is free software; you can redistribute it and/or modify it
11   under the terms of the GNU Lesser General Public License as published by
12   the Free Software Foundation; either version 2.1 of the License, or
13   (at your option) any later version.
14
15   systemd is distributed in the hope that it will be useful, but
16   WITHOUT ANY WARRANTY; without even the implied warranty of
17   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18   Lesser General Public License for more details.
19
20   You should have received a copy of the GNU Lesser General Public License
21   along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 ***/
23
24 #include <stdbool.h>
25 #include "util.h"
26
27 enum {
28         JSON_END,
29         JSON_COLON,
30         JSON_COMMA,
31         JSON_OBJECT_OPEN,
32         JSON_OBJECT_CLOSE,
33         JSON_ARRAY_OPEN,
34         JSON_ARRAY_CLOSE,
35         JSON_STRING,
36         JSON_REAL,
37         JSON_INTEGER,
38         JSON_BOOLEAN,
39         JSON_NULL,
40 };
41
42 typedef enum {
43         JSON_VARIANT_CONTROL,
44         JSON_VARIANT_STRING,
45         JSON_VARIANT_INTEGER,
46         JSON_VARIANT_BOOLEAN,
47         JSON_VARIANT_REAL,
48         JSON_VARIANT_ARRAY,
49         JSON_VARIANT_OBJECT,
50         JSON_VARIANT_NULL
51 } JsonVariantType;
52
53 union json_value {
54         bool boolean;
55         double real;
56         intmax_t integer;
57 };
58
59 typedef struct JsonVariant {
60         union {
61                 char *string;
62                 struct JsonVariant *objects;
63                 union json_value value;
64         };
65         JsonVariantType type;
66         unsigned size;
67 } JsonVariant;
68
69 int json_variant_new(JsonVariant **ret, JsonVariantType type);
70 JsonVariant *json_variant_unref(JsonVariant *);
71 DEFINE_TRIVIAL_CLEANUP_FUNC(JsonVariant *, json_variant_unref);
72 #define _cleanup_jsonunref_ _cleanup_(json_variant_unrefp)
73
74 char *json_variant_string(JsonVariant *);
75 bool json_variant_bool(JsonVariant *);
76 intmax_t json_variant_integer(JsonVariant *);
77 double json_variant_real(JsonVariant *);
78
79 JsonVariant *json_variant_element(JsonVariant *, unsigned index);
80 JsonVariant *json_variant_value(JsonVariant *, const char *key);
81
82 #define JSON_VALUE_NULL ((union json_value) {})
83
84 int json_tokenize(const char **p, char **ret_string, union json_value *ret_value, void **state, unsigned *line);
85 int json_parse(const char *string, JsonVariant **rv);
86 int json_parse_measure(const char *string, size_t *size);