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.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtCompatible; 020import com.google.errorprone.annotations.CanIgnoreReturnValue; 021import com.google.errorprone.annotations.ForOverride; 022import com.google.errorprone.annotations.concurrent.LazyInit; 023import java.io.Serializable; 024import java.util.Iterator; 025import org.checkerframework.checker.nullness.qual.Nullable; 026 027/** 028 * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} 029 * to {@code A}; used for converting back and forth between <i>different representations of the same 030 * information</i>. 031 * 032 * <h3>Invertibility</h3> 033 * 034 * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code 035 * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very 036 * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an 037 * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: 038 * 039 * <ol> 040 * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} 041 * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- 042 * <i>not</i> the same string ({@code "1.00"}) we started with 043 * </ol> 044 * 045 * <p>Note that it should still be the case that the round-tripped and original objects are 046 * <i>similar</i>. 047 * 048 * <h3>Nullability</h3> 049 * 050 * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null 051 * references. It would not make sense to consider {@code null} and a non-null reference to be 052 * "different representations of the same information", since one is distinguishable from 053 * <i>missing</i> information and the other is not. The {@link #convert} method handles this null 054 * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are 055 * guaranteed to never be passed {@code null}, and must never return {@code null}. 056 * 057 * 058 * <h3>Common ways to use</h3> 059 * 060 * <p>Getting a converter: 061 * 062 * <ul> 063 * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link 064 * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain 065 * #reverse reverse} views of these. 066 * <li>Convert between specific preset values using {@link 067 * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to 068 * create a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> 069 * the {@code Converter} type using a mocking framework. 070 * <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods. 071 * <li><b>Java 8 users:</b> you may prefer to pass two lambda expressions or method references to 072 * the {@link #from from} factory method. 073 * </ul> 074 * 075 * <p>Using a converter: 076 * 077 * <ul> 078 * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. 079 * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. 080 * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code 081 * converter.reverse().convertAll(bs)}. 082 * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link 083 * java.util.function.Function} is accepted (for example {@link java.util.stream.Stream#map 084 * Stream.map}). 085 * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to 086 * be overridden. 087 * </ul> 088 * 089 * <h3>Example</h3> 090 * 091 * <pre> 092 * return new Converter<Integer, String>() { 093 * protected String doForward(Integer i) { 094 * return Integer.toHexString(i); 095 * } 096 * 097 * protected Integer doBackward(String s) { 098 * return parseUnsignedInt(s, 16); 099 * } 100 * };</pre> 101 * 102 * <p>An alternative using Java 8: 103 * 104 * <pre>{@code 105 * return Converter.from( 106 * Integer::toHexString, 107 * s -> parseUnsignedInt(s, 16)); 108 * }</pre> 109 * 110 * @author Mike Ward 111 * @author Kurt Alfred Kluever 112 * @author Gregory Kick 113 * @since 16.0 114 */ 115@GwtCompatible 116public abstract class Converter<A, B> implements Function<A, B> { 117 private final boolean handleNullAutomatically; 118 119 // We lazily cache the reverse view to avoid allocating on every call to reverse(). 120 @LazyInit private transient @Nullable Converter<B, A> reverse; 121 122 /** Constructor for use by subclasses. */ 123 protected Converter() { 124 this(true); 125 } 126 127 /** Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. */ 128 Converter(boolean handleNullAutomatically) { 129 this.handleNullAutomatically = handleNullAutomatically; 130 } 131 132 // SPI methods (what subclasses must implement) 133 134 /** 135 * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be 136 * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. 137 * 138 * @param a the instance to convert; will never be null 139 * @return the converted instance; <b>must not</b> be null 140 */ 141 @ForOverride 142 protected abstract B doForward(A a); 143 144 /** 145 * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be 146 * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. 147 * 148 * @param b the instance to convert; will never be null 149 * @return the converted instance; <b>must not</b> be null 150 * @throws UnsupportedOperationException if backward conversion is not implemented; this should be 151 * very rare. Note that if backward conversion is not only unimplemented but 152 * unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}), 153 * then this is not logically a {@code Converter} at all, and should just implement {@link 154 * Function}. 155 */ 156 @ForOverride 157 protected abstract A doBackward(B b); 158 159 // API (consumer-side) methods 160 161 /** 162 * Returns a representation of {@code a} as an instance of type {@code B}. 163 * 164 * @return the converted value; is null <i>if and only if</i> {@code a} is null 165 */ 166 @CanIgnoreReturnValue 167 public final @Nullable B convert(@Nullable A a) { 168 return correctedDoForward(a); 169 } 170 171 @Nullable 172 B correctedDoForward(@Nullable A a) { 173 if (handleNullAutomatically) { 174 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 175 return a == null ? null : checkNotNull(doForward(a)); 176 } else { 177 return doForward(a); 178 } 179 } 180 181 @Nullable 182 A correctedDoBackward(@Nullable B b) { 183 if (handleNullAutomatically) { 184 // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? 185 return b == null ? null : checkNotNull(doBackward(b)); 186 } else { 187 return doBackward(b); 188 } 189 } 190 191 /** 192 * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The 193 * conversion is done lazily. 194 * 195 * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After 196 * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding 197 * element. 198 */ 199 @CanIgnoreReturnValue 200 public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) { 201 checkNotNull(fromIterable, "fromIterable"); 202 return new Iterable<B>() { 203 @Override 204 public Iterator<B> iterator() { 205 return new Iterator<B>() { 206 private final Iterator<? extends A> fromIterator = fromIterable.iterator(); 207 208 @Override 209 public boolean hasNext() { 210 return fromIterator.hasNext(); 211 } 212 213 @Override 214 public B next() { 215 return convert(fromIterator.next()); 216 } 217 218 @Override 219 public void remove() { 220 fromIterator.remove(); 221 } 222 }; 223 } 224 }; 225 } 226 227 /** 228 * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a 229 * value roughly equivalent to {@code a}. 230 * 231 * <p>The returned converter is serializable if {@code this} converter is. 232 * 233 * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons. 234 */ 235 @CanIgnoreReturnValue 236 public Converter<B, A> reverse() { 237 Converter<B, A> result = reverse; 238 return (result == null) ? reverse = new ReverseConverter<>(this) : result; 239 } 240 241 private static final class ReverseConverter<A, B> extends Converter<B, A> 242 implements Serializable { 243 final Converter<A, B> original; 244 245 ReverseConverter(Converter<A, B> original) { 246 this.original = original; 247 } 248 249 /* 250 * These gymnastics are a little confusing. Basically this class has neither legacy nor 251 * non-legacy behavior; it just needs to let the behavior of the backing converter shine 252 * through. So, we override the correctedDo* methods, after which the do* methods should never 253 * be reached. 254 */ 255 256 @Override 257 protected A doForward(B b) { 258 throw new AssertionError(); 259 } 260 261 @Override 262 protected B doBackward(A a) { 263 throw new AssertionError(); 264 } 265 266 @Override 267 @Nullable 268 A correctedDoForward(@Nullable B b) { 269 return original.correctedDoBackward(b); 270 } 271 272 @Override 273 @Nullable 274 B correctedDoBackward(@Nullable A a) { 275 return original.correctedDoForward(a); 276 } 277 278 @Override 279 public Converter<A, B> reverse() { 280 return original; 281 } 282 283 @Override 284 public boolean equals(@Nullable Object object) { 285 if (object instanceof ReverseConverter) { 286 ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; 287 return this.original.equals(that.original); 288 } 289 return false; 290 } 291 292 @Override 293 public int hashCode() { 294 return ~original.hashCode(); 295 } 296 297 @Override 298 public String toString() { 299 return original + ".reverse()"; 300 } 301 302 private static final long serialVersionUID = 0L; 303 } 304 305 /** 306 * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result 307 * of this converter. Its {@code reverse} method applies the converters in reverse order. 308 * 309 * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} 310 * are. 311 */ 312 public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { 313 return doAndThen(secondConverter); 314 } 315 316 /** Package-private non-final implementation of andThen() so only we can override it. */ 317 <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) { 318 return new ConverterComposition<>(this, checkNotNull(secondConverter)); 319 } 320 321 private static final class ConverterComposition<A, B, C> extends Converter<A, C> 322 implements Serializable { 323 final Converter<A, B> first; 324 final Converter<B, C> second; 325 326 ConverterComposition(Converter<A, B> first, Converter<B, C> second) { 327 this.first = first; 328 this.second = second; 329 } 330 331 /* 332 * These gymnastics are a little confusing. Basically this class has neither legacy nor 333 * non-legacy behavior; it just needs to let the behaviors of the backing converters shine 334 * through (which might even differ from each other!). So, we override the correctedDo* methods, 335 * after which the do* methods should never be reached. 336 */ 337 338 @Override 339 protected C doForward(A a) { 340 throw new AssertionError(); 341 } 342 343 @Override 344 protected A doBackward(C c) { 345 throw new AssertionError(); 346 } 347 348 @Override 349 @Nullable 350 C correctedDoForward(@Nullable A a) { 351 return second.correctedDoForward(first.correctedDoForward(a)); 352 } 353 354 @Override 355 @Nullable 356 A correctedDoBackward(@Nullable C c) { 357 return first.correctedDoBackward(second.correctedDoBackward(c)); 358 } 359 360 @Override 361 public boolean equals(@Nullable Object object) { 362 if (object instanceof ConverterComposition) { 363 ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; 364 return this.first.equals(that.first) && this.second.equals(that.second); 365 } 366 return false; 367 } 368 369 @Override 370 public int hashCode() { 371 return 31 * first.hashCode() + second.hashCode(); 372 } 373 374 @Override 375 public String toString() { 376 return first + ".andThen(" + second + ")"; 377 } 378 379 private static final long serialVersionUID = 0L; 380 } 381 382 /** 383 * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. 384 */ 385 @Deprecated 386 @Override 387 @CanIgnoreReturnValue 388 public final @Nullable B apply(@Nullable A a) { 389 return convert(a); 390 } 391 392 /** 393 * Indicates whether another object is equal to this converter. 394 * 395 * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. 396 * However, an implementation may also choose to return {@code true} whenever {@code object} is a 397 * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" 398 * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for 399 * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} 400 * result from this method does not imply that the converters are known <i>not</i> to be 401 * interchangeable. 402 */ 403 @Override 404 public boolean equals(@Nullable Object object) { 405 return super.equals(object); 406 } 407 408 // Static converters 409 410 /** 411 * Returns a converter based on separate forward and backward functions. This is useful if the 412 * function instances already exist, or so that you can supply lambda expressions. If those 413 * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and 414 * implement its {@link #doForward} and {@link #doBackward} methods directly. 415 * 416 * <p>These functions will never be passed {@code null} and must not under any circumstances 417 * return {@code null}. If a value cannot be converted, the function should throw an unchecked 418 * exception (typically, but not necessarily, {@link IllegalArgumentException}). 419 * 420 * <p>The returned converter is serializable if both provided functions are. 421 * 422 * @since 17.0 423 */ 424 public static <A, B> Converter<A, B> from( 425 Function<? super A, ? extends B> forwardFunction, 426 Function<? super B, ? extends A> backwardFunction) { 427 return new FunctionBasedConverter<>(forwardFunction, backwardFunction); 428 } 429 430 private static final class FunctionBasedConverter<A, B> extends Converter<A, B> 431 implements Serializable { 432 private final Function<? super A, ? extends B> forwardFunction; 433 private final Function<? super B, ? extends A> backwardFunction; 434 435 private FunctionBasedConverter( 436 Function<? super A, ? extends B> forwardFunction, 437 Function<? super B, ? extends A> backwardFunction) { 438 this.forwardFunction = checkNotNull(forwardFunction); 439 this.backwardFunction = checkNotNull(backwardFunction); 440 } 441 442 @Override 443 protected B doForward(A a) { 444 return forwardFunction.apply(a); 445 } 446 447 @Override 448 protected A doBackward(B b) { 449 return backwardFunction.apply(b); 450 } 451 452 @Override 453 public boolean equals(@Nullable Object object) { 454 if (object instanceof FunctionBasedConverter) { 455 FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; 456 return this.forwardFunction.equals(that.forwardFunction) 457 && this.backwardFunction.equals(that.backwardFunction); 458 } 459 return false; 460 } 461 462 @Override 463 public int hashCode() { 464 return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); 465 } 466 467 @Override 468 public String toString() { 469 return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; 470 } 471 } 472 473 /** Returns a serializable converter that always converts or reverses an object to itself. */ 474 @SuppressWarnings("unchecked") // implementation is "fully variant" 475 public static <T> Converter<T, T> identity() { 476 return (IdentityConverter<T>) IdentityConverter.INSTANCE; 477 } 478 479 /** 480 * A converter that always converts or reverses an object to itself. Note that T is now a 481 * "pass-through type". 482 */ 483 private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { 484 static final IdentityConverter<?> INSTANCE = new IdentityConverter<>(); 485 486 @Override 487 protected T doForward(T t) { 488 return t; 489 } 490 491 @Override 492 protected T doBackward(T t) { 493 return t; 494 } 495 496 @Override 497 public IdentityConverter<T> reverse() { 498 return this; 499 } 500 501 @Override 502 <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) { 503 return checkNotNull(otherConverter, "otherConverter"); 504 } 505 506 /* 507 * We *could* override convertAll() to return its input, but it's a rather pointless 508 * optimization and opened up a weird type-safety problem. 509 */ 510 511 @Override 512 public String toString() { 513 return "Converter.identity()"; 514 } 515 516 private Object readResolve() { 517 return INSTANCE; 518 } 519 520 private static final long serialVersionUID = 0L; 521 } 522}