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 org.jspecify.annotations.Nullable; 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 private transient @Nullable 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 public final @Nullable B convert(@Nullable A a) { 193 return correctedDoForward(a); 194 } 195 196 @Nullable B correctedDoForward(@Nullable A a) { 197 if (handleNullAutomatically) { 198 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 199 return a == null ? null : checkNotNull(doForward(a)); 200 } else { 201 return unsafeDoForward(a); 202 } 203 } 204 205 @Nullable A correctedDoBackward(@Nullable B b) { 206 if (handleNullAutomatically) { 207 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 208 return b == null ? null : checkNotNull(doBackward(b)); 209 } else { 210 return unsafeDoBackward(b); 211 } 212 } 213 214 /* 215 * LegacyConverter violates the contract of Converter by allowing its doForward and doBackward 216 * methods to accept null. We could avoid having unchecked casts in Converter.java itself if we 217 * could perform a cast to LegacyConverter, but we can't because it's an internal-only class. 218 * 219 * TODO(cpovirk): So make it part of the open-source build, albeit package-private there? 220 * 221 * So we use uncheckedCastNullableTToT here. This is a weird usage of that method: The method is 222 * documented as being for use with type parameters that have parametric nullness. But Converter's 223 * type parameters do not. Still, we use it here so that we can suppress a warning at a smaller 224 * level than the whole method but without performing a runtime null check. That way, we can still 225 * pass null inputs to LegacyConverter, and it can violate the contract of Converter. 226 * 227 * TODO(cpovirk): Could this be simplified if we modified implementations of LegacyConverter to 228 * override methods (probably called "unsafeDoForward" and "unsafeDoBackward") with the same 229 * signatures as the methods below, rather than overriding the same doForward and doBackward 230 * methods as implementations of normal converters do? 231 * 232 * But no matter what we do, it's worth remembering that the resulting code is going to be unsound 233 * in the presence of LegacyConverter, at least in the case of users who view the converter as a 234 * Function<A, B> or who call convertAll (and for any checkers that apply @PolyNull-like semantics 235 * to Converter.convert). So maybe we don't want to think too hard about how to prevent our 236 * checkers from issuing errors related to LegacyConverter, since it turns out that 237 * LegacyConverter does violate the assumptions we make elsewhere. 238 */ 239 240 private @Nullable B unsafeDoForward(@Nullable A a) { 241 return doForward(uncheckedCastNullableTToT(a)); 242 } 243 244 private @Nullable A unsafeDoBackward(@Nullable B b) { 245 return doBackward(uncheckedCastNullableTToT(b)); 246 } 247 248 /** 249 * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The 250 * conversion is done lazily. 251 * 252 * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After 253 * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding 254 * element. 255 */ 256 /* 257 * Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A, 258 * B>`, convertAll could accept and return iterables with nullable element types. In both cases, 259 * we've chosen to instead use a signature that benefits existing users -- and is still safe. 260 * 261 * For convertAll, I haven't looked as closely at *how* much existing users benefit, so we should 262 * keep an eye out for problems that new users encounter. Note also that convertAll could support 263 * both use cases by using @PolyNull. (By contrast, we can't use @PolyNull for our superinterface 264 * (`implements Function<@PolyNull A, @PolyNull B>`), at least as far as I know.) 265 */ 266 public Iterable<B> convertAll(Iterable<? extends A> fromIterable) { 267 checkNotNull(fromIterable, "fromIterable"); 268 return new Iterable<B>() { 269 @Override 270 public Iterator<B> iterator() { 271 return new Iterator<B>() { 272 private final Iterator<? extends A> fromIterator = fromIterable.iterator(); 273 274 @Override 275 public boolean hasNext() { 276 return fromIterator.hasNext(); 277 } 278 279 @Override 280 public B next() { 281 return convert(fromIterator.next()); 282 } 283 284 @Override 285 public void remove() { 286 fromIterator.remove(); 287 } 288 }; 289 } 290 }; 291 } 292 293 /** 294 * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a 295 * value roughly equivalent to {@code a}. 296 * 297 * <p>The returned converter is serializable if {@code this} converter is. 298 * 299 * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons. 300 */ 301 @CheckReturnValue 302 public Converter<B, A> reverse() { 303 Converter<B, A> result = reverse; 304 return (result == null) ? reverse = new ReverseConverter<>(this) : result; 305 } 306 307 private static final class ReverseConverter<A, B> extends Converter<B, A> 308 implements Serializable { 309 final Converter<A, B> original; 310 311 ReverseConverter(Converter<A, B> original) { 312 this.original = original; 313 } 314 315 /* 316 * These gymnastics are a little confusing. Basically this class has neither legacy nor 317 * non-legacy behavior; it just needs to let the behavior of the backing converter shine 318 * through. So, we override the correctedDo* methods, after which the do* methods should never 319 * be reached. 320 */ 321 322 @Override 323 protected A doForward(B b) { 324 throw new AssertionError(); 325 } 326 327 @Override 328 protected B doBackward(A a) { 329 throw new AssertionError(); 330 } 331 332 @Override 333 @Nullable A correctedDoForward(@Nullable B b) { 334 return original.correctedDoBackward(b); 335 } 336 337 @Override 338 @Nullable B correctedDoBackward(@Nullable A a) { 339 return original.correctedDoForward(a); 340 } 341 342 @Override 343 public Converter<A, B> reverse() { 344 return original; 345 } 346 347 @Override 348 public boolean equals(@Nullable Object object) { 349 if (object instanceof ReverseConverter) { 350 ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; 351 return this.original.equals(that.original); 352 } 353 return false; 354 } 355 356 @Override 357 public int hashCode() { 358 return ~original.hashCode(); 359 } 360 361 @Override 362 public String toString() { 363 return original + ".reverse()"; 364 } 365 366 private static final long serialVersionUID = 0L; 367 } 368 369 /** 370 * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result 371 * of this converter. Its {@code reverse} method applies the converters in reverse order. 372 * 373 * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} 374 * are. 375 */ 376 public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { 377 return doAndThen(secondConverter); 378 } 379 380 /** Package-private non-final implementation of andThen() so only we can override it. */ 381 <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) { 382 return new ConverterComposition<>(this, checkNotNull(secondConverter)); 383 } 384 385 private static final class ConverterComposition<A, B, C> extends Converter<A, C> 386 implements Serializable { 387 final Converter<A, B> first; 388 final Converter<B, C> second; 389 390 ConverterComposition(Converter<A, B> first, Converter<B, C> second) { 391 this.first = first; 392 this.second = second; 393 } 394 395 /* 396 * These gymnastics are a little confusing. Basically this class has neither legacy nor 397 * non-legacy behavior; it just needs to let the behaviors of the backing converters shine 398 * through (which might even differ from each other!). So, we override the correctedDo* methods, 399 * after which the do* methods should never be reached. 400 */ 401 402 @Override 403 protected C doForward(A a) { 404 throw new AssertionError(); 405 } 406 407 @Override 408 protected A doBackward(C c) { 409 throw new AssertionError(); 410 } 411 412 @Override 413 @Nullable C correctedDoForward(@Nullable A a) { 414 return second.correctedDoForward(first.correctedDoForward(a)); 415 } 416 417 @Override 418 @Nullable A correctedDoBackward(@Nullable C c) { 419 return first.correctedDoBackward(second.correctedDoBackward(c)); 420 } 421 422 @Override 423 public boolean equals(@Nullable Object object) { 424 if (object instanceof ConverterComposition) { 425 ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; 426 return this.first.equals(that.first) && this.second.equals(that.second); 427 } 428 return false; 429 } 430 431 @Override 432 public int hashCode() { 433 return 31 * first.hashCode() + second.hashCode(); 434 } 435 436 @Override 437 public String toString() { 438 return first + ".andThen(" + second + ")"; 439 } 440 441 private static final long serialVersionUID = 0L; 442 } 443 444 /** 445 * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. 446 */ 447 @Deprecated 448 @Override 449 @InlineMe(replacement = "this.convert(a)") 450 public final B apply(A a) { 451 /* 452 * Given that we declare this method as accepting and returning non-nullable values (because we 453 * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to 454 * perform runtime null checks on the input and output. (That would also make NullPointerTester 455 * happy!) However, since we didn't do that for many years, we're not about to start now. 456 * (Runtime checks could be particularly bad for users of LegacyConverter.) 457 * 458 * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like 459 * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to 460 * perform even a cast, much less a runtime check. 461 * 462 * All that said, don't forget that everyone should call converter.convert() instead of 463 * converter.apply(), anyway. If clients use only converter.convert(), then their nullness 464 * checkers are unlikely to ever look at the annotations on this declaration. 465 * 466 * Historical note: At one point, we'd declared this method as accepting and returning nullable 467 * values. For details on that, see earlier revisions of this file. 468 */ 469 return convert(a); 470 } 471 472 /** 473 * Indicates whether another object is equal to this converter. 474 * 475 * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. 476 * However, an implementation may also choose to return {@code true} whenever {@code object} is a 477 * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" 478 * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for 479 * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} 480 * result from this method does not imply that the converters are known <i>not</i> to be 481 * interchangeable. 482 */ 483 @Override 484 public boolean equals(@Nullable Object object) { 485 return super.equals(object); 486 } 487 488 // Static converters 489 490 /** 491 * Returns a converter based on separate forward and backward functions. This is useful if the 492 * function instances already exist, or so that you can supply lambda expressions. If those 493 * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and 494 * implement its {@link #doForward} and {@link #doBackward} methods directly. 495 * 496 * <p>These functions will never be passed {@code null} and must not under any circumstances 497 * return {@code null}. If a value cannot be converted, the function should throw an unchecked 498 * exception (typically, but not necessarily, {@link IllegalArgumentException}). 499 * 500 * <p>The returned converter is serializable if both provided functions are. 501 * 502 * @since 17.0 503 */ 504 public static <A, B> Converter<A, B> from( 505 Function<? super A, ? extends B> forwardFunction, 506 Function<? super B, ? extends A> backwardFunction) { 507 return new FunctionBasedConverter<>(forwardFunction, backwardFunction); 508 } 509 510 private static final class FunctionBasedConverter<A, B> extends Converter<A, B> 511 implements Serializable { 512 private final Function<? super A, ? extends B> forwardFunction; 513 private final Function<? super B, ? extends A> backwardFunction; 514 515 private FunctionBasedConverter( 516 Function<? super A, ? extends B> forwardFunction, 517 Function<? super B, ? extends A> backwardFunction) { 518 this.forwardFunction = checkNotNull(forwardFunction); 519 this.backwardFunction = checkNotNull(backwardFunction); 520 } 521 522 @Override 523 protected B doForward(A a) { 524 return forwardFunction.apply(a); 525 } 526 527 @Override 528 protected A doBackward(B b) { 529 return backwardFunction.apply(b); 530 } 531 532 @Override 533 public boolean equals(@Nullable Object object) { 534 if (object instanceof FunctionBasedConverter) { 535 FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; 536 return this.forwardFunction.equals(that.forwardFunction) 537 && this.backwardFunction.equals(that.backwardFunction); 538 } 539 return false; 540 } 541 542 @Override 543 public int hashCode() { 544 return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); 545 } 546 547 @Override 548 public String toString() { 549 return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; 550 } 551 } 552 553 /** Returns a serializable converter that always converts or reverses an object to itself. */ 554 @SuppressWarnings("unchecked") // implementation is "fully variant" 555 public static <T> Converter<T, T> identity() { 556 return (IdentityConverter<T>) IdentityConverter.INSTANCE; 557 } 558 559 /** 560 * A converter that always converts or reverses an object to itself. Note that T is now a 561 * "pass-through type". 562 */ 563 private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { 564 static final Converter<?, ?> INSTANCE = new IdentityConverter<>(); 565 566 @Override 567 protected T doForward(T t) { 568 return t; 569 } 570 571 @Override 572 protected T doBackward(T t) { 573 return t; 574 } 575 576 @Override 577 public IdentityConverter<T> reverse() { 578 return this; 579 } 580 581 @Override 582 <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) { 583 return checkNotNull(otherConverter, "otherConverter"); 584 } 585 586 /* 587 * We *could* override convertAll() to return its input, but it's a rather pointless 588 * optimization and opened up a weird type-safety problem. 589 */ 590 591 @Override 592 public String toString() { 593 return "Converter.identity()"; 594 } 595 596 private Object readResolve() { 597 return INSTANCE; 598 } 599 600 private static final long serialVersionUID = 0L; 601 } 602}