001/*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.errorprone.annotations.CanIgnoreReturnValue;
021import com.google.errorprone.annotations.concurrent.LazyInit;
022import java.io.Serializable;
023import java.util.Iterator;
024import javax.annotation.Nullable;
025
026/**
027 * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B}
028 * to {@code A}; used for converting back and forth between <i>different representations of the same
029 * information</i>.
030 *
031 * <h3>Invertibility</h3>
032 *
033 * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code
034 * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very
035 * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an
036 * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}:
037 *
038 * <ol>
039 * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0}
040 * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} --
041 *     <i>not</i> the same string ({@code "1.00"}) we started with
042 * </ol>
043 *
044 * <p>Note that it should still be the case that the round-tripped and original objects are
045 * <i>similar</i>.
046 *
047 * <h3>Nullability</h3>
048 *
049 * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null
050 * references. It would not make sense to consider {@code null} and a non-null reference to be
051 * "different representations of the same information", since one is distinguishable from
052 * <i>missing</i> information and the other is not. The {@link #convert} method handles this null
053 * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are
054 * guaranteed to never be passed {@code null}, and must never return {@code null}.
055 *
056 *
057 * <h3>Common ways to use</h3>
058 *
059 * <p>Getting a converter:
060 *
061 * <ul>
062 * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link
063 *     com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain
064 *     #reverse reverse} views of these.
065 * <li>Convert between specific preset values using {@link
066 *     com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to create
067 *     a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> the
068 *     {@code Converter} type using a mocking framework.
069 * <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods.
070 * <li><b>Java 8 users:</b> you may prefer to pass two lambda expressions or method references to
071 *     the {@link #from from} factory method.
072 * </ul>
073 *
074 * <p>Using a converter:
075 *
076 * <ul>
077 * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}.
078 * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}.
079 * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code
080 *     converter.reverse().convertAll(bs)}.
081 * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link
082 *     java.util.function.Function} is accepted (for example {@link java.util.stream.Stream#map
083 *     Stream.map}).
084 * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to be
085 *     overridden.
086 * </ul>
087 *
088 * <h3>Example</h3>
089 *
090 * <pre>
091 *   return new Converter&lt;Integer, String&gt;() {
092 *     protected String doForward(Integer i) {
093 *       return Integer.toHexString(i);
094 *     }
095 *
096 *     protected Integer doBackward(String s) {
097 *       return parseUnsignedInt(s, 16);
098 *     }
099 *   };</pre>
100 *
101 * <p>An alternative using Java 8:
102 *
103 * <pre>{@code
104 * return Converter.from(
105 *     Integer::toHexString,
106 *     s -> parseUnsignedInt(s, 16));
107 * }</pre>
108 *
109 * @author Mike Ward
110 * @author Kurt Alfred Kluever
111 * @author Gregory Kick
112 * @since 16.0
113 */
114@GwtCompatible
115public abstract class Converter<A, B> implements Function<A, B> {
116  private final boolean handleNullAutomatically;
117
118  // We lazily cache the reverse view to avoid allocating on every call to reverse().
119  @LazyInit
120  private transient Converter<B, A> reverse;
121
122  /** Constructor for use by subclasses. */
123  protected Converter() {
124    this(true);
125  }
126
127  /**
128   * Constructor used only by {@code LegacyConverter} to suspend automatic null-handling.
129   */
130  Converter(boolean handleNullAutomatically) {
131    this.handleNullAutomatically = handleNullAutomatically;
132  }
133
134  // SPI methods (what subclasses must implement)
135
136  /**
137   * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be
138   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
139   *
140   * @param a the instance to convert; will never be null
141   * @return the converted instance; <b>must not</b> be null
142   */
143  protected abstract B doForward(A a);
144
145  /**
146   * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be
147   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
148   *
149   * @param b the instance to convert; will never be null
150   * @return the converted instance; <b>must not</b> be null
151   * @throws UnsupportedOperationException if backward conversion is not implemented; this should be
152   *     very rare. Note that if backward conversion is not only unimplemented but
153   *     unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}),
154   *     then this is not logically a {@code Converter} at all, and should just implement {@link
155   *     Function}.
156   */
157  protected abstract A doBackward(B b);
158
159  // API (consumer-side) methods
160
161  /**
162   * Returns a representation of {@code a} as an instance of type {@code B}.
163   *
164   * @return the converted value; is null <i>if and only if</i> {@code a} is null
165   */
166  @Nullable
167  @CanIgnoreReturnValue
168  public final B convert(@Nullable A a) {
169    return correctedDoForward(a);
170  }
171
172  @Nullable
173  B correctedDoForward(@Nullable A a) {
174    if (handleNullAutomatically) {
175      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
176      return a == null ? null : checkNotNull(doForward(a));
177    } else {
178      return doForward(a);
179    }
180  }
181
182  @Nullable
183  A correctedDoBackward(@Nullable B b) {
184    if (handleNullAutomatically) {
185      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
186      return b == null ? null : checkNotNull(doBackward(b));
187    } else {
188      return doBackward(b);
189    }
190  }
191
192  /**
193   * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The
194   * conversion is done lazily.
195   *
196   * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After
197   * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
198   * element.
199   */
200  @CanIgnoreReturnValue
201  public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) {
202    checkNotNull(fromIterable, "fromIterable");
203    return new Iterable<B>() {
204      @Override
205      public Iterator<B> iterator() {
206        return new Iterator<B>() {
207          private final Iterator<? extends A> fromIterator = fromIterable.iterator();
208
209          @Override
210          public boolean hasNext() {
211            return fromIterator.hasNext();
212          }
213
214          @Override
215          public B next() {
216            return convert(fromIterator.next());
217          }
218
219          @Override
220          public void remove() {
221            fromIterator.remove();
222          }
223        };
224      }
225    };
226  }
227
228  /**
229   * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a
230   * value roughly equivalent to {@code a}.
231   *
232   * <p>The returned converter is serializable if {@code this} converter is.
233   *
234   * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons.
235   */
236  @CanIgnoreReturnValue
237  public Converter<B, A> reverse() {
238    Converter<B, A> result = reverse;
239    return (result == null) ? reverse = new ReverseConverter<A, B>(this) : result;
240  }
241
242  private static final class ReverseConverter<A, B> extends Converter<B, A>
243      implements Serializable {
244    final Converter<A, B> original;
245
246    ReverseConverter(Converter<A, B> original) {
247      this.original = original;
248    }
249
250    /*
251     * These gymnastics are a little confusing. Basically this class has neither legacy nor
252     * non-legacy behavior; it just needs to let the behavior of the backing converter shine
253     * through. So, we override the correctedDo* methods, after which the do* methods should never
254     * be reached.
255     */
256
257    @Override
258    protected A doForward(B b) {
259      throw new AssertionError();
260    }
261
262    @Override
263    protected B doBackward(A a) {
264      throw new AssertionError();
265    }
266
267    @Override
268    @Nullable
269    A correctedDoForward(@Nullable B b) {
270      return original.correctedDoBackward(b);
271    }
272
273    @Override
274    @Nullable
275    B correctedDoBackward(@Nullable A a) {
276      return original.correctedDoForward(a);
277    }
278
279    @Override
280    public Converter<A, B> reverse() {
281      return original;
282    }
283
284    @Override
285    public boolean equals(@Nullable Object object) {
286      if (object instanceof ReverseConverter) {
287        ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object;
288        return this.original.equals(that.original);
289      }
290      return false;
291    }
292
293    @Override
294    public int hashCode() {
295      return ~original.hashCode();
296    }
297
298    @Override
299    public String toString() {
300      return original + ".reverse()";
301    }
302
303    private static final long serialVersionUID = 0L;
304  }
305
306  /**
307   * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result
308   * of this converter. Its {@code reverse} method applies the converters in reverse order.
309   *
310   * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter}
311   * are.
312   */
313  public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) {
314    return doAndThen(secondConverter);
315  }
316
317  /**
318   * Package-private non-final implementation of andThen() so only we can override it.
319   */
320  <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) {
321    return new ConverterComposition<A, B, C>(this, checkNotNull(secondConverter));
322  }
323
324  private static final class ConverterComposition<A, B, C> extends Converter<A, C>
325      implements Serializable {
326    final Converter<A, B> first;
327    final Converter<B, C> second;
328
329    ConverterComposition(Converter<A, B> first, Converter<B, C> second) {
330      this.first = first;
331      this.second = second;
332    }
333
334    /*
335     * These gymnastics are a little confusing. Basically this class has neither legacy nor
336     * non-legacy behavior; it just needs to let the behaviors of the backing converters shine
337     * through (which might even differ from each other!). So, we override the correctedDo* methods,
338     * after which the do* methods should never be reached.
339     */
340
341    @Override
342    protected C doForward(A a) {
343      throw new AssertionError();
344    }
345
346    @Override
347    protected A doBackward(C c) {
348      throw new AssertionError();
349    }
350
351    @Override
352    @Nullable
353    C correctedDoForward(@Nullable A a) {
354      return second.correctedDoForward(first.correctedDoForward(a));
355    }
356
357    @Override
358    @Nullable
359    A correctedDoBackward(@Nullable C c) {
360      return first.correctedDoBackward(second.correctedDoBackward(c));
361    }
362
363    @Override
364    public boolean equals(@Nullable Object object) {
365      if (object instanceof ConverterComposition) {
366        ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object;
367        return this.first.equals(that.first) && this.second.equals(that.second);
368      }
369      return false;
370    }
371
372    @Override
373    public int hashCode() {
374      return 31 * first.hashCode() + second.hashCode();
375    }
376
377    @Override
378    public String toString() {
379      return first + ".andThen(" + second + ")";
380    }
381
382    private static final long serialVersionUID = 0L;
383  }
384
385  /**
386   * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead.
387   */
388  @Deprecated
389  @Override
390  @Nullable
391  @CanIgnoreReturnValue
392  public final B apply(@Nullable A a) {
393    return convert(a);
394  }
395
396  /**
397   * Indicates whether another object is equal to this converter.
398   *
399   * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
400   * However, an implementation may also choose to return {@code true} whenever {@code object} is a
401   * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable"
402   * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for
403   * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false}
404   * result from this method does not imply that the converters are known <i>not</i> to be
405   * interchangeable.
406   */
407  @Override
408  public boolean equals(@Nullable Object object) {
409    return super.equals(object);
410  }
411
412  // Static converters
413
414  /**
415   * Returns a converter based on separate forward and backward functions. This is useful if the
416   * function instances already exist, or so that you can supply lambda expressions. If those
417   * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and
418   * implement its {@link #doForward} and {@link #doBackward} methods directly.
419   *
420   * <p>These functions will never be passed {@code null} and must not under any circumstances
421   * return {@code null}. If a value cannot be converted, the function should throw an unchecked
422   * exception (typically, but not necessarily, {@link IllegalArgumentException}).
423   *
424   * <p>The returned converter is serializable if both provided functions are.
425   *
426   * @since 17.0
427   */
428  public static <A, B> Converter<A, B> from(
429      Function<? super A, ? extends B> forwardFunction,
430      Function<? super B, ? extends A> backwardFunction) {
431    return new FunctionBasedConverter<A, B>(forwardFunction, backwardFunction);
432  }
433
434  private static final class FunctionBasedConverter<A, B> extends Converter<A, B>
435      implements Serializable {
436    private final Function<? super A, ? extends B> forwardFunction;
437    private final Function<? super B, ? extends A> backwardFunction;
438
439    private FunctionBasedConverter(
440        Function<? super A, ? extends B> forwardFunction,
441        Function<? super B, ? extends A> backwardFunction) {
442      this.forwardFunction = checkNotNull(forwardFunction);
443      this.backwardFunction = checkNotNull(backwardFunction);
444    }
445
446    @Override
447    protected B doForward(A a) {
448      return forwardFunction.apply(a);
449    }
450
451    @Override
452    protected A doBackward(B b) {
453      return backwardFunction.apply(b);
454    }
455
456    @Override
457    public boolean equals(@Nullable Object object) {
458      if (object instanceof FunctionBasedConverter) {
459        FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object;
460        return this.forwardFunction.equals(that.forwardFunction)
461            && this.backwardFunction.equals(that.backwardFunction);
462      }
463      return false;
464    }
465
466    @Override
467    public int hashCode() {
468      return forwardFunction.hashCode() * 31 + backwardFunction.hashCode();
469    }
470
471    @Override
472    public String toString() {
473      return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")";
474    }
475  }
476
477  /**
478   * Returns a serializable converter that always converts or reverses an object to itself.
479   */
480  @SuppressWarnings("unchecked") // implementation is "fully variant"
481  public static <T> Converter<T, T> identity() {
482    return (IdentityConverter<T>) IdentityConverter.INSTANCE;
483  }
484
485  /**
486   * A converter that always converts or reverses an object to itself. Note that T is now a
487   * "pass-through type".
488   */
489  private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable {
490    static final IdentityConverter INSTANCE = new IdentityConverter();
491
492    @Override
493    protected T doForward(T t) {
494      return t;
495    }
496
497    @Override
498    protected T doBackward(T t) {
499      return t;
500    }
501
502    @Override
503    public IdentityConverter<T> reverse() {
504      return this;
505    }
506
507    @Override
508    <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) {
509      return checkNotNull(otherConverter, "otherConverter");
510    }
511
512    /*
513     * We *could* override convertAll() to return its input, but it's a rather pointless
514     * optimization and opened up a weird type-safety problem.
515     */
516
517    @Override
518    public String toString() {
519      return "Converter.identity()";
520    }
521
522    private Object readResolve() {
523      return INSTANCE;
524    }
525
526    private static final long serialVersionUID = 0L;
527  }
528}