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 java.util.stream.Stream; 031import org.jspecify.annotations.Nullable; 032 033/** 034 * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} 035 * to {@code A}; used for converting back and forth between <i>different representations of the same 036 * information</i>. 037 * 038 * <h2>Invertibility</h2> 039 * 040 * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code 041 * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very 042 * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an 043 * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: 044 * 045 * <ol> 046 * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} 047 * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- 048 * <i>not</i> the same string ({@code "1.00"}) we started with 049 * </ol> 050 * 051 * <p>Note that it should still be the case that the round-tripped and original objects are 052 * <i>similar</i>. 053 * 054 * <h2>Nullability</h2> 055 * 056 * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null 057 * references. It would not make sense to consider {@code null} and a non-null reference to be 058 * "different representations of the same information", since one is distinguishable from 059 * <i>missing</i> information and the other is not. The {@link #convert} method handles this null 060 * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are 061 * guaranteed to never be passed {@code null}, and must never return {@code null}. 062 * 063 * <h2>Common ways to use</h2> 064 * 065 * <p>Getting a converter: 066 * 067 * <ul> 068 * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link 069 * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain 070 * #reverse reverse} views of these. 071 * <li>Convert between specific preset values using {@link 072 * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to 073 * create a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> 074 * the {@code Converter} type using a mocking framework. 075 * <li>Pass two lambda expressions or method references to the {@link #from from} factory method. 076 * <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods. 077 * </ul> 078 * 079 * <p>Using a converter: 080 * 081 * <ul> 082 * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. 083 * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. 084 * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code 085 * converter.reverse().convertAll(bs)}. 086 * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link 087 * java.util.function.Function} is accepted (for example {@link Stream#map 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 @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 * <p>We generally encourage using {@link Stream} over lazily computed views like this one. Here, 261 * that means using {@link Stream#map stream.map(converter)}. 262 */ 263 /* 264 * Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A, 265 * B>`, convertAll could accept and return iterables with nullable element types. In both cases, 266 * we've chosen to instead use a signature that benefits existing users -- and is still safe. 267 * 268 * For convertAll, I haven't looked as closely at *how* much existing users benefit, so we should 269 * keep an eye out for problems that new users encounter. Note also that convertAll could support 270 * both use cases by using @PolyNull. (By contrast, we can't use @PolyNull for our superinterface 271 * (`implements Function<@PolyNull A, @PolyNull B>`), at least as far as I know.) 272 */ 273 public Iterable<B> convertAll(Iterable<? extends A> fromIterable) { 274 checkNotNull(fromIterable, "fromIterable"); 275 return () -> 276 new Iterator<B>() { 277 final Iterator<? extends A> fromIterator = fromIterable.iterator(); 278 279 @Override 280 public boolean hasNext() { 281 return fromIterator.hasNext(); 282 } 283 284 @Override 285 public B next() { 286 return convert(fromIterator.next()); 287 } 288 289 @Override 290 public void remove() { 291 fromIterator.remove(); 292 } 293 }; 294 } 295 296 /** 297 * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a 298 * value roughly equivalent to {@code a}. 299 * 300 * <p>The returned converter is serializable if {@code this} converter is. 301 * 302 * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons. 303 */ 304 @CheckReturnValue 305 public Converter<B, A> reverse() { 306 Converter<B, A> result = reverse; 307 if (result == null) { 308 result = reverse = new ReverseConverter<>(this); 309 } 310 return 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 @Nullable A correctedDoForward(@Nullable B b) { 340 return original.correctedDoBackward(b); 341 } 342 343 @Override 344 @Nullable B correctedDoBackward(@Nullable A a) { 345 return original.correctedDoForward(a); 346 } 347 348 @Override 349 public Converter<A, B> reverse() { 350 return original; 351 } 352 353 @Override 354 public boolean equals(@Nullable Object object) { 355 if (object instanceof ReverseConverter) { 356 ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; 357 return this.original.equals(that.original); 358 } 359 return false; 360 } 361 362 @Override 363 public int hashCode() { 364 return ~original.hashCode(); 365 } 366 367 @Override 368 public String toString() { 369 return original + ".reverse()"; 370 } 371 372 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0L; 373 } 374 375 /** 376 * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result 377 * of this converter. Its {@code reverse} method applies the converters in reverse order. 378 * 379 * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} 380 * are. 381 */ 382 public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { 383 return doAndThen(secondConverter); 384 } 385 386 /** Package-private non-final implementation of andThen() so only we can override it. */ 387 <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) { 388 return new ConverterComposition<>(this, checkNotNull(secondConverter)); 389 } 390 391 private static final class ConverterComposition<A, B, C> extends Converter<A, C> 392 implements Serializable { 393 final Converter<A, B> first; 394 final Converter<B, C> second; 395 396 ConverterComposition(Converter<A, B> first, Converter<B, C> second) { 397 this.first = first; 398 this.second = second; 399 } 400 401 /* 402 * These gymnastics are a little confusing. Basically this class has neither legacy nor 403 * non-legacy behavior; it just needs to let the behaviors of the backing converters shine 404 * through (which might even differ from each other!). So, we override the correctedDo* methods, 405 * after which the do* methods should never be reached. 406 */ 407 408 @Override 409 protected C doForward(A a) { 410 throw new AssertionError(); 411 } 412 413 @Override 414 protected A doBackward(C c) { 415 throw new AssertionError(); 416 } 417 418 @Override 419 @Nullable C correctedDoForward(@Nullable A a) { 420 return second.correctedDoForward(first.correctedDoForward(a)); 421 } 422 423 @Override 424 @Nullable A correctedDoBackward(@Nullable C c) { 425 return first.correctedDoBackward(second.correctedDoBackward(c)); 426 } 427 428 @Override 429 public boolean equals(@Nullable Object object) { 430 if (object instanceof ConverterComposition) { 431 ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; 432 return this.first.equals(that.first) && this.second.equals(that.second); 433 } 434 return false; 435 } 436 437 @Override 438 public int hashCode() { 439 return 31 * first.hashCode() + second.hashCode(); 440 } 441 442 @Override 443 public String toString() { 444 return first + ".andThen(" + second + ")"; 445 } 446 447 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0L; 448 } 449 450 /** 451 * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. 452 */ 453 @Deprecated 454 @Override 455 @InlineMe(replacement = "this.convert(a)") 456 public final B apply(A a) { 457 /* 458 * Given that we declare this method as accepting and returning non-nullable values (because we 459 * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to 460 * perform runtime null checks on the input and output. (That would also make NullPointerTester 461 * happy!) However, since we didn't do that for many years, we're not about to start now. 462 * (Runtime checks could be particularly bad for users of LegacyConverter.) 463 * 464 * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like 465 * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to 466 * perform even a cast, much less a runtime check. 467 * 468 * All that said, don't forget that everyone should call converter.convert() instead of 469 * converter.apply(), anyway. If clients use only converter.convert(), then their nullness 470 * checkers are unlikely to ever look at the annotations on this declaration. 471 * 472 * Historical note: At one point, we'd declared this method as accepting and returning nullable 473 * values. For details on that, see earlier revisions of this file. 474 */ 475 return convert(a); 476 } 477 478 /** 479 * <i>May</i> return {@code true} if {@code object} is a {@code Converter} that behaves 480 * identically to this converter. 481 * 482 * <p><b>Warning: do not depend</b> on the behavior of this method. 483 * 484 * <p>Historically, {@code Converter} instances in this library have implemented this method to 485 * recognize certain cases where distinct {@code Converter} instances would in fact behave 486 * identically. However, this is not true of {@code Converter} implementations in general. It is 487 * best not to depend on it. 488 */ 489 @Override 490 public boolean equals(@Nullable Object object) { 491 return super.equals(object); 492 } 493 494 // Static converters 495 496 /** 497 * Returns a converter based on separate forward and backward functions. This is useful if the 498 * function instances already exist, or so that you can supply lambda expressions. If those 499 * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and 500 * implement its {@link #doForward} and {@link #doBackward} methods directly. 501 * 502 * <p>These functions will never be passed {@code null} and must not under any circumstances 503 * return {@code null}. If a value cannot be converted, the function should throw an unchecked 504 * exception (typically, but not necessarily, {@link IllegalArgumentException}). 505 * 506 * <p>The returned converter is serializable if both provided functions are. 507 * 508 * @since 17.0 509 */ 510 public static <A, B> Converter<A, B> from( 511 Function<? super A, ? extends B> forwardFunction, 512 Function<? super B, ? extends A> backwardFunction) { 513 return new FunctionBasedConverter<>(forwardFunction, backwardFunction); 514 } 515 516 private static final class FunctionBasedConverter<A, B> extends Converter<A, B> 517 implements Serializable { 518 private final Function<? super A, ? extends B> forwardFunction; 519 private final Function<? super B, ? extends A> backwardFunction; 520 521 private FunctionBasedConverter( 522 Function<? super A, ? extends B> forwardFunction, 523 Function<? super B, ? extends A> backwardFunction) { 524 this.forwardFunction = checkNotNull(forwardFunction); 525 this.backwardFunction = checkNotNull(backwardFunction); 526 } 527 528 @Override 529 protected B doForward(A a) { 530 return forwardFunction.apply(a); 531 } 532 533 @Override 534 protected A doBackward(B b) { 535 return backwardFunction.apply(b); 536 } 537 538 @Override 539 public boolean equals(@Nullable Object object) { 540 if (object instanceof FunctionBasedConverter) { 541 FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; 542 return this.forwardFunction.equals(that.forwardFunction) 543 && this.backwardFunction.equals(that.backwardFunction); 544 } 545 return false; 546 } 547 548 @Override 549 public int hashCode() { 550 return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); 551 } 552 553 @Override 554 public String toString() { 555 return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; 556 } 557 558 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 6500462374954026321L; 559 } 560 561 /** Returns a serializable converter that always converts or reverses an object to itself. */ 562 @SuppressWarnings("unchecked") // implementation is "fully variant" 563 public static <T> Converter<T, T> identity() { 564 return (IdentityConverter<T>) IdentityConverter.INSTANCE; 565 } 566 567 /** 568 * A converter that always converts or reverses an object to itself. Note that T is now a 569 * "pass-through type". 570 */ 571 private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { 572 static final Converter<?, ?> INSTANCE = new IdentityConverter<>(); 573 574 @Override 575 protected T doForward(T t) { 576 return t; 577 } 578 579 @Override 580 protected T doBackward(T t) { 581 return t; 582 } 583 584 @Override 585 public IdentityConverter<T> reverse() { 586 return this; 587 } 588 589 @Override 590 <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) { 591 return checkNotNull(otherConverter, "otherConverter"); 592 } 593 594 /* 595 * We *could* override convertAll() to return its input, but it's a rather pointless 596 * optimization and opened up a weird type-safety problem. 597 */ 598 599 @Override 600 public String toString() { 601 return "Converter.identity()"; 602 } 603 604 private Object readResolve() { 605 return INSTANCE; 606 } 607 608 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0L; 609 } 610}