aboutsummaryrefslogtreecommitdiff
path: root/src/ch/epfl/xblast/ArgumentChecker.java
blob: 56f8acdb4b6ba12b1179006997a9df4e405345a4 (plain)
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
83
84
85
86
87
88
89
90
91
package ch.epfl.xblast;

import ch.epfl.cs108.Sq;

import java.util.Collection;
import java.util.Objects;

/**
 * ArgumentChecker.
 *
 * @author Pacien TRAN-GIRARD (261948)
 * @author Timothée FLOURE (257420)
 */
public final class ArgumentChecker {

    private ArgumentChecker() {
        // Static class
    }

    /**
     * Returns the given value if it is non-negative.
     *
     * @param v the tested value
     * @return the given value if non-negative
     * @throws IllegalArgumentException if the value is inferior to 0
     */
    public static int requireNonNegative(int v) {
        if (v < 0)
            throw new IllegalArgumentException();

        return v;
    }

    /**
     * Requires the given Collection to be non-empty and returns it or throw an IllegalArgumentException otherwise.
     *
     * @param c   the Collection to check
     * @param <T> the Collection type
     * @return the checked Collection
     */
    public static <T extends Collection> T requireNonEmpty(T c) {
        if (Objects.requireNonNull(c).isEmpty())
            throw new IllegalArgumentException();

        return c;
    }

    /**
     * Requires the given Sequence to be non-empty and returns it or throw an IllegalArgumentException otherwise.
     *
     * @param s   the sequence to check
     * @param <T> the sequence type
     * @return the checked sequence
     */
    public static <T extends Sq> T requireNonEmpty(T s) {
        if (Objects.requireNonNull(s).isEmpty())
            throw new IllegalArgumentException();

        return s;
    }

    /**
     * Returns the element from the array at the requested index, or null if it cannot be retrieved.
     *
     * @param array the array
     * @param index the index
     * @param <T>   the type of element
     * @return the requested element, or null
     */
    public static <T> T getOrNull(T[] array, int index) {
        if (Objects.isNull(array) || index < 0 || index >= array.length)
            return null;
        else
            return array[index];
    }

    /**
     * Parses and returns an integer, or return null on error.
     *
     * @param str the integer to parse
     * @return the parsed integer, or null
     */
    public static Integer parseIntOrNull(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException | NullPointerException e) {
            return null;
        }
    }

}