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