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