aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/jsonwriter.h
blob: efafd17b987fa15ebb53a405f901d497c97c03f7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <vespa/vespalib/stllike/string.h>
#include <vector>
#include <memory>

namespace vespalib {

class asciistream;

/**
 * If you want a simpler interface to write JSON with, look at the JsonStream
 * class in the same directory as this class, this uses this class to make a
 * more user friendly writer.
 */
class JSONWriter {
private:
    enum State {
        INIT = 0,
        OBJECT,
        ARRAY
    };
    asciistream         * _os;
    std::vector<State>    _stack;
    bool                  _comma;
    bool                  _pretty;
    uint32_t              _indent;

    void push(State next);
    void pop(State expected);
    void considerComma();
    void updateCommaState();
    void quote(const char * str, size_t len);
    void indent();

public:
    JSONWriter();
    JSONWriter(asciistream & output);
    JSONWriter(const JSONWriter &) = delete;
    JSONWriter & operator = (const JSONWriter &) = delete;
    JSONWriter(JSONWriter &&) = default;
    JSONWriter & operator = (JSONWriter &&) = default;
    ~JSONWriter();

    JSONWriter & setOutputStream(asciistream & output);
    JSONWriter & clear();
    JSONWriter & beginObject();
    JSONWriter & endObject();
    JSONWriter & beginArray();
    JSONWriter & endArray();
    JSONWriter & appendNull();
    JSONWriter & appendKey(stringref str);
    JSONWriter & appendBool(bool v);
    JSONWriter & appendDouble(double v);
    JSONWriter & appendFloat(float v);
    JSONWriter & appendInt64(int64_t v);
    JSONWriter & appendUInt64(uint64_t v);
    JSONWriter & appendString(stringref str);
    JSONWriter & appendJSON(stringref json);

    void setPretty() { _pretty = true; };
};

class JSONStringer : public JSONWriter {
private:
    std::unique_ptr<asciistream> _oss;

public:
    JSONStringer();
    JSONStringer(JSONStringer &&) = default;
    JSONStringer & operator = (JSONStringer &&) = default;
    ~JSONStringer();
    JSONStringer & clear();
    stringref toString() const;
};

}