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