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