package com.oracle.svm.configure.json;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
public class JsonWriter implements AutoCloseable {
private static final String WHITESPACE = " ";
private final Writer writer;
private int indentation = 0;
public JsonWriter(Path path, OpenOption... options) throws IOException {
this(Files.newBufferedWriter(path, StandardCharsets.UTF_8, options));
}
public JsonWriter(Writer writer) {
this.writer = writer;
}
public JsonWriter append(char c) throws IOException {
writer.write(c);
return this;
}
public JsonWriter append(String s) throws IOException {
writer.write(s);
return this;
}
public JsonWriter quote(Object o) throws IOException {
if (o == null) {
return append("null");
} else if (Boolean.TRUE.equals(o)) {
return append("true");
} else if (Boolean.FALSE.equals(o)) {
return append("false");
}
return quote(o.toString());
}
public JsonWriter quote(String s) throws IOException {
writer.write(quoteString(s));
return this;
}
public static String quoteString(String s) {
if (s == null) {
return "null";
}
StringBuilder sb = new StringBuilder(2 + s.length() + 8 );
sb.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '"' || c == '\\') {
sb.append('\\');
sb.append(c);
} else if (c < 0x001F) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
sb.append('"');
return sb.toString();
}
public JsonWriter newline() throws IOException {
writer.write('\n');
writer.write(WHITESPACE, 0, Math.min(2 * indentation, WHITESPACE.length()));
return this;
}
public JsonWriter indent() {
indentation++;
return this;
}
public JsonWriter unindent() {
assert indentation > 0;
indentation--;
return this;
}
public void flush() throws IOException {
writer.flush();
}
@Override
public void close() throws IOException {
writer.close();
}
}