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