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