001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.statistics.descriptive;
018
019import java.math.BigInteger;
020
021/**
022 * Returns the sum of the available values.
023 *
024 * <ul>
025 *   <li>The result is zero if no values are added.
026 * </ul>
027 *
028 * <p>This class uses an exact integer sum. The exact sum is
029 * returned using {@link #getAsBigInteger()}. Methods that return {@code int} or
030 * {@code long} primitives will raise an exception if the result overflows.
031 * The {@code long} value is safe up to the maximum array length for any input
032 * {@code int[]} data. The {@code long} value can overflow when instances are combined.
033 *
034 * <p>Note that the implementation does not use {@code BigInteger} arithmetic; for
035 * performance the sum is computed using primitives to create a signed 128-bit integer.
036 * Support is provided for at least 2<sup>63</sup> observations.
037 *
038 * <p>This class is designed to work with (though does not require)
039 * {@linkplain java.util.stream streams}.
040 *
041 * <p><strong>This implementation is not thread safe.</strong>
042 * If multiple threads access an instance of this class concurrently,
043 * and at least one of the threads invokes the {@link java.util.function.IntConsumer#accept(int) accept} or
044 * {@link StatisticAccumulator#combine(StatisticResult) combine} method, it must be synchronized externally.
045 *
046 * <p>However, it is safe to use {@link java.util.function.IntConsumer#accept(int) accept}
047 * and {@link StatisticAccumulator#combine(StatisticResult) combine}
048 * as {@code accumulator} and {@code combiner} functions of
049 * {@link java.util.stream.Collector Collector} on a parallel stream,
050 * because the parallel implementation of {@link java.util.stream.Stream#collect Stream.collect()}
051 * provides the necessary partitioning, isolation, and merging of results for
052 * safe and efficient parallel execution.
053 *
054 * @since 1.1
055 */
056public final class IntSum implements IntStatistic, StatisticAccumulator<IntSum> {
057    /** Sum of the values. */
058    private final Int128 sum;
059
060    /**
061     * Create an instance.
062     */
063    private IntSum() {
064        this(Int128.create());
065    }
066
067    /**
068     * Create an instance.
069     *
070     * @param sum Sum of the values.
071     */
072    private IntSum(Int128 sum) {
073        this.sum = sum;
074    }
075
076    /**
077     * Creates an instance.
078     *
079     * <p>The initial result is zero.
080     *
081     * @return {@code IntSum} instance.
082     */
083    public static IntSum create() {
084        return new IntSum();
085    }
086
087    /**
088     * Returns an instance populated using the input {@code values}.
089     *
090     * <p>When the input is an empty array, the result is zero.
091     *
092     * <p>The {@link #getAsLong()} result is valid for any input {@code int[]} length;
093     * the {@link #getAsInt()} result may overflow.
094     *
095     * @param values Values.
096     * @return {@code IntSum} instance.
097     */
098    public static IntSum of(int... values) {
099        // Sum of an array cannot exceed a 64-bit long
100        long s = 0;
101        for (final int x : values) {
102            s += x;
103        }
104        // Convert
105        return new IntSum(Int128.of(s));
106    }
107
108    /**
109     * Gets the sum.
110     *
111     * <p>This is package private for use in {@link IntStatistics}.
112     *
113     * @return the sum
114     */
115    Int128 getSum() {
116        return sum;
117    }
118
119    /**
120     * Updates the state of the statistic to reflect the addition of {@code value}.
121     *
122     * @param value Value.
123     */
124    @Override
125    public void accept(int value) {
126        sum.add(value);
127    }
128
129    /**
130     * Gets the sum of all input values.
131     *
132     * <p>When no values have been added, the result is zero.
133     *
134     * <p>Warning: This will raise an {@link ArithmeticException}
135     * if the result is not within the range {@code [-2^31, 2^31)}.
136     *
137     * @return sum of all values.
138     * @throws ArithmeticException if the {@code result} overflows an {@code int}
139     * @see #getAsBigInteger()
140     */
141    @Override
142    public int getAsInt() {
143        return sum.toIntExact();
144    }
145
146    /**
147     * Gets the sum of all input values.
148     *
149     * <p>When no values have been added, the result is zero.
150     *
151     * <p>Warning: This will raise an {@link ArithmeticException}
152     * if the result is not within the range {@code [-2^63, 2^63)}.
153     *
154     * @return sum of all values.
155     * @throws ArithmeticException if the {@code result} overflows a {@code long}
156     * @see #getAsBigInteger()
157     */
158    @Override
159    public long getAsLong() {
160        return sum.toLongExact();
161    }
162
163    /**
164     * Gets the sum of all input values.
165     *
166     * <p>When no values have been added, the result is zero.
167     *
168     * <p>Note that this conversion can lose information about the precision of the
169     * {@code BigInteger} value.
170     *
171     * @return sum of all values.
172     * @see #getAsBigInteger()
173     */
174    @Override
175    public double getAsDouble() {
176        return sum.toDouble();
177    }
178
179    /**
180     * Gets the sum of all input values.
181     *
182     * <p>When no values have been added, the result is zero.
183     *
184     * @return sum of all values.
185     */
186    @Override
187    public BigInteger getAsBigInteger() {
188        return sum.toBigInteger();
189    }
190
191    @Override
192    public IntSum combine(IntSum other) {
193        sum.add(other.sum);
194        return this;
195    }
196}