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