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