summaryrefslogtreecommitdiff
path: root/src/main/java/au/id/zancanaro/javacheck/Generators.java
blob: 9730bac2cfdae8dc56034b41ca0974a4a8c48d43 (about) (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package au.id.zancanaro.javacheck;

import java.util.*;
import java.util.function.Function;

@SuppressWarnings({"unused", "WeakerAccess"})
public final class Generators {
    private Generators() {
    }

    /**
     * Create a generator which explicitly depends on the current "size"
     * parameter.
     *
     * @param makeGenerator A function from size to a generator
     * @param <T>           The static type of the returned generator
     * @return The generator returned by makeGenerator
     */
    public static <T> Generator<T> sized(Function<Integer, Generator<T>> makeGenerator) {
        return (random, size) -> makeGenerator.apply(size).generate(random, size);
    }

    /**
     * Remove a generator's shrink tree.
     *
     * @param gen The generator
     * @param <T> The generator's static type
     * @return A new generator which is the previous generator with shrink tree
     * removed
     */
    public static <T> Generator<T> noShrink(Generator<T> gen) {
        return gen.withShrinkStrategy(value -> Iterators.emptyIterator());
    }

    @SafeVarargs
    public static <T> Generator<T> oneOf(Generator<? extends T>... gens) {
        return integer(0, gens.length).flatMap(index -> gens[index].map(x -> (T) x));
    }

    public static <T> Generator<T> elements(T[] elements) {
        return elements(Arrays.asList(elements));
    }

    public static <T> Generator<T> elements(List<T> elements) {
        return integer(0, elements.size()).map(elements::get);
    }

    public static Generator<Boolean> bool() {
        return (random, size) ->
                ShrinkTree.pure(random.nextBoolean())
                        .withShrinkStrategy(boolShrinkStrategy());
    }

    private static ShrinkStrategy<Boolean> boolShrinkStrategy() {
        return value -> new Iterator<Boolean>() {
            boolean hasMore = value;

            @Override
            public boolean hasNext() {
                return hasMore;
            }

            @Override
            public Boolean next() {
                if (hasMore) {
                    return (hasMore = false);
                } else {
                    throw new NoSuchElementException("Boolean shrink tree exhausted");
                }
            }
        };
    }

    public static Generator<Long> longInteger(long lower, long upper) {
        return (random, size) -> {
            long value = random.longs(lower, upper).findFirst().getAsLong();
            long bound = lower > 0 ? lower : (upper < 0 ? upper : 0);
            return ShrinkTree.pure(value)
                    .withShrinkStrategy(longShrinkStrategy(bound));
        };
    }

    public static Generator<Long> longInteger() {
        return sized(size -> longInteger(-size, size));
    }

    private static ShrinkStrategy<Long> longShrinkStrategy(final long bound) {
        return value -> new Iterator<Long>() {
            long curr = value - bound;

            @Override
            public boolean hasNext() {
                return curr != 0;
            }

            @Override
            public Long next() {
                long prevCurr = curr;
                curr = curr / 2;
                return value - prevCurr;
            }
        };
    }

    public static Generator<Integer> integer(int lower, int upper) {
        return (random, size) -> {
            int value = random.ints(lower, upper).findFirst().getAsInt();
            int bound = lower > 0 ? lower : (upper < 0 ? upper : 0);
            return ShrinkTree.pure(value)
                    .withShrinkStrategy(intShrinkStrategy(bound));
        };
    }

    public static Generator<Integer> integer() {
        return sized(size -> integer(-size, size));
    }

    public static Generator<Integer> natural() {
        return sized(size -> integer(0, size));
    }

    public static ShrinkStrategy<Integer> intShrinkStrategy(int bound) {
        return value -> new Iterator<Integer>() {
            int curr = value - bound;

            @Override
            public boolean hasNext() {
                return curr != 0;
            }

            @Override
            public Integer next() {
                int prevCurr = curr;
                curr = curr / 2;
                return value - prevCurr;
            }
        };
    }

    public static Generator<Double> doublePrecision(double lower, double upper) {
        return (random, size) -> {
            double value = random.doubles(lower, upper).findFirst().getAsDouble();
            double bound = lower > 0 ? lower : (upper < 0 ? upper : 0);
            return ShrinkTree.pure(value)
                    .withShrinkStrategy(doubleShrinkStrategy(bound, Double.MIN_NORMAL /* maybe pick a bigger epsilon? */));
        };
    }

    public static Generator<Double> doublePrecision() {
        return sized(size -> doublePrecision(-size, size));
    }

    public static ShrinkStrategy<Double> doubleShrinkStrategy(double bound, double epsilon) {
        return value -> new Iterator<Double>() {
            double curr = value - bound;

            @Override
            public boolean hasNext() {
                return Math.abs(curr) > epsilon;
            }

            @Override
            public Double next() {
                double prevCurr = curr;
                curr = curr / 2;
                return value - prevCurr;
            }
        };
    }

    public static <T> Generator<List<T>> listOf(Generator<T> gen, int minElements, int maxElements) {
        return (random, size) -> {
            Generator<Integer> countGen = sized(s -> integer(minElements, maxElements));
            int count = countGen.generate(random, size).getValue();
            return Generator.list(count, gen)
                    .generate(random, size)
                    .filter(list -> minElements <= list.size() && list.size() < maxElements)
                    .map(Collections::unmodifiableList);
        };
    }

    public static <T> Generator<List<T>> listOf(Generator<T> gen) {
        return (random, size) -> {
            Generator<Integer> countGen = sized(s -> integer(0, s));
            int count = countGen.generate(random, size).getValue();
            return Generator.list(count, gen)
                    .generate(random, size)
                    .map(Collections::unmodifiableList);
        };
    }

    public static Generator<Character> character() {
        return integer(0, 256).map(i -> (char) i.intValue());
    }

    public static Generator<Character> asciiCharacter() {
        return integer(32, 127).map(i -> (char) i.intValue());
    }

    public static Generator<Character> alphaNumericCharacter() {
        return oneOf(
                integer(48, 58),
                integer(65, 91),
                integer(97, 123)).map(i -> (char) i.intValue());
    }

    public static Generator<Character> alphaCharacter() {
        return oneOf(
                integer(65, 91),
                integer(97, 123)).map(i -> (char) i.intValue());
    }

    private static String makeString(Character[] arr) {
        StringBuilder builder = new StringBuilder(arr.length);
        for (Character c : arr) {
            builder.append(c);
        }
        return builder.toString();
    }

    public static Generator<String> string() {
        return stringOf(character());
    }

    public static Generator<String> stringOf(Generator<Character> charGen) {
        return listOf(charGen).map(list -> {
            char[] chars = new char[list.size()];
            int i = 0;
            for (Character c : list) {
                chars[i++] = c;
            }
            return String.valueOf(chars);
        });
    }
}