summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/DimensionSizes.java
blob: 7570a35745279c507e073b99a4392ff60c5b83d6 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.yahoo.tensor;

import com.google.common.annotations.Beta;

import java.util.Arrays;

/**
 * The sizes of a set of dimensions.
 * 
 * @author bratseth
 */
@Beta
public final class DimensionSizes {

    private final int[] sizes;

    private DimensionSizes(Builder builder) {
        this.sizes = builder.sizes;
        builder.sizes = null; // invalidate builder to avoid copying the array
    }

    /**
     * Returns the length of this in the nth dimension
     *
     * @throws IndexOutOfBoundsException if the index is larger than the number of dimensions in this tensor minus one
     */
    public int size(int dimensionIndex) { return sizes[dimensionIndex]; }

    /** Returns the number of dimensions this provides the size of */
    public int dimensions() { return sizes.length; }

    /** Returns the product of the sizes of this */
    public int totalSize() {
        int productSize = 1;
        for (int dimensionSize : sizes )
            productSize *= dimensionSize;
        return productSize;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof DimensionSizes)) return false;
        return Arrays.equals(((DimensionSizes) o).sizes, this.sizes);
    }

    @Override
    public int hashCode() { return Arrays.hashCode(sizes); }

    /** 
     * Builder of a set of dimension sizes.
     * Dimensions whose size is not set before building will get size 0.
     */
    public final static class Builder {

        private int[] sizes;

        public Builder(int dimensions) {
            this.sizes = new int[dimensions];
        }

        public Builder set(int dimensionIndex, int size) {
            sizes[dimensionIndex] = size;
            return this;
        }

        /**
         * Returns the length of this in the nth dimension
         *
         * @throws IndexOutOfBoundsException if the index is larger than the number of dimensions in this tensor minus one
         */
        public int size(int dimensionIndex) { return sizes[dimensionIndex]; }

        /** Returns the number of dimensions this provides the size of */
        public int dimensions() { return sizes.length; }

        /** Build this. This builder becomes invalid after calling this. */
        public DimensionSizes build() { return new DimensionSizes(this); }

    }

}