001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.base; 016 017import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT; 018import static com.google.common.base.Preconditions.checkNotNull; 019 020import com.google.common.annotations.GwtCompatible; 021import com.google.errorprone.annotations.CheckReturnValue; 022import com.google.errorprone.annotations.ForOverride; 023import com.google.errorprone.annotations.InlineMe; 024import com.google.errorprone.annotations.concurrent.LazyInit; 025import com.google.j2objc.annotations.RetainedWith; 026import java.io.Serializable; 027import java.util.Iterator; 028import javax.annotation.CheckForNull; 029 030/** 031 * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} 032 * to {@code A}; used for converting back and forth between <i>different representations of the same 033 * information</i>. 034 * 035 * <h3>Invertibility</h3> 036 * 037 * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code 038 * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very 039 * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an 040 * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: 041 * 042 * <ol> 043 * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} 044 * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- 045 * <i>not</i> the same string ({@code "1.00"}) we started with 046 * </ol> 047 * 048 * <p>Note that it should still be the case that the round-tripped and original objects are 049 * <i>similar</i>. 050 * 051 * <h3>Nullability</h3> 052 * 053 * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null 054 * references. It would not make sense to consider {@code null} and a non-null reference to be 055 * "different representations of the same information", since one is distinguishable from 056 * <i>missing</i> information and the other is not. The {@link #convert} method handles this null 057 * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are 058 * guaranteed to never be passed {@code null}, and must never return {@code null}. 059 * 060 * <h3>Common ways to use</h3> 061 * 062 * <p>Getting a converter: 063 * 064 * <ul> 065 * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link 066 * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain 067 * #reverse reverse} views of these. 068 * <li>Convert between specific preset values using {@link 069 * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to 070 * create a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> 071 * the {@code Converter} type using a mocking framework. 072 * <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods. 073 * <li><b>Java 8+ users:</b> you may prefer to pass two lambda expressions or method references to 074 * the {@link #from from} factory method. 075 * </ul> 076 * 077 * <p>Using a converter: 078 * 079 * <ul> 080 * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. 081 * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. 082 * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code 083 * converter.reverse().convertAll(bs)}. 084 * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link 085 * java.util.function.Function} is accepted (for example {@link java.util.stream.Stream#map 086 * Stream.map}). 087 * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to 088 * be overridden. 089 * </ul> 090 * 091 * <h3>Example</h3> 092 * 093 * <pre> 094 * return new Converter<Integer, String>() { 095 * protected String doForward(Integer i) { 096 * return Integer.toHexString(i); 097 * } 098 * 099 * protected Integer doBackward(String s) { 100 * return parseUnsignedInt(s, 16); 101 * } 102 * };</pre> 103 * 104 * <p>An alternative using Java 8: 105 * 106 * <pre>{@code 107 * return Converter.from( 108 * Integer::toHexString, 109 * s -> parseUnsignedInt(s, 16)); 110 * }</pre> 111 * 112 * @author Mike Ward 113 * @author Kurt Alfred Kluever 114 * @author Gregory Kick 115 * @since 16.0 116 */ 117@GwtCompatible 118/* 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 @CheckForNull 193 public final B convert(@CheckForNull A a) { 194 return correctedDoForward(a); 195 } 196 197 @CheckForNull 198 B correctedDoForward(@CheckForNull A a) { 199 if (handleNullAutomatically) { 200 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 201 return a == null ? null : checkNotNull(doForward(a)); 202 } else { 203 return unsafeDoForward(a); 204 } 205 } 206 207 @CheckForNull 208 A correctedDoBackward(@CheckForNull B b) { 209 if (handleNullAutomatically) { 210 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 211 return b == null ? null : checkNotNull(doBackward(b)); 212 } else { 213 return unsafeDoBackward(b); 214 } 215 } 216 217 /* 218 * LegacyConverter violates the contract of Converter by allowing its doForward and doBackward 219 * methods to accept null. We could avoid having unchecked casts in Converter.java itself if we 220 * could perform a cast to LegacyConverter, but we can't because it's an internal-only class. 221 * 222 * TODO(cpovirk): So make it part of the open-source build, albeit package-private there? 223 * 224 * So we use uncheckedCastNullableTToT here. This is a weird usage of that method: The method is 225 * documented as being for use with type parameters that have parametric nullness. But Converter's 226 * type parameters do not. Still, we use it here so that we can suppress a warning at a smaller 227 * level than the whole method but without performing a runtime null check. That way, we can still 228 * pass null inputs to LegacyConverter, and it can violate the contract of Converter. 229 * 230 * TODO(cpovirk): Could this be simplified if we modified implementations of LegacyConverter to 231 * override methods (probably called "unsafeDoForward" and "unsafeDoBackward") with the same 232 * signatures as the methods below, rather than overriding the same doForward and doBackward 233 * methods as implementations of normal converters do? 234 * 235 * But no matter what we do, it's worth remembering that the resulting code is going to be unsound 236 * in the presence of LegacyConverter, at least in the case of users who view the converter as a 237 * Function<A, B> or who call convertAll (and for any checkers that apply @PolyNull-like semantics 238 * to Converter.convert). So maybe we don't want to think too hard about how to prevent our 239 * checkers from issuing errors related to LegacyConverter, since it turns out that 240 * LegacyConverter does violate the assumptions we make elsewhere. 241 */ 242 243 @CheckForNull 244 private B unsafeDoForward(@CheckForNull A a) { 245 return doForward(uncheckedCastNullableTToT(a)); 246 } 247 248 @CheckForNull 249 private A unsafeDoBackward(@CheckForNull B b) { 250 return doBackward(uncheckedCastNullableTToT(b)); 251 } 252 253 /** 254 * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The 255 * conversion is done lazily. 256 * 257 * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After 258 * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding 259 * element. 260 */ 261 /* 262 * Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A, 263 * B>`, convertAll could accept and return iterables with nullable element types. In both cases, 264 * we've chosen to instead use a signature that benefits existing users -- and is still safe. 265 * 266 * For convertAll, I haven't looked as closely at *how* much existing users benefit, so we should 267 * keep an eye out for problems that new users encounter. Note also that convertAll could support 268 * both use cases by using @PolyNull. (By contrast, we can't use @PolyNull for our superinterface 269 * (`implements Function<@PolyNull A, @PolyNull B>`), at least as far as I know.) 270 */ 271 public Iterable<B> convertAll(Iterable<? extends A> fromIterable) { 272 checkNotNull(fromIterable, "fromIterable"); 273 return new Iterable<B>() { 274 @Override 275 public Iterator<B> iterator() { 276 return new Iterator<B>() { 277 private 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 298 /** 299 * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a 300 * value roughly equivalent to {@code a}. 301 * 302 * <p>The returned converter is serializable if {@code this} converter is. 303 * 304 * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons. 305 */ 306 @CheckReturnValue 307 public Converter<B, A> reverse() { 308 Converter<B, A> result = reverse; 309 return (result == null) ? reverse = new ReverseConverter<>(this) : result; 310 } 311 312 private static final class ReverseConverter<A, B> extends Converter<B, A> 313 implements Serializable { 314 final Converter<A, B> original; 315 316 ReverseConverter(Converter<A, B> original) { 317 this.original = original; 318 } 319 320 /* 321 * These gymnastics are a little confusing. Basically this class has neither legacy nor 322 * non-legacy behavior; it just needs to let the behavior of the backing converter shine 323 * through. So, we override the correctedDo* methods, after which the do* methods should never 324 * be reached. 325 */ 326 327 @Override 328 protected A doForward(B b) { 329 throw new AssertionError(); 330 } 331 332 @Override 333 protected B doBackward(A a) { 334 throw new AssertionError(); 335 } 336 337 @Override 338 @CheckForNull 339 A correctedDoForward(@CheckForNull B b) { 340 return original.correctedDoBackward(b); 341 } 342 343 @Override 344 @CheckForNull 345 B correctedDoBackward(@CheckForNull A a) { 346 return original.correctedDoForward(a); 347 } 348 349 @Override 350 public Converter<A, B> reverse() { 351 return original; 352 } 353 354 @Override 355 public boolean equals(@CheckForNull Object object) { 356 if (object instanceof ReverseConverter) { 357 ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; 358 return this.original.equals(that.original); 359 } 360 return false; 361 } 362 363 @Override 364 public int hashCode() { 365 return ~original.hashCode(); 366 } 367 368 @Override 369 public String toString() { 370 return original + ".reverse()"; 371 } 372 373 private static final long serialVersionUID = 0L; 374 } 375 376 /** 377 * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result 378 * of this converter. Its {@code reverse} method applies the converters in reverse order. 379 * 380 * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} 381 * are. 382 */ 383 public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { 384 return doAndThen(secondConverter); 385 } 386 387 /** Package-private non-final implementation of andThen() so only we can override it. */ 388 <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) { 389 return new ConverterComposition<>(this, checkNotNull(secondConverter)); 390 } 391 392 private static final class ConverterComposition<A, B, C> extends Converter<A, C> 393 implements Serializable { 394 final Converter<A, B> first; 395 final Converter<B, C> second; 396 397 ConverterComposition(Converter<A, B> first, Converter<B, C> second) { 398 this.first = first; 399 this.second = second; 400 } 401 402 /* 403 * These gymnastics are a little confusing. Basically this class has neither legacy nor 404 * non-legacy behavior; it just needs to let the behaviors of the backing converters shine 405 * through (which might even differ from each other!). So, we override the correctedDo* methods, 406 * after which the do* methods should never be reached. 407 */ 408 409 @Override 410 protected C doForward(A a) { 411 throw new AssertionError(); 412 } 413 414 @Override 415 protected A doBackward(C c) { 416 throw new AssertionError(); 417 } 418 419 @Override 420 @CheckForNull 421 C correctedDoForward(@CheckForNull A a) { 422 return second.correctedDoForward(first.correctedDoForward(a)); 423 } 424 425 @Override 426 @CheckForNull 427 A correctedDoBackward(@CheckForNull C c) { 428 return first.correctedDoBackward(second.correctedDoBackward(c)); 429 } 430 431 @Override 432 public boolean equals(@CheckForNull Object object) { 433 if (object instanceof ConverterComposition) { 434 ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; 435 return this.first.equals(that.first) && this.second.equals(that.second); 436 } 437 return false; 438 } 439 440 @Override 441 public int hashCode() { 442 return 31 * first.hashCode() + second.hashCode(); 443 } 444 445 @Override 446 public String toString() { 447 return first + ".andThen(" + second + ")"; 448 } 449 450 private static final long serialVersionUID = 0L; 451 } 452 453 /** 454 * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. 455 */ 456 @Deprecated 457 @Override 458 @InlineMe(replacement = "this.convert(a)") 459 public final B apply(A a) { 460 /* 461 * Given that we declare this method as accepting and returning non-nullable values (because we 462 * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to 463 * perform runtime null checks on the input and output. (That would also make NullPointerTester 464 * happy!) However, since we didn't do that for many years, we're not about to start now. 465 * (Runtime checks could be particularly bad for users of LegacyConverter.) 466 * 467 * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like 468 * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to 469 * perform even a cast, much less a runtime check. 470 * 471 * All that said, don't forget that everyone should call converter.convert() instead of 472 * converter.apply(), anyway. If clients use only converter.convert(), then their nullness 473 * checkers are unlikely to ever look at the annotations on this declaration. 474 * 475 * Historical note: At one point, we'd declared this method as accepting and returning nullable 476 * values. For details on that, see earlier revisions of this file. 477 */ 478 return convert(a); 479 } 480 481 /** 482 * Indicates whether another object is equal to this converter. 483 * 484 * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. 485 * However, an implementation may also choose to return {@code true} whenever {@code object} is a 486 * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" 487 * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for 488 * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} 489 * result from this method does not imply that the converters are known <i>not</i> to be 490 * interchangeable. 491 */ 492 @Override 493 public boolean equals(@CheckForNull Object object) { 494 return super.equals(object); 495 } 496 497 // Static converters 498 499 /** 500 * Returns a converter based on separate forward and backward functions. This is useful if the 501 * function instances already exist, or so that you can supply lambda expressions. If those 502 * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and 503 * implement its {@link #doForward} and {@link #doBackward} methods directly. 504 * 505 * <p>These functions will never be passed {@code null} and must not under any circumstances 506 * return {@code null}. If a value cannot be converted, the function should throw an unchecked 507 * exception (typically, but not necessarily, {@link IllegalArgumentException}). 508 * 509 * <p>The returned converter is serializable if both provided functions are. 510 * 511 * @since 17.0 512 */ 513 public static <A, B> Converter<A, B> from( 514 Function<? super A, ? extends B> forwardFunction, 515 Function<? super B, ? extends A> backwardFunction) { 516 return new FunctionBasedConverter<>(forwardFunction, backwardFunction); 517 } 518 519 private static final class FunctionBasedConverter<A, B> extends Converter<A, B> 520 implements Serializable { 521 private final Function<? super A, ? extends B> forwardFunction; 522 private final Function<? super B, ? extends A> backwardFunction; 523 524 private FunctionBasedConverter( 525 Function<? super A, ? extends B> forwardFunction, 526 Function<? super B, ? extends A> backwardFunction) { 527 this.forwardFunction = checkNotNull(forwardFunction); 528 this.backwardFunction = checkNotNull(backwardFunction); 529 } 530 531 @Override 532 protected B doForward(A a) { 533 return forwardFunction.apply(a); 534 } 535 536 @Override 537 protected A doBackward(B b) { 538 return backwardFunction.apply(b); 539 } 540 541 @Override 542 public boolean equals(@CheckForNull Object object) { 543 if (object instanceof FunctionBasedConverter) { 544 FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; 545 return this.forwardFunction.equals(that.forwardFunction) 546 && this.backwardFunction.equals(that.backwardFunction); 547 } 548 return false; 549 } 550 551 @Override 552 public int hashCode() { 553 return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); 554 } 555 556 @Override 557 public String toString() { 558 return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; 559 } 560 } 561 562 /** Returns a serializable converter that always converts or reverses an object to itself. */ 563 @SuppressWarnings("unchecked") // implementation is "fully variant" 564 public static <T> Converter<T, T> identity() { 565 return (IdentityConverter<T>) IdentityConverter.INSTANCE; 566 } 567 568 /** 569 * A converter that always converts or reverses an object to itself. Note that T is now a 570 * "pass-through type". 571 */ 572 private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { 573 static final Converter<?, ?> INSTANCE = new IdentityConverter<>(); 574 575 @Override 576 protected T doForward(T t) { 577 return t; 578 } 579 580 @Override 581 protected T doBackward(T t) { 582 return t; 583 } 584 585 @Override 586 public IdentityConverter<T> reverse() { 587 return this; 588 } 589 590 @Override 591 <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) { 592 return checkNotNull(otherConverter, "otherConverter"); 593 } 594 595 /* 596 * We *could* override convertAll() to return its input, but it's a rather pointless 597 * optimization and opened up a weird type-safety problem. 598 */ 599 600 @Override 601 public String toString() { 602 return "Converter.identity()"; 603 } 604 605 private Object readResolve() { 606 return INSTANCE; 607 } 608 609 private static final long serialVersionUID = 0L; 610 } 611}