1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package org.whispersystems.libsignal.util.guava;
18 
19 import static org.whispersystems.libsignal.util.guava.Preconditions.checkNotNull;
20 
21 import java.util.Collections;
22 import java.util.Set;
23 
24 /**
25  * Implementation of an {@link Optional} containing a reference.
26  */
27 
28 final class Present<T> extends Optional<T> {
29   private final T reference;
30 
Present(T reference)31   Present(T reference) {
32     this.reference = reference;
33   }
34 
isPresent()35   @Override public boolean isPresent() {
36     return true;
37   }
38 
get()39   @Override public T get() {
40     return reference;
41   }
42 
or(T defaultValue)43   @Override public T or(T defaultValue) {
44     checkNotNull(defaultValue, "use orNull() instead of or(null)");
45     return reference;
46   }
47 
or(Optional<? extends T> secondChoice)48   @Override public Optional<T> or(Optional<? extends T> secondChoice) {
49     checkNotNull(secondChoice);
50     return this;
51   }
52 
or(Supplier<? extends T> supplier)53   @Override public T or(Supplier<? extends T> supplier) {
54     checkNotNull(supplier);
55     return reference;
56   }
57 
orNull()58   @Override public T orNull() {
59     return reference;
60   }
61 
asSet()62   @Override public Set<T> asSet() {
63     return Collections.singleton(reference);
64   }
65 
transform(Function<? super T, V> function)66   @Override public <V> Optional<V> transform(Function<? super T, V> function) {
67     return new Present<V>(checkNotNull(function.apply(reference),
68         "Transformation function cannot return null."));
69   }
70 
equals(Object object)71   @Override public boolean equals(Object object) {
72     if (object instanceof Present) {
73       Present<?> other = (Present<?>) object;
74       return reference.equals(other.reference);
75     }
76     return false;
77   }
78 
hashCode()79   @Override public int hashCode() {
80     return 0x598df91c + reference.hashCode();
81   }
82 
toString()83   @Override public String toString() {
84     return "Optional.of(" + reference + ")";
85   }
86 
87   private static final long serialVersionUID = 0;
88 }
89