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.NullnessCasts.uncheckedCastNullableTToT;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.CheckReturnValue;
022import com.google.errorprone.annotations.ForOverride;
023import com.google.errorprone.annotations.InlineMe;
024import com.google.errorprone.annotations.concurrent.LazyInit;
025import com.google.j2objc.annotations.RetainedWith;
026import java.io.Serializable;
027import java.util.Iterator;
028import javax.annotation.CheckForNull;
029
030/**
031 * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B}
032 * to {@code A}; used for converting back and forth between <i>different representations of the same
033 * information</i>.
034 *
035 * <h3>Invertibility</h3>
036 *
037 * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code
038 * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very
039 * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an
040 * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}:
041 *
042 * <ol>
043 *   <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0}
044 *   <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} --
045 *       <i>not</i> the same string ({@code "1.00"}) we started with
046 * </ol>
047 *
048 * <p>Note that it should still be the case that the round-tripped and original objects are
049 * <i>similar</i>.
050 *
051 * <h3>Nullability</h3>
052 *
053 * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null
054 * references. It would not make sense to consider {@code null} and a non-null reference to be
055 * "different representations of the same information", since one is distinguishable from
056 * <i>missing</i> information and the other is not. The {@link #convert} method handles this null
057 * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are
058 * guaranteed to never be passed {@code null}, and must never return {@code null}.
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
070 *       create a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i>
071 *       the {@code Converter} type using a mocking framework.
072 *   <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods.
073 *   <li><b>Java 8 users:</b> you may prefer to pass two lambda expressions or method references to
074 *       the {@link #from from} factory method.
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
085 *       java.util.function.Function} is accepted (for example {@link java.util.stream.Stream#map
086 *       Stream.map}).
087 *   <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to
088 *       be overridden.
089 * </ul>
090 *
091 * <h3>Example</h3>
092 *
093 * <pre>
094 *   return new Converter&lt;Integer, String&gt;() {
095 *     protected String doForward(Integer i) {
096 *       return Integer.toHexString(i);
097 *     }
098 *
099 *     protected Integer doBackward(String s) {
100 *       return parseUnsignedInt(s, 16);
101 *     }
102 *   };</pre>
103 *
104 * <p>An alternative using Java 8:
105 *
106 * <pre>{@code
107 * return Converter.from(
108 *     Integer::toHexString,
109 *     s -> parseUnsignedInt(s, 16));
110 * }</pre>
111 *
112 * @author Mike Ward
113 * @author Kurt Alfred Kluever
114 * @author Gregory Kick
115 * @since 16.0
116 */
117@GwtCompatible
118@ElementTypesAreNonnullByDefault
119/*
120 * 1. The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the
121 * doForward and doBackward methods to indicate that the parameter cannot be null. (We also take
122 * advantage of that for convertAll, as discussed on that method.)
123 *
124 * 2. The supertype of this class could be `Function<@Nullable A, @Nullable B>`, since
125 * Converter.apply (like Converter.convert) is capable of accepting null inputs. However, a
126 * supertype of `Function<A, B>` turns out to be massively more useful to callers in practice: They
127 * want their output to be non-null in operations like `stream.map(myConverter)`, and we can
128 * guarantee that as long as we also require the input type to be non-null[*] (which is a
129 * requirement that existing callers already fulfill).
130 *
131 * Disclaimer: Part of the reason that callers are so well adapted to `Function<A, B>` may be that
132 * that is how the signature looked even prior to this comment! So naturally any change can break
133 * existing users, but it can't *fix* existing users because any users who needed
134 * `Function<@Nullable A, @Nullable B>` already had to find a workaround. Still, there is a *ton* of
135 * fallout from trying to switch. I would be shocked if the switch would offer benefits to anywhere
136 * near enough users to justify the costs.
137 *
138 * Fortunately, if anyone does want to use a Converter as a `Function<@Nullable A, @Nullable B>`,
139 * it's easy to get one: `converter::convert`.
140 *
141 * [*] In annotating this class, we're ignoring LegacyConverter.
142 */
143public abstract class Converter<A, B> implements Function<A, B> {
144  private final boolean handleNullAutomatically;
145
146  // We lazily cache the reverse view to avoid allocating on every call to reverse().
147  @LazyInit @RetainedWith @CheckForNull private transient Converter<B, A> reverse;
148
149  /** Constructor for use by subclasses. */
150  protected Converter() {
151    this(true);
152  }
153
154  /** Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. */
155  Converter(boolean handleNullAutomatically) {
156    this.handleNullAutomatically = handleNullAutomatically;
157  }
158
159  // SPI methods (what subclasses must implement)
160
161  /**
162   * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be
163   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
164   *
165   * @param a the instance to convert; will never be null
166   * @return the converted instance; <b>must not</b> be null
167   */
168  @ForOverride
169  protected abstract B doForward(A a);
170
171  /**
172   * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be
173   * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown.
174   *
175   * @param b the instance to convert; will never be null
176   * @return the converted instance; <b>must not</b> be null
177   * @throws UnsupportedOperationException if backward conversion is not implemented; this should be
178   *     very rare. Note that if backward conversion is not only unimplemented but
179   *     unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}),
180   *     then this is not logically a {@code Converter} at all, and should just implement {@link
181   *     Function}.
182   */
183  @ForOverride
184  protected abstract A doBackward(B b);
185
186  // API (consumer-side) methods
187
188  /**
189   * Returns a representation of {@code a} as an instance of type {@code B}.
190   *
191   * @return the converted value; is null <i>if and only if</i> {@code a} is null
192   */
193  @CheckForNull
194  public final B convert(@CheckForNull A a) {
195    return correctedDoForward(a);
196  }
197
198  @CheckForNull
199  B correctedDoForward(@CheckForNull A a) {
200    if (handleNullAutomatically) {
201      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
202      return a == null ? null : checkNotNull(doForward(a));
203    } else {
204      return unsafeDoForward(a);
205    }
206  }
207
208  @CheckForNull
209  A correctedDoBackward(@CheckForNull B b) {
210    if (handleNullAutomatically) {
211      // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert?
212      return b == null ? null : checkNotNull(doBackward(b));
213    } else {
214      return unsafeDoBackward(b);
215    }
216  }
217
218  /*
219   * LegacyConverter violates the contract of Converter by allowing its doForward and doBackward
220   * methods to accept null. We could avoid having unchecked casts in Converter.java itself if we
221   * could perform a cast to LegacyConverter, but we can't because it's an internal-only class.
222   *
223   * TODO(cpovirk): So make it part of the open-source build, albeit package-private there?
224   *
225   * So we use uncheckedCastNullableTToT here. This is a weird usage of that method: The method is
226   * documented as being for use with type parameters that have parametric nullness. But Converter's
227   * type parameters do not. Still, we use it here so that we can suppress a warning at a smaller
228   * level than the whole method but without performing a runtime null check. That way, we can still
229   * pass null inputs to LegacyConverter, and it can violate the contract of Converter.
230   *
231   * TODO(cpovirk): Could this be simplified if we modified implementations of LegacyConverter to
232   * override methods (probably called "unsafeDoForward" and "unsafeDoBackward") with the same
233   * signatures as the methods below, rather than overriding the same doForward and doBackward
234   * methods as implementations of normal converters do?
235   *
236   * But no matter what we do, it's worth remembering that the resulting code is going to be unsound
237   * in the presence of LegacyConverter, at least in the case of users who view the converter as a
238   * Function<A, B> or who call convertAll (and for any checkers that apply @PolyNull-like semantics
239   * to Converter.convert). So maybe we don't want to think too hard about how to prevent our
240   * checkers from issuing errors related to LegacyConverter, since it turns out that
241   * LegacyConverter does violate the assumptions we make elsewhere.
242   */
243
244  @CheckForNull
245  private B unsafeDoForward(@CheckForNull A a) {
246    return doForward(uncheckedCastNullableTToT(a));
247  }
248
249  @CheckForNull
250  private A unsafeDoBackward(@CheckForNull B b) {
251    return doBackward(uncheckedCastNullableTToT(b));
252  }
253
254  /**
255   * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The
256   * conversion is done lazily.
257   *
258   * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After
259   * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding
260   * element.
261   */
262  /*
263   * Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A,
264   * B>`, convertAll could accept and return iterables with nullable element types. In both cases,
265   * we've chosen to instead use a signature that benefits existing users -- and is still safe.
266   *
267   * For convertAll, I haven't looked as closely at *how* much existing users benefit, so we should
268   * keep an eye out for problems that new users encounter. Note also that convertAll could support
269   * both use cases by using @PolyNull. (By contrast, we can't use @PolyNull for our superinterface
270   * (`implements Function<@PolyNull A, @PolyNull B>`), at least as far as I know.)
271   */
272  public Iterable<B> convertAll(Iterable<? extends A> fromIterable) {
273    checkNotNull(fromIterable, "fromIterable");
274    return new Iterable<B>() {
275      @Override
276      public Iterator<B> iterator() {
277        return new Iterator<B>() {
278          private final Iterator<? extends A> fromIterator = fromIterable.iterator();
279
280          @Override
281          public boolean hasNext() {
282            return fromIterator.hasNext();
283          }
284
285          @Override
286          public B next() {
287            return convert(fromIterator.next());
288          }
289
290          @Override
291          public void remove() {
292            fromIterator.remove();
293          }
294        };
295      }
296    };
297  }
298
299  /**
300   * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a
301   * value roughly equivalent to {@code a}.
302   *
303   * <p>The returned converter is serializable if {@code this} converter is.
304   *
305   * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons.
306   */
307  @CheckReturnValue
308  public Converter<B, A> reverse() {
309    Converter<B, A> result = reverse;
310    return (result == null) ? reverse = new ReverseConverter<>(this) : result;
311  }
312
313  private static final class ReverseConverter<A, B> extends Converter<B, A>
314      implements Serializable {
315    final Converter<A, B> original;
316
317    ReverseConverter(Converter<A, B> original) {
318      this.original = original;
319    }
320
321    /*
322     * These gymnastics are a little confusing. Basically this class has neither legacy nor
323     * non-legacy behavior; it just needs to let the behavior of the backing converter shine
324     * through. So, we override the correctedDo* methods, after which the do* methods should never
325     * be reached.
326     */
327
328    @Override
329    protected A doForward(B b) {
330      throw new AssertionError();
331    }
332
333    @Override
334    protected B doBackward(A a) {
335      throw new AssertionError();
336    }
337
338    @Override
339    @CheckForNull
340    A correctedDoForward(@CheckForNull B b) {
341      return original.correctedDoBackward(b);
342    }
343
344    @Override
345    @CheckForNull
346    B correctedDoBackward(@CheckForNull A a) {
347      return original.correctedDoForward(a);
348    }
349
350    @Override
351    public Converter<A, B> reverse() {
352      return original;
353    }
354
355    @Override
356    public boolean equals(@CheckForNull Object object) {
357      if (object instanceof ReverseConverter) {
358        ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object;
359        return this.original.equals(that.original);
360      }
361      return false;
362    }
363
364    @Override
365    public int hashCode() {
366      return ~original.hashCode();
367    }
368
369    @Override
370    public String toString() {
371      return original + ".reverse()";
372    }
373
374    private static final long serialVersionUID = 0L;
375  }
376
377  /**
378   * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result
379   * of this converter. Its {@code reverse} method applies the converters in reverse order.
380   *
381   * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter}
382   * are.
383   */
384  public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) {
385    return doAndThen(secondConverter);
386  }
387
388  /** Package-private non-final implementation of andThen() so only we can override it. */
389  <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) {
390    return new ConverterComposition<>(this, checkNotNull(secondConverter));
391  }
392
393  private static final class ConverterComposition<A, B, C> extends Converter<A, C>
394      implements Serializable {
395    final Converter<A, B> first;
396    final Converter<B, C> second;
397
398    ConverterComposition(Converter<A, B> first, Converter<B, C> second) {
399      this.first = first;
400      this.second = second;
401    }
402
403    /*
404     * These gymnastics are a little confusing. Basically this class has neither legacy nor
405     * non-legacy behavior; it just needs to let the behaviors of the backing converters shine
406     * through (which might even differ from each other!). So, we override the correctedDo* methods,
407     * after which the do* methods should never be reached.
408     */
409
410    @Override
411    protected C doForward(A a) {
412      throw new AssertionError();
413    }
414
415    @Override
416    protected A doBackward(C c) {
417      throw new AssertionError();
418    }
419
420    @Override
421    @CheckForNull
422    C correctedDoForward(@CheckForNull A a) {
423      return second.correctedDoForward(first.correctedDoForward(a));
424    }
425
426    @Override
427    @CheckForNull
428    A correctedDoBackward(@CheckForNull C c) {
429      return first.correctedDoBackward(second.correctedDoBackward(c));
430    }
431
432    @Override
433    public boolean equals(@CheckForNull Object object) {
434      if (object instanceof ConverterComposition) {
435        ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object;
436        return this.first.equals(that.first) && this.second.equals(that.second);
437      }
438      return false;
439    }
440
441    @Override
442    public int hashCode() {
443      return 31 * first.hashCode() + second.hashCode();
444    }
445
446    @Override
447    public String toString() {
448      return first + ".andThen(" + second + ")";
449    }
450
451    private static final long serialVersionUID = 0L;
452  }
453
454  /**
455   * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead.
456   */
457  @Deprecated
458  @Override
459  @InlineMe(replacement = "this.convert(a)")
460  public final B apply(A a) {
461    /*
462     * Given that we declare this method as accepting and returning non-nullable values (because we
463     * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to
464     * perform runtime null checks on the input and output. (That would also make NullPointerTester
465     * happy!) However, since we didn't do that for many years, we're not about to start now.
466     * (Runtime checks could be particularly bad for users of LegacyConverter.)
467     *
468     * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like
469     * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to
470     * perform even a cast, much less a runtime check.
471     *
472     * All that said, don't forget that everyone should call converter.convert() instead of
473     * converter.apply(), anyway. If clients use only converter.convert(), then their nullness
474     * checkers are unlikely to ever look at the annotations on this declaration.
475     *
476     * Historical note: At one point, we'd declared this method as accepting and returning nullable
477     * values. For details on that, see earlier revisions of this file.
478     */
479    return convert(a);
480  }
481
482  /**
483   * Indicates whether another object is equal to this converter.
484   *
485   * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
486   * However, an implementation may also choose to return {@code true} whenever {@code object} is a
487   * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable"
488   * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for
489   * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false}
490   * result from this method does not imply that the converters are known <i>not</i> to be
491   * interchangeable.
492   */
493  @Override
494  public boolean equals(@CheckForNull Object object) {
495    return super.equals(object);
496  }
497
498  // Static converters
499
500  /**
501   * Returns a converter based on separate forward and backward functions. This is useful if the
502   * function instances already exist, or so that you can supply lambda expressions. If those
503   * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and
504   * implement its {@link #doForward} and {@link #doBackward} methods directly.
505   *
506   * <p>These functions will never be passed {@code null} and must not under any circumstances
507   * return {@code null}. If a value cannot be converted, the function should throw an unchecked
508   * exception (typically, but not necessarily, {@link IllegalArgumentException}).
509   *
510   * <p>The returned converter is serializable if both provided functions are.
511   *
512   * @since 17.0
513   */
514  public static <A, B> Converter<A, B> from(
515      Function<? super A, ? extends B> forwardFunction,
516      Function<? super B, ? extends A> backwardFunction) {
517    return new FunctionBasedConverter<>(forwardFunction, backwardFunction);
518  }
519
520  private static final class FunctionBasedConverter<A, B> extends Converter<A, B>
521      implements Serializable {
522    private final Function<? super A, ? extends B> forwardFunction;
523    private final Function<? super B, ? extends A> backwardFunction;
524
525    private FunctionBasedConverter(
526        Function<? super A, ? extends B> forwardFunction,
527        Function<? super B, ? extends A> backwardFunction) {
528      this.forwardFunction = checkNotNull(forwardFunction);
529      this.backwardFunction = checkNotNull(backwardFunction);
530    }
531
532    @Override
533    protected B doForward(A a) {
534      return forwardFunction.apply(a);
535    }
536
537    @Override
538    protected A doBackward(B b) {
539      return backwardFunction.apply(b);
540    }
541
542    @Override
543    public boolean equals(@CheckForNull Object object) {
544      if (object instanceof FunctionBasedConverter) {
545        FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object;
546        return this.forwardFunction.equals(that.forwardFunction)
547            && this.backwardFunction.equals(that.backwardFunction);
548      }
549      return false;
550    }
551
552    @Override
553    public int hashCode() {
554      return forwardFunction.hashCode() * 31 + backwardFunction.hashCode();
555    }
556
557    @Override
558    public String toString() {
559      return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")";
560    }
561  }
562
563  /** Returns a serializable converter that always converts or reverses an object to itself. */
564  @SuppressWarnings("unchecked") // implementation is "fully variant"
565  public static <T> Converter<T, T> identity() {
566    return (IdentityConverter<T>) IdentityConverter.INSTANCE;
567  }
568
569  /**
570   * A converter that always converts or reverses an object to itself. Note that T is now a
571   * "pass-through type".
572   */
573  private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable {
574    static final Converter<?, ?> INSTANCE = new IdentityConverter<>();
575
576    @Override
577    protected T doForward(T t) {
578      return t;
579    }
580
581    @Override
582    protected T doBackward(T t) {
583      return t;
584    }
585
586    @Override
587    public IdentityConverter<T> reverse() {
588      return this;
589    }
590
591    @Override
592    <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) {
593      return checkNotNull(otherConverter, "otherConverter");
594    }
595
596    /*
597     * We *could* override convertAll() to return its input, but it's a rather pointless
598     * optimization and opened up a weird type-safety problem.
599     */
600
601    @Override
602    public String toString() {
603      return "Converter.identity()";
604    }
605
606    private Object readResolve() {
607      return INSTANCE;
608    }
609
610    private static final long serialVersionUID = 0L;
611  }
612}