Debian Codegraph @

src/test/java/io/reactivex/rxjava3/internal/util/CrashingMappedIterable.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.internal.util;
15
16 import java.util.Iterator;
17
18 import io.reactivex.rxjava3.exceptions.TestException;
19 import io.reactivex.rxjava3.functions.Function;
20
21 /**
22 * An Iterable and Iterator that crashes with TestException after the given number
23 * of method invocations on iterator(), hasNext() and next().
24 *
25 * @param <T> the result type
26 */
27 public final class CrashingMappedIterable<T> implements Iterable<T> {
28 int crashOnIterator;
29
30 final int crashOnHasNext;
31
32 final int crashOnNext;
33
34 final Function<Integer, T> mapper;
35
36 public CrashingMappedIterable(int crashOnIterator, int crashOnHasNext, int crashOnNext, Function<Integer, T> mapper) {
37 this.crashOnIterator = crashOnIterator;
38 this.crashOnHasNext = crashOnHasNext;
39 this.crashOnNext = crashOnNext;
40 this.mapper = mapper;
41 }
42
43 @Override
44 public Iterator<T> iterator() {
45 if (--crashOnIterator <= 0) {
46 throw new TestException("iterator()");
47 }
48 return new CrashingMapperIterator<>(crashOnHasNext, crashOnNext, mapper);
49 }
50
51 static final class CrashingMapperIterator<T> implements Iterator<T> {
52 int crashOnHasNext;
53
54 int crashOnNext;
55
56 int count;
57
58 final Function<Integer, T> mapper;
59
60 CrashingMapperIterator(int crashOnHasNext, int crashOnNext, Function<Integer, T> mapper) {
61 this.crashOnHasNext = crashOnHasNext;
62 this.crashOnNext = crashOnNext;
63 this.mapper = mapper;
64 }
65
66 @Override
67 public boolean hasNext() {
68 if (--crashOnHasNext <= 0) {
69 throw new TestException("hasNext()");
70 }
71 return true;
72 }
73
74 @Override
75 public T next() {
76 if (--crashOnNext <= 0) {
77 throw new TestException("next()");
78 }
79 try {
80 return mapper.apply(count++);
81 } catch (Throwable ex) {
82 throw ExceptionHelper.wrapOrThrow(ex);
83 }
84 }
85
86 @Override
87 public void remove() {
88 throw new UnsupportedOperationException();
89 }
90 }
91 }