001    /*
002     * Copyright (C) 2007 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.base;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    
022    import com.google.common.annotations.Beta;
023    import com.google.common.annotations.GwtCompatible;
024    
025    import java.io.Serializable;
026    import java.util.Map;
027    
028    import javax.annotation.Nullable;
029    
030    /**
031     * Static utility methods pertaining to {@code Function} instances.
032     *
033     * <p>All methods return serializable functions as long as they're given serializable parameters.
034     * 
035     * <p>See the Guava User Guide article on <a href=
036     * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
037     * Function}</a>.
038     *
039     * @author Mike Bostock
040     * @author Jared Levy
041     * @since 2.0 (imported from Google Collections Library)
042     */
043    @GwtCompatible
044    public final class Functions {
045      private Functions() {}
046    
047      /**
048       * Returns a function that calls {@code toString()} on its argument. The function does not accept
049       * nulls; it will throw a {@link NullPointerException} when applied to {@code null}.
050       *
051       * <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as
052       * documented at {@link Function#apply}). For example, this function yields different results for
053       * the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}.
054       */
055      public static Function<Object, String> toStringFunction() {
056        return ToStringFunction.INSTANCE;
057      }
058    
059      // enum singleton pattern
060      private enum ToStringFunction implements Function<Object, String> {
061        INSTANCE;
062    
063        public String apply(Object o) {
064          checkNotNull(o);  // eager for GWT.
065          return o.toString();
066        }
067    
068        
069        @Override
070        public String toString() {
071          return "toString";
072        }
073      }
074    
075      /**
076       * Returns the identity function.
077       */
078      @SuppressWarnings("unchecked")
079      public static <E> Function<E, E> identity() {
080        return (Function<E, E>) IdentityFunction.INSTANCE;
081      }
082    
083      // enum singleton pattern
084      private enum IdentityFunction implements Function<Object, Object> {
085        INSTANCE;
086    
087        public Object apply(Object o) {
088          return o;
089        }
090    
091        
092        @Override
093        public String toString() {
094          return "identity";
095        }
096      }
097    
098      /**
099       * Returns a function which performs a map lookup. The returned function throws an {@link
100       * IllegalArgumentException} if given a key that does not exist in the map.
101       */
102      public static <K, V> Function<K, V> forMap(Map<K, V> map) {
103        return new FunctionForMapNoDefault<K, V>(map);
104      }
105    
106      private static class FunctionForMapNoDefault<K, V> implements Function<K, V>, Serializable {
107        final Map<K, V> map;
108    
109        FunctionForMapNoDefault(Map<K, V> map) {
110          this.map = checkNotNull(map);
111        }
112    
113        public V apply(K key) {
114          V result = map.get(key);
115          checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key);
116          return result;
117        }
118    
119        
120        @Override
121        public boolean equals(@Nullable Object o) {
122          if (o instanceof FunctionForMapNoDefault) {
123            FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o;
124            return map.equals(that.map);
125          }
126          return false;
127        }
128    
129        
130        @Override
131        public int hashCode() {
132          return map.hashCode();
133        }
134    
135        
136        @Override
137        public String toString() {
138          return "forMap(" + map + ")";
139        }
140    
141        private static final long serialVersionUID = 0;
142      }
143    
144      /**
145       * Returns a function which performs a map lookup with a default value. The function created by
146       * this method returns {@code defaultValue} for all inputs that do not belong to the map's key
147       * set.
148       *
149       * @param map source map that determines the function behavior
150       * @param defaultValue the value to return for inputs that aren't map keys
151       * @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code
152       *         defaultValue} otherwise
153       */
154      public static <K, V> Function<K, V> forMap(Map<K, ? extends V> map, @Nullable V defaultValue) {
155        return new ForMapWithDefault<K, V>(map, defaultValue);
156      }
157    
158      private static class ForMapWithDefault<K, V> implements Function<K, V>, Serializable {
159        final Map<K, ? extends V> map;
160        final V defaultValue;
161    
162        ForMapWithDefault(Map<K, ? extends V> map, @Nullable V defaultValue) {
163          this.map = checkNotNull(map);
164          this.defaultValue = defaultValue;
165        }
166    
167        public V apply(K key) {
168          V result = map.get(key);
169          return (result != null || map.containsKey(key)) ? result : defaultValue;
170        }
171    
172        
173        @Override
174        public boolean equals(@Nullable Object o) {
175          if (o instanceof ForMapWithDefault) {
176            ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o;
177            return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue);
178          }
179          return false;
180        }
181    
182        
183        @Override
184        public int hashCode() {
185          return Objects.hashCode(map, defaultValue);
186        }
187    
188        
189        @Override
190        public String toString() {
191          return "forMap(" + map + ", defaultValue=" + defaultValue + ")";
192        }
193    
194        private static final long serialVersionUID = 0;
195      }
196    
197      /**
198       * Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition
199       * is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}.
200       *
201       * @param g the second function to apply
202       * @param f the first function to apply
203       * @return the composition of {@code f} and {@code g}
204       * @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a>
205       */
206      public static <A, B, C> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) {
207        return new FunctionComposition<A, B, C>(g, f);
208      }
209    
210      private static class FunctionComposition<A, B, C> implements Function<A, C>, Serializable {
211        private final Function<B, C> g;
212        private final Function<A, ? extends B> f;
213    
214        public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) {
215          this.g = checkNotNull(g);
216          this.f = checkNotNull(f);
217        }
218    
219        public C apply(A a) {
220          return g.apply(f.apply(a));
221        }
222    
223        
224        @Override
225        public boolean equals(@Nullable Object obj) {
226          if (obj instanceof FunctionComposition) {
227            FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj;
228            return f.equals(that.f) && g.equals(that.g);
229          }
230          return false;
231        }
232    
233        
234        @Override
235        public int hashCode() {
236          return f.hashCode() ^ g.hashCode();
237        }
238    
239        
240        @Override
241        public String toString() {
242          return g.toString() + "(" + f.toString() + ")";
243        }
244    
245        private static final long serialVersionUID = 0;
246      }
247    
248      /**
249       * Creates a function that returns the same boolean output as the given predicate for all inputs.
250       *
251       * <p>The returned function is <i>consistent with equals</i> (as documented at {@link
252       * Function#apply}) if and only if {@code predicate} is itself consistent with equals.
253       */
254      public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) {
255        return new PredicateFunction<T>(predicate);
256      }
257    
258      /** @see Functions#forPredicate */
259      private static class PredicateFunction<T> implements Function<T, Boolean>, Serializable {
260        private final Predicate<T> predicate;
261    
262        private PredicateFunction(Predicate<T> predicate) {
263          this.predicate = checkNotNull(predicate);
264        }
265    
266        public Boolean apply(T t) {
267          return predicate.apply(t);
268        }
269    
270        
271        @Override
272        public boolean equals(@Nullable Object obj) {
273          if (obj instanceof PredicateFunction) {
274            PredicateFunction<?> that = (PredicateFunction<?>) obj;
275            return predicate.equals(that.predicate);
276          }
277          return false;
278        }
279    
280        
281        @Override
282        public int hashCode() {
283          return predicate.hashCode();
284        }
285    
286        
287        @Override
288        public String toString() {
289          return "forPredicate(" + predicate + ")";
290        }
291    
292        private static final long serialVersionUID = 0;
293      }
294    
295      /**
296       * Creates a function that returns {@code value} for any input.
297       *
298       * @param value the constant value for the function to return
299       * @return a function that always returns {@code value}
300       */
301      public static <E> Function<Object, E> constant(@Nullable E value) {
302        return new ConstantFunction<E>(value);
303      }
304    
305      private static class ConstantFunction<E> implements Function<Object, E>, Serializable {
306        private final E value;
307    
308        public ConstantFunction(@Nullable E value) {
309          this.value = value;
310        }
311    
312        public E apply(@Nullable Object from) {
313          return value;
314        }
315    
316        
317        @Override
318        public boolean equals(@Nullable Object obj) {
319          if (obj instanceof ConstantFunction) {
320            ConstantFunction<?> that = (ConstantFunction<?>) obj;
321            return Objects.equal(value, that.value);
322          }
323          return false;
324        }
325    
326        
327        @Override
328        public int hashCode() {
329          return (value == null) ? 0 : value.hashCode();
330        }
331    
332        
333        @Override
334        public String toString() {
335          return "constant(" + value + ")";
336        }
337    
338        private static final long serialVersionUID = 0;
339      }
340    
341      /**
342       * Returns a function that always returns the result of invoking {@link Supplier#get} on {@code
343       * supplier}, regardless of its input.
344       * 
345       * @since 10.0
346       */
347      @Beta
348      public static <T> Function<Object, T> forSupplier(Supplier<T> supplier) {
349        return new SupplierFunction<T>(supplier);
350      }
351    
352      /** @see Functions#forSupplier*/
353      private static class SupplierFunction<T> implements Function<Object, T>, Serializable {
354        
355        private final Supplier<T> supplier;
356    
357        private SupplierFunction(Supplier<T> supplier) {
358          this.supplier = checkNotNull(supplier);
359        }
360    
361        public T apply(@Nullable Object input) {
362          return supplier.get();
363        }
364        
365        
366        @Override
367        public boolean equals(@Nullable Object obj) {
368          if (obj instanceof SupplierFunction) {
369            SupplierFunction<?> that = (SupplierFunction<?>) obj;
370            return this.supplier.equals(that.supplier);
371          }
372          return false;
373        }
374        
375        
376        @Override
377        public int hashCode() {
378          return supplier.hashCode();
379        }
380        
381        
382        @Override
383        public String toString() {
384          return "forSupplier(" + supplier + ")";
385        }
386        
387        private static final long serialVersionUID = 0;
388      }
389    }