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