001package io.prometheus.metrics.model.snapshots;
002
003import java.util.Objects;
004
005/**
006 * Some pre-defined units for convenience. You can create your own units with
007 *
008 * <pre>
009 *     new Unit("myUnit");
010 * </pre>
011 *
012 * Note that in Prometheus, units are largely based on SI base units (seconds, bytes, joules, grams,
013 * meters, ratio, volts, amperes, and Celsius).
014 */
015public final class Unit {
016
017  private final String name;
018
019  public static final Unit RATIO = new Unit("ratio");
020  public static final Unit SECONDS = new Unit("seconds");
021  public static final Unit BYTES = new Unit("bytes");
022  public static final Unit CELSIUS = new Unit("celsius");
023  public static final Unit JOULES = new Unit("joules");
024  public static final Unit GRAMS = new Unit("grams");
025  public static final Unit METERS = new Unit("meters");
026  public static final Unit VOLTS = new Unit("volts");
027  public static final Unit AMPERES = new Unit("amperes");
028
029  public Unit(String name) {
030    if (name == null) {
031      throw new NullPointerException("Unit name cannot be null.");
032    }
033    name = name.trim();
034    String error = PrometheusNaming.validateUnitName(name);
035    if (error != null) {
036      throw new IllegalArgumentException(name + ": Illegal unit name: " + error);
037    }
038    this.name = name;
039  }
040
041  @Override
042  public String toString() {
043    return name;
044  }
045
046  public static double nanosToSeconds(long nanos) {
047    return nanos / 1E9;
048  }
049
050  public static double millisToSeconds(long millis) {
051    return millis / 1E3;
052  }
053
054  public static double secondsToMillis(double seconds) {
055    return seconds * 1E3;
056  }
057
058  public static double kiloBytesToBytes(double kilobytes) {
059    return kilobytes * 1024;
060  }
061
062  @Override
063  public boolean equals(Object o) {
064    if (this == o) {
065      return true;
066    }
067    if (o == null || getClass() != o.getClass()) {
068      return false;
069    }
070    Unit unit = (Unit) o;
071    return Objects.equals(name, unit.name);
072  }
073
074  @Override
075  public int hashCode() {
076    return Objects.hash(name);
077  }
078}