ppsspp/Common/Data/Format/JSONWriter.h

89 lines
2.1 KiB
C
Raw Normal View History

2012-03-31 11:16:13 +02:00
// Minimal-state JSON writer. Consumes almost no memory
2012-03-24 23:39:19 +01:00
// apart from the string being built-up, which could easily be replaced
// with a file stream (although I've chosen not to do that just yet).
//
2012-03-31 11:16:13 +02:00
// Writes nicely 2-space indented output with correct comma-placement
2012-03-27 23:25:04 +02:00
// in arrays and dictionaries.
//
// Does not deal with encodings in any way.
//
// Zero dependencies apart from stdlib (if you remove the vhjson usage.)
2012-03-24 23:39:19 +01:00
#include <string>
#include <vector>
#include <sstream>
struct JsonNode;
namespace json {
2012-03-24 23:39:19 +01:00
class JsonWriter {
2012-05-08 22:04:24 +02:00
public:
JsonWriter(int flags = NORMAL);
2012-10-30 13:20:55 +01:00
~JsonWriter();
void begin();
void beginArray();
void beginRaw();
2012-10-30 13:20:55 +01:00
void end();
void pushDict();
void pushDict(const std::string &name);
void pushArray();
void pushArray(const std::string &name);
2012-10-30 13:20:55 +01:00
void pop();
void writeBool(bool value);
void writeBool(const std::string &name, bool value);
2012-10-30 13:20:55 +01:00
void writeInt(int value);
void writeInt(const std::string &name, int value);
void writeUint(uint32_t value);
void writeUint(const std::string &name, uint32_t value);
2012-10-30 13:20:55 +01:00
void writeFloat(double value);
void writeFloat(const std::string &name, double value);
void writeString(const std::string &value);
void writeString(const std::string &name, const std::string &value);
void writeRaw(const std::string &value);
void writeRaw(const std::string &name, const std::string &value);
void writeNull();
void writeNull(const std::string &name);
2012-03-24 23:39:19 +01:00
2012-10-30 13:20:55 +01:00
std::string str() const {
return str_.str();
}
2012-03-24 23:39:19 +01:00
std::string flush() {
std::string result = str_.str();
str_.str("");
return result;
}
enum {
NORMAL = 0,
PRETTY = 1,
};
2012-05-08 22:04:24 +02:00
private:
2012-10-30 13:20:55 +01:00
const char *indent(int n) const;
const char *comma() const;
const char *arrayComma() const;
const char *indent() const;
const char *arrayIndent() const;
void writeEscapedString(const std::string &s);
2012-10-30 13:20:55 +01:00
enum BlockType {
ARRAY,
DICT,
RAW,
2012-10-30 13:20:55 +01:00
};
struct StackEntry {
StackEntry(BlockType t) : type(t), first(true) {}
BlockType type;
bool first;
};
std::vector<StackEntry> stack_;
std::ostringstream str_;
bool pretty_;
2012-03-24 23:39:19 +01:00
};
std::string json_stringify(const JsonNode *json);
} // namespace json