001package io.prometheus.metrics.expositionformats;
002
003import io.prometheus.metrics.model.snapshots.Labels;
004
005import java.io.IOException;
006import java.io.OutputStreamWriter;
007import java.io.Writer;
008
009import static io.prometheus.metrics.model.snapshots.PrometheusNaming.prometheusName;
010
011public class TextFormatUtil {
012
013    static void writeLong(OutputStreamWriter writer, long value) throws IOException {
014        writer.append(Long.toString(value));
015    }
016
017    static void writeDouble(OutputStreamWriter writer, double d) throws IOException {
018        if (d == Double.POSITIVE_INFINITY) {
019            writer.write("+Inf");
020        } else if (d == Double.NEGATIVE_INFINITY) {
021            writer.write("-Inf");
022        } else {
023            writer.write(Double.toString(d));
024            // FloatingDecimal.getBinaryToASCIIConverter(d).appendTo(writer);
025        }
026    }
027
028    static void writeTimestamp(OutputStreamWriter writer, long timestampMs) throws IOException {
029        writer.write(Long.toString(timestampMs / 1000L));
030        writer.write(".");
031        long ms = timestampMs % 1000;
032        if (ms < 100) {
033            writer.write("0");
034        }
035        if (ms < 10) {
036            writer.write("0");
037        }
038        writer.write(Long.toString(ms));
039    }
040
041    static void writeEscapedLabelValue(Writer writer, String s) throws IOException {
042        for (int i = 0; i < s.length(); i++) {
043            char c = s.charAt(i);
044            switch (c) {
045                case '\\':
046                    writer.append("\\\\");
047                    break;
048                case '\"':
049                    writer.append("\\\"");
050                    break;
051                case '\n':
052                    writer.append("\\n");
053                    break;
054                default:
055                    writer.append(c);
056            }
057        }
058    }
059
060    static void writeLabels(OutputStreamWriter writer, Labels labels, String additionalLabelName, double additionalLabelValue) throws IOException {
061        writer.write('{');
062        for (int i = 0; i < labels.size(); i++) {
063            if (i > 0) {
064                writer.write(",");
065            }
066            writer.write(labels.getPrometheusName(i));
067            writer.write("=\"");
068            writeEscapedLabelValue(writer, labels.getValue(i));
069            writer.write("\"");
070        }
071        if (additionalLabelName != null) {
072            if (!labels.isEmpty()) {
073                writer.write(",");
074            }
075            writer.write(additionalLabelName);
076            writer.write("=\"");
077            writeDouble(writer, additionalLabelValue);
078            writer.write("\"");
079        }
080        writer.write('}');
081    }
082}