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