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