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