-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathGuardedWrapper.java
More file actions
72 lines (58 loc) · 1.66 KB
/
GuardedWrapper.java
File metadata and controls
72 lines (58 loc) · 1.66 KB
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
package com.github.mustachejava.reflect;
import com.github.mustachejava.util.GuardException;
import com.github.mustachejava.util.Wrapper;
import java.util.Arrays;
import java.util.List;
import static java.util.Arrays.asList;
/**
* Wrapper that guards.
*/
public class GuardedWrapper implements Wrapper {
// We only need a single guard exception -- don't fill stack trace
// and don't reallocate it.
@SuppressWarnings("ThrowableInstanceNeverThrown")
protected static final GuardException guardException = new GuardException();
// Array of guards that must be satisfied
protected final Guard[] guards;
// Hashcode cache
private int hashCode;
public GuardedWrapper(Guard[] guards) {
this.guards = guards;
}
@Override
public Object call(List<Object> scopes) throws GuardException {
guardCall(scopes);
return null;
}
protected void guardCall(List<Object> scopes) throws GuardException {
for (Guard predicate : guards) {
if (!predicate.apply(scopes)) {
throw guardException;
}
}
}
@Override
public int hashCode() {
if (hashCode == 0) {
for (Guard predicate : guards) {
hashCode += hashCode * 43 + predicate.hashCode();
}
if (hashCode == 0) hashCode = 1;
}
return hashCode;
}
@Override
public boolean equals(Object o) {
if (o instanceof GuardedWrapper) {
GuardedWrapper other = (GuardedWrapper) o;
return (guards == null && other.guards == null) || Arrays.equals(other.guards, guards);
}
return false;
}
public Guard[] getGuards() {
return guards;
}
public String toString() {
return "[GuardedWrapper: " + asList(guards) + "]";
}
}