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        if (name.trim().isEmpty()) {
032            throw new IllegalArgumentException("Unit name cannot be empty.");
033        }
034        this.name = name.trim();
035    }
036
037    @Override
038    public String toString() {
039        return name;
040    }
041
042    public static double nanosToSeconds(long nanos) {
043        return nanos / 1E9;
044    }
045
046    public static double millisToSeconds(long millis) {
047        return millis / 1E3;
048    }
049
050    public static double secondsToMillis(double seconds) {
051        return seconds * 1E3;
052    }
053
054    public static double kiloBytesToBytes(double kilobytes) {
055        return kilobytes * 1024;
056    }
057
058    @Override
059    public boolean equals(Object o) {
060        if (this == o) return true;
061        if (o == null || getClass() != o.getClass()) return false;
062        Unit unit = (Unit) o;
063        return Objects.equals(name, unit.name);
064    }
065
066    @Override
067    public int hashCode() {
068        return Objects.hash(name);
069    }
070}