aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/binaryprefix/BinaryScaledAmount.java
blob: d276cb6f950ec760f9ab19b2eaea8c466ca845da (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.binaryprefix;

/**
 * An amount scaled by a binary prefix.
 *
 * <p>
 * Examples: 2 kilo, 2 mega, ...
 * </p>
 *
 * @author Tony Vaagenes
 */
public final class BinaryScaledAmount {

    public final double amount;
    public final BinaryPrefix binaryPrefix;

    public BinaryScaledAmount(double amount, BinaryPrefix binaryPrefix) {
        this.amount = amount;
        this.binaryPrefix = binaryPrefix;
    }

    public BinaryScaledAmount() {
        this(0, BinaryPrefix.unit);
    }

    public long as(BinaryPrefix newBinaryPrefix) {
        return Math.round(newBinaryPrefix.convertFrom(amount, binaryPrefix));
    }

    public boolean equals(BinaryScaledAmount candidate) {
        return BinaryPrefix.unit.convertFrom(amount, binaryPrefix) ==
                BinaryPrefix.unit.convertFrom(candidate.amount, candidate.binaryPrefix);
    }

    public BinaryScaledAmount multiply(double d) {
        return new BinaryScaledAmount(d*amount, binaryPrefix);
    }

    public BinaryScaledAmount divide(double d) {
        return multiply(1/d);
    }

    @Override
    public boolean equals(Object candidate) {
        if (!(candidate instanceof BinaryScaledAmount)) {
            return false;
        } else {
            return equals((BinaryScaledAmount)candidate);
        }
    }

    @Override
    public int hashCode() {
        return (int)BinaryPrefix.unit.convertFrom(amount, binaryPrefix);
    }

}