-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathSingletonContext.java
More file actions
63 lines (54 loc) · 1.75 KB
/
Copy pathSingletonContext.java
File metadata and controls
63 lines (54 loc) · 1.75 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
package datadog.context;
import static java.lang.Math.max;
import static java.util.Objects.requireNonNull;
import java.util.Objects;
import javax.annotation.Nullable;
/** {@link Context} containing a single value. */
final class SingletonContext implements SelfScopedContext {
final int index;
final Object value;
SingletonContext(int index, Object value) {
this.index = index;
this.value = value;
}
@Override
@Nullable
@SuppressWarnings("unchecked")
public <V> V get(ContextKey<V> key) {
requireNonNull(key, "Context key cannot be null");
return this.index == key.index ? (V) this.value : null;
}
@Override
public <V> Context with(ContextKey<V> secondKey, @Nullable V secondValue) {
requireNonNull(secondKey, "Context key cannot be null");
int secondIndex = secondKey.index;
if (this.index == secondIndex) {
return secondValue == null
? EmptyContext.INSTANCE
: new SingletonContext(this.index, secondValue);
} else {
Object[] store = new Object[max(this.index, secondIndex) + 1];
store[this.index] = this.value;
store[secondIndex] = secondValue;
return new IndexedContext(store);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SingletonContext that = (SingletonContext) o;
return this.index == that.index && Objects.equals(this.value, that.value);
}
@Override
public int hashCode() {
int result = 31;
result = 31 * result + this.index;
result = 31 * result + Objects.hashCode(this.value);
return result;
}
@Override
public String toString() {
return "SingletonContext{" + "index=" + this.index + ", value=" + this.value + '}';
}
}