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>Otherwise, extend this class and implement its {@link #doForward} and {@link #doBackward}
073 *     methods.
074 * </ul>
075 *
076 * <p>Using a converter:
077 *
078 * <ul>
079 * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}.
080 * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}.
081 * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code
082 *     converter.reverse().convertAll(bs)}.
083 * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link Function} is accepted
084 * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to be
085 *     overridden.
086 * </ul>
087 *
088 * @author Mike Ward
089 * @author Kurt Alfred Kluever
090 * @author Gregory Kick
091 * @since 16.0
092 */
093@Beta
094@GwtCompatible
095public abstract class Converter<A, B> implements Function<A, B> {
096  private final boolean handleNullAutomatically;
097
098  // We lazily cache the reverse view to avoid allocating on every call to reverse().
099  private transient Converter<B, A> reverse;
100
101  /** Constructor for use by subclasses. */
102  protected Converter() {
103    this(true);
104  }
105
106  /**
107   * Constructor used only by {@code LegacyConverter} to suspend automatic null-handling.
108   */
109  Converter(boolean handleNullAutomatically) {
110    this.handleNullAutomatically = handleNullAutomatically;
111  }
112
113  // SPI methods (what subclasses must implement)
114
115  /**
116   * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be
117   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
118   *
119   * @param a the instance to convert; will never be null
120   * @return the converted instance; <b>must not</b> be null
121   */
122  protected abstract B doForward(A a);
123
124  /**
125   * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be
126   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
127   *
128   * @param b the instance to convert; will never be null
129   * @return the converted instance; <b>must not</b> be null
130   * @throws UnsupportedOperationException if backward conversion is not implemented; this should be
131   *     very rare. Note that if backward conversion is not only unimplemented but
132   *     unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}),
133   *     then this is not logically a {@code Converter} at all, and should just implement {@link
134   *     Function}.
135   */
136  protected abstract A doBackward(B b);
137
138  // API (consumer-side) methods
139
140  /**
141   * Returns a representation of {@code a} as an instance of type {@code B}.
142   *
143   * @return the converted value; is null <i>if and only if</i> {@code a} is null
144   */
145  @Nullable
146  public final B convert(@Nullable A a) {
147    return correctedDoForward(a);
148  }
149
150  @Nullable
151  B correctedDoForward(@Nullable A a) {
152    if (handleNullAutomatically) {
153      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
154      return a == null ? null : checkNotNull(doForward(a));
155    } else {
156      return doForward(a);
157    }
158  }
159
160  @Nullable
161  A correctedDoBackward(@Nullable B b) {
162    if (handleNullAutomatically) {
163      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
164      return b == null ? null : checkNotNull(doBackward(b));
165    } else {
166      return doBackward(b);
167    }
168  }
169
170  /**
171   * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The
172   * conversion is done lazily.
173   *
174   * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After
175   * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
176   * element.
177   */
178  public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) {
179    checkNotNull(fromIterable, "fromIterable");
180    return new Iterable<B>() {
181      @Override public Iterator<B> iterator() {
182        return new Iterator<B>() {
183          private final Iterator<? extends A> fromIterator = fromIterable.iterator();
184
185          @Override
186          public boolean hasNext() {
187            return fromIterator.hasNext();
188          }
189
190          @Override
191          public B next() {
192            return convert(fromIterator.next());
193          }
194
195          @Override
196          public void remove() {
197            fromIterator.remove();
198          }
199        };
200      }
201    };
202  }
203
204  /**
205   * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a
206   * value roughly equivalent to {@code a}.
207   *
208   * <p>The returned converter is serializable if {@code this} converter is.
209   */
210  // TODO(user): Make this method final
211  public Converter<B, A> reverse() {
212    Converter<B, A> result = reverse;
213    return (result == null) ? reverse = new ReverseConverter<A, B>(this) : result;
214  }
215
216  private static final class ReverseConverter<A, B>
217      extends Converter<B, A> implements Serializable {
218    final Converter<A, B> original;
219
220    ReverseConverter(Converter<A, B> original) {
221      this.original = original;
222    }
223
224    /*
225     * These gymnastics are a little confusing. Basically this class has neither legacy nor
226     * non-legacy behavior; it just needs to let the behavior of the backing converter shine
227     * through. So, we override the correctedDo* methods, after which the do* methods should never
228     * be reached.
229     */
230
231    @Override
232    protected A doForward(B b) {
233      throw new AssertionError();
234    }
235
236    @Override
237    protected B doBackward(A a) {
238      throw new AssertionError();
239    }
240
241    @Override
242    @Nullable
243    A correctedDoForward(@Nullable B b) {
244      return original.correctedDoBackward(b);
245    }
246
247    @Override
248    @Nullable
249    B correctedDoBackward(@Nullable A a) {
250      return original.correctedDoForward(a);
251    }
252
253    @Override
254    public Converter<A, B> reverse() {
255      return original;
256    }
257
258    @Override
259    public boolean equals(@Nullable Object object) {
260      if (object instanceof ReverseConverter) {
261        ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object;
262        return this.original.equals(that.original);
263      }
264      return false;
265    }
266
267    @Override
268    public int hashCode() {
269      return ~original.hashCode();
270    }
271
272    @Override
273    public String toString() {
274      return original + ".reverse()";
275    }
276
277    private static final long serialVersionUID = 0L;
278  }
279
280  /**
281   * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result
282   * of this converter. Its {@code reverse} method applies the converters in reverse order.
283   *
284   * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter}
285   * are.
286   */
287  public <C> Converter<A, C> andThen(Converter<B, C> secondConverter) {
288    return new ConverterComposition<A, B, C>(this, checkNotNull(secondConverter));
289  }
290
291  private static final class ConverterComposition<A, B, C>
292      extends Converter<A, C> implements Serializable {
293    final Converter<A, B> first;
294    final Converter<B, C> second;
295
296    ConverterComposition(Converter<A, B> first, Converter<B, C> second) {
297      this.first = first;
298      this.second = second;
299    }
300
301    /*
302     * These gymnastics are a little confusing. Basically this class has neither legacy nor
303     * non-legacy behavior; it just needs to let the behaviors of the backing converters shine
304     * through (which might even differ from each other!). So, we override the correctedDo* methods,
305     * after which the do* methods should never be reached.
306     */
307
308    @Override
309    protected C doForward(A a) {
310      throw new AssertionError();
311    }
312
313    @Override
314    protected A doBackward(C c) {
315      throw new AssertionError();
316    }
317
318    @Override
319    @Nullable
320    C correctedDoForward(@Nullable A a) {
321      return second.correctedDoForward(first.correctedDoForward(a));
322    }
323
324    @Override
325    @Nullable
326    A correctedDoBackward(@Nullable C c) {
327      return first.correctedDoBackward(second.correctedDoBackward(c));
328    }
329
330    @Override
331    public boolean equals(@Nullable Object object) {
332      if (object instanceof ConverterComposition) {
333        ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object;
334        return this.first.equals(that.first)
335            && this.second.equals(that.second);
336      }
337      return false;
338    }
339
340    @Override
341    public int hashCode() {
342      return 31 * first.hashCode() + second.hashCode();
343    }
344
345    @Override
346    public String toString() {
347      return first + ".andThen(" + second + ")";
348    }
349
350    private static final long serialVersionUID = 0L;
351  }
352
353  /**
354   * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead.
355   */
356  @Deprecated
357  @Override
358  @Nullable
359  public final B apply(@Nullable A a) {
360    return convert(a);
361  }
362
363  /**
364   * Indicates whether another object is equal to this converter.
365   *
366   * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
367   * However, an implementation may also choose to return {@code true} whenever {@code object} is a
368   * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable"
369   * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for
370   * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false}
371   * result from this method does not imply that the converters are known <i>not</i> to be
372   * interchangeable.
373   */
374  @Override
375  public boolean equals(@Nullable Object object) {
376    return super.equals(object);
377  }
378
379  // Static converters
380
381  /**
382   * Returns a converter based on <i>existing</i> forward and backward functions. Note that it is
383   * unnecessary to create <i>new</i> classes implementing {@code Function} just to pass them in
384   * here. Instead, simply subclass {@code Converter} and implement its {@link #doForward} and
385   * {@link #doBackward} methods directly.
386   *
387   * <p>These functions will never be passed {@code null} and must not under any circumstances
388   * return {@code null}. If a value cannot be converted, the function should throw an unchecked
389   * exception (typically, but not necessarily, {@link IllegalArgumentException}).
390   *
391   * <p>The returned converter is serializable if both provided functions are.
392   *
393   * @since 17.0
394   */
395  public static <A, B> Converter<A, B> from(
396      Function<? super A, ? extends B> forwardFunction,
397      Function<? super B, ? extends A> backwardFunction) {
398    return new FunctionBasedConverter<A, B>(forwardFunction, backwardFunction);
399  }
400
401  private static final class FunctionBasedConverter<A, B>
402      extends Converter<A, B> implements Serializable {
403    private final Function<? super A, ? extends B> forwardFunction;
404    private final Function<? super B, ? extends A> backwardFunction;
405
406    private FunctionBasedConverter(
407        Function<? super A, ? extends B> forwardFunction,
408        Function<? super B, ? extends A> backwardFunction) {
409      this.forwardFunction = checkNotNull(forwardFunction);
410      this.backwardFunction = checkNotNull(backwardFunction);
411    }
412
413    @Override
414    protected B doForward(A a) {
415      return forwardFunction.apply(a);
416    }
417
418    @Override
419    protected A doBackward(B b) {
420      return backwardFunction.apply(b);
421    }
422
423    @Override
424    public boolean equals(@Nullable Object object) {
425      if (object instanceof FunctionBasedConverter) {
426        FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object;
427        return this.forwardFunction.equals(that.forwardFunction)
428            && this.backwardFunction.equals(that.backwardFunction);
429      }
430      return false;
431    }
432
433    @Override
434    public int hashCode() {
435      return forwardFunction.hashCode() * 31 + backwardFunction.hashCode();
436    }
437
438    @Override
439    public String toString() {
440      return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")";
441    }
442  }
443
444  /**
445   * Returns a serializable converter that always converts or reverses an object to itself.
446   */
447  @SuppressWarnings("unchecked") // implementation is "fully variant"
448  public static <T> Converter<T, T> identity() {
449    return (IdentityConverter<T>) IdentityConverter.INSTANCE;
450  }
451
452  /**
453   * A converter that always converts or reverses an object to itself. Note that T is now a
454   * "pass-through type".
455   */
456  private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable {
457    static final IdentityConverter INSTANCE = new IdentityConverter();
458
459    @Override
460    protected T doForward(T t) {
461      return t;
462    }
463
464    @Override
465    protected T doBackward(T t) {
466      return t;
467    }
468
469    @Override
470    public IdentityConverter<T> reverse() {
471      return this;
472    }
473
474    @Override
475    public <S> Converter<T, S> andThen(Converter<T, S> otherConverter) {
476      return checkNotNull(otherConverter, "otherConverter");
477    }
478
479    /*
480     * We *could* override convertAll() to return its input, but it's a rather pointless
481     * optimization and opened up a weird type-safety problem.
482     */
483
484    @Override
485    public String toString() {
486      return "Converter.identity()";
487    }
488
489    private Object readResolve() {
490      return INSTANCE;
491    }
492
493    private static final long serialVersionUID = 0L;
494  }
495}