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;
018import static java.util.Objects.requireNonNull;
019
020import com.google.common.annotations.GwtCompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import java.io.IOException;
023import java.util.AbstractList;
024import java.util.Arrays;
025import java.util.Iterator;
026import java.util.List;
027import java.util.Map;
028import java.util.Map.Entry;
029import javax.annotation.CheckForNull;
030import org.checkerframework.checker.nullness.qual.Nullable;
031
032/**
033 * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a
034 * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns
035 * them as a {@link String}. Example:
036 *
037 * <pre>{@code
038 * Joiner joiner = Joiner.on("; ").skipNulls();
039 *  . . .
040 * return joiner.join("Harry", null, "Ron", "Hermione");
041 * }</pre>
042 *
043 * <p>This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are
044 * converted to strings using {@link Object#toString()} before being appended.
045 *
046 * <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining
047 * methods will throw {@link NullPointerException} if any given element is null.
048 *
049 * <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code
050 * useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner
051 * instance returned by the method. This makes joiners thread-safe, and safe to store as {@code
052 * static final} constants.
053 *
054 * <pre>{@code
055 * // Bad! Do not do this!
056 * Joiner joiner = Joiner.on(',');
057 * joiner.skipNulls(); // does nothing!
058 * return joiner.join("wrong", null, "wrong");
059 * }</pre>
060 *
061 * <p>See the Guava User Guide article on <a
062 * href="https://github.com/google/guava/wiki/StringsExplained#joiner">{@code Joiner}</a>.
063 *
064 * @author Kevin Bourrillion
065 * @since 2.0
066 */
067@GwtCompatible
068@ElementTypesAreNonnullByDefault
069public class Joiner {
070  /** Returns a joiner which automatically places {@code separator} between consecutive elements. */
071  public static Joiner on(String separator) {
072    return new Joiner(separator);
073  }
074
075  /** Returns a joiner which automatically places {@code separator} between consecutive elements. */
076  public static Joiner on(char separator) {
077    return new Joiner(String.valueOf(separator));
078  }
079
080  private final String separator;
081
082  private Joiner(String separator) {
083    this.separator = checkNotNull(separator);
084  }
085
086  private Joiner(Joiner prototype) {
087    this.separator = prototype.separator;
088  }
089
090  /*
091   * In this file, we use <? extends @Nullable Object> instead of <?> to work around a Kotlin bug
092   * (see b/189937072 until we file a bug against Kotlin itself). (The two should be equivalent, so
093   * we normally prefer the shorter one.)
094   */
095
096  /**
097   * Appends the string representation of each of {@code parts}, using the previously configured
098   * separator between each, to {@code appendable}.
099   */
100  @CanIgnoreReturnValue
101  public <A extends Appendable> A appendTo(A appendable, Iterable<? extends @Nullable Object> parts)
102      throws IOException {
103    return appendTo(appendable, parts.iterator());
104  }
105
106  /**
107   * Appends the string representation of each of {@code parts}, using the previously configured
108   * separator between each, to {@code appendable}.
109   *
110   * @since 11.0
111   */
112  @CanIgnoreReturnValue
113  public <A extends Appendable> A appendTo(A appendable, Iterator<? extends @Nullable Object> parts)
114      throws IOException {
115    checkNotNull(appendable);
116    if (parts.hasNext()) {
117      appendable.append(toString(parts.next()));
118      while (parts.hasNext()) {
119        appendable.append(separator);
120        appendable.append(toString(parts.next()));
121      }
122    }
123    return appendable;
124  }
125
126  /**
127   * Appends the string representation of each of {@code parts}, using the previously configured
128   * separator between each, to {@code appendable}.
129   */
130  @CanIgnoreReturnValue
131  public final <A extends Appendable> A appendTo(A appendable, @Nullable Object[] parts)
132      throws IOException {
133    @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker
134    List<?> partsList = Arrays.<@Nullable Object>asList(parts);
135    return appendTo(appendable, partsList);
136  }
137
138  /** Appends to {@code appendable} the string representation of each of the remaining arguments. */
139  @CanIgnoreReturnValue
140  public final <A extends Appendable> A appendTo(
141      A appendable,
142      @CheckForNull Object first,
143      @CheckForNull Object second,
144      @Nullable Object... rest)
145      throws IOException {
146    return appendTo(appendable, iterable(first, second, rest));
147  }
148
149  /**
150   * Appends the string representation of each of {@code parts}, using the previously configured
151   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
152   * Iterable)}, except that it does not throw {@link IOException}.
153   */
154  @CanIgnoreReturnValue
155  public final StringBuilder appendTo(
156      StringBuilder builder, Iterable<? extends @Nullable Object> parts) {
157    return appendTo(builder, parts.iterator());
158  }
159
160  /**
161   * Appends the string representation of each of {@code parts}, using the previously configured
162   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
163   * Iterable)}, except that it does not throw {@link IOException}.
164   *
165   * @since 11.0
166   */
167  @CanIgnoreReturnValue
168  public final StringBuilder appendTo(
169      StringBuilder builder, Iterator<? extends @Nullable Object> parts) {
170    try {
171      appendTo((Appendable) builder, parts);
172    } catch (IOException impossible) {
173      throw new AssertionError(impossible);
174    }
175    return builder;
176  }
177
178  /**
179   * Appends the string representation of each of {@code parts}, using the previously configured
180   * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
181   * Iterable)}, except that it does not throw {@link IOException}.
182   */
183  @CanIgnoreReturnValue
184  public final StringBuilder appendTo(StringBuilder builder, @Nullable Object[] parts) {
185    @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker
186    List<?> partsList = Arrays.<@Nullable Object>asList(parts);
187    return appendTo(builder, partsList);
188  }
189
190  /**
191   * Appends to {@code builder} the string representation of each of the remaining arguments.
192   * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not
193   * throw {@link IOException}.
194   */
195  @CanIgnoreReturnValue
196  public final StringBuilder appendTo(
197      StringBuilder builder,
198      @CheckForNull Object first,
199      @CheckForNull Object second,
200      @Nullable Object... rest) {
201    return appendTo(builder, iterable(first, second, rest));
202  }
203
204  /**
205   * Returns a string containing the string representation of each of {@code parts}, using the
206   * previously configured separator between each.
207   */
208  public String join(Iterable<? extends @Nullable Object> parts) {
209    // We don't use the same optimization here as in the JRE flavor.
210    // TODO: b/381289911 - Evaluate the performance impact of doing so.
211    return join(parts.iterator());
212  }
213
214  /*
215   * TODO: b/381289911 - Make the Iterator overload use StringJoiner (including Android or not)—or
216   * some other optimization, given that StringJoiner can over-allocate:
217   * https://bugs.openjdk.org/browse/JDK-8305774
218   */
219
220  // TODO: b/381289911 - Optimize MapJoiner similarly to Joiner (including Android or not).
221
222  /**
223   * Returns a string containing the string representation of each of {@code parts}, using the
224   * previously configured separator between each.
225   *
226   * @since 11.0
227   */
228  public final String join(Iterator<? extends @Nullable Object> parts) {
229    return appendTo(new StringBuilder(), parts).toString();
230  }
231
232  /**
233   * Returns a string containing the string representation of each of {@code parts}, using the
234   * previously configured separator between each.
235   */
236  public final String join(@Nullable Object[] parts) {
237    @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker
238    List<?> partsList = Arrays.<@Nullable Object>asList(parts);
239    return join(partsList);
240  }
241
242  /**
243   * Returns a string containing the string representation of each argument, using the previously
244   * configured separator between each.
245   */
246  public final String join(
247      @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) {
248    return join(iterable(first, second, rest));
249  }
250
251  /**
252   * Returns a joiner with the same behavior as this one, except automatically substituting {@code
253   * nullText} for any provided null elements.
254   */
255  public Joiner useForNull(String nullText) {
256    checkNotNull(nullText);
257    return new Joiner(this) {
258      @Override
259      CharSequence toString(@CheckForNull Object part) {
260        return (part == null) ? nullText : Joiner.this.toString(part);
261      }
262
263      @Override
264      public Joiner useForNull(String nullText) {
265        throw new UnsupportedOperationException("already specified useForNull");
266      }
267
268      @Override
269      public Joiner skipNulls() {
270        throw new UnsupportedOperationException("already specified useForNull");
271      }
272    };
273  }
274
275  /**
276   * Returns a joiner with the same behavior as this joiner, except automatically skipping over any
277   * provided null elements.
278   */
279  public Joiner skipNulls() {
280    return new Joiner(this) {
281      @Override
282      @SuppressWarnings("JoinIterableIterator") // suggests infinite recursion
283      public String join(Iterable<? extends @Nullable Object> parts) {
284        return join(parts.iterator());
285      }
286
287      @Override
288      public <A extends Appendable> A appendTo(
289          A appendable, Iterator<? extends @Nullable Object> parts) throws IOException {
290        checkNotNull(appendable, "appendable");
291        checkNotNull(parts, "parts");
292        while (parts.hasNext()) {
293          Object part = parts.next();
294          if (part != null) {
295            appendable.append(Joiner.this.toString(part));
296            break;
297          }
298        }
299        while (parts.hasNext()) {
300          Object part = parts.next();
301          if (part != null) {
302            appendable.append(separator);
303            appendable.append(Joiner.this.toString(part));
304          }
305        }
306        return appendable;
307      }
308
309      @Override
310      public Joiner useForNull(String nullText) {
311        throw new UnsupportedOperationException("already specified skipNulls");
312      }
313
314      @Override
315      public MapJoiner withKeyValueSeparator(String kvs) {
316        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
317      }
318    };
319  }
320
321  /**
322   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
323   * this {@code Joiner} otherwise.
324   *
325   * @since 20.0
326   */
327  public MapJoiner withKeyValueSeparator(char keyValueSeparator) {
328    return withKeyValueSeparator(String.valueOf(keyValueSeparator));
329  }
330
331  /**
332   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
333   * this {@code Joiner} otherwise.
334   */
335  public MapJoiner withKeyValueSeparator(String keyValueSeparator) {
336    return new MapJoiner(this, keyValueSeparator);
337  }
338
339  /**
340   * An object that joins map entries in the same manner as {@code Joiner} joins iterables and
341   * arrays. Like {@code Joiner}, it is thread-safe and immutable.
342   *
343   * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code
344   * Multimap} entries in two distinct modes:
345   *
346   * <ul>
347   *   <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a
348   *       {@code MapJoiner} method that accepts entries as input, and receive output of the form
349   *       {@code key1=A&key1=B&key2=C}.
350   *   <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code
351   *       MapJoiner} method that accepts a map as input, and receive output of the form {@code
352   *       key1=[A, B]&key2=C}.
353   * </ul>
354   *
355   * @since 2.0
356   */
357  public static final class MapJoiner {
358    private final Joiner joiner;
359    private final String keyValueSeparator;
360
361    private MapJoiner(Joiner joiner, String keyValueSeparator) {
362      this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull
363      this.keyValueSeparator = checkNotNull(keyValueSeparator);
364    }
365
366    /**
367     * Appends the string representation of each entry of {@code map}, using the previously
368     * configured separator and key-value separator, to {@code appendable}.
369     */
370    @CanIgnoreReturnValue
371    public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {
372      return appendTo(appendable, map.entrySet());
373    }
374
375    /**
376     * Appends the string representation of each entry of {@code map}, using the previously
377     * configured separator and key-value separator, to {@code builder}. Identical to {@link
378     * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.
379     */
380    @CanIgnoreReturnValue
381    public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {
382      return appendTo(builder, map.entrySet());
383    }
384
385    /**
386     * Appends the string representation of each entry in {@code entries}, using the previously
387     * configured separator and key-value separator, to {@code appendable}.
388     *
389     * @since 10.0
390     */
391    @CanIgnoreReturnValue
392    public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
393        throws IOException {
394      return appendTo(appendable, entries.iterator());
395    }
396
397    /**
398     * Appends the string representation of each entry in {@code entries}, using the previously
399     * configured separator and key-value separator, to {@code appendable}.
400     *
401     * @since 11.0
402     */
403    @CanIgnoreReturnValue
404    public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
405        throws IOException {
406      checkNotNull(appendable);
407      if (parts.hasNext()) {
408        Entry<?, ?> entry = parts.next();
409        appendable.append(joiner.toString(entry.getKey()));
410        appendable.append(keyValueSeparator);
411        appendable.append(joiner.toString(entry.getValue()));
412        while (parts.hasNext()) {
413          appendable.append(joiner.separator);
414          Entry<?, ?> e = parts.next();
415          appendable.append(joiner.toString(e.getKey()));
416          appendable.append(keyValueSeparator);
417          appendable.append(joiner.toString(e.getValue()));
418        }
419      }
420      return appendable;
421    }
422
423    /**
424     * Appends the string representation of each entry in {@code entries}, using the previously
425     * configured separator and key-value separator, to {@code builder}. Identical to {@link
426     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
427     *
428     * @since 10.0
429     */
430    @CanIgnoreReturnValue
431    public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
432      return appendTo(builder, entries.iterator());
433    }
434
435    /**
436     * Appends the string representation of each entry in {@code entries}, using the previously
437     * configured separator and key-value separator, to {@code builder}. Identical to {@link
438     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
439     *
440     * @since 11.0
441     */
442    @CanIgnoreReturnValue
443    public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
444      try {
445        appendTo((Appendable) builder, entries);
446      } catch (IOException impossible) {
447        throw new AssertionError(impossible);
448      }
449      return builder;
450    }
451
452    /**
453     * Returns a string containing the string representation of each entry of {@code map}, using the
454     * previously configured separator and key-value separator.
455     */
456    public String join(Map<?, ?> map) {
457      return join(map.entrySet());
458    }
459
460    /**
461     * Returns a string containing the string representation of each entry in {@code entries}, using
462     * the previously configured separator and key-value separator.
463     *
464     * @since 10.0
465     */
466    public String join(Iterable<? extends Entry<?, ?>> entries) {
467      return join(entries.iterator());
468    }
469
470    /**
471     * Returns a string containing the string representation of each entry in {@code entries}, using
472     * the previously configured separator and key-value separator.
473     *
474     * @since 11.0
475     */
476    public String join(Iterator<? extends Entry<?, ?>> entries) {
477      return appendTo(new StringBuilder(), entries).toString();
478    }
479
480    /**
481     * Returns a map joiner with the same behavior as this one, except automatically substituting
482     * {@code nullText} for any provided null keys or values.
483     */
484    public MapJoiner useForNull(String nullText) {
485      return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);
486    }
487  }
488
489  // TODO(cpovirk): Rename to "toCharSequence."
490  CharSequence toString(@CheckForNull Object part) {
491    /*
492     * requireNonNull is not safe: Joiner.on(...).join(somethingThatContainsNull) will indeed throw.
493     * However, Joiner.on(...).useForNull(...).join(somethingThatContainsNull) *is* safe -- because
494     * it returns a subclass of Joiner that overrides this method to tolerate null inputs.
495     *
496     * Unfortunately, we don't distinguish between these two cases in our public API: Joiner.on(...)
497     * and Joiner.on(...).useForNull(...) both declare the same return type: plain Joiner. To ensure
498     * that users *can* pass null arguments to Joiner, we annotate it as if it always tolerates null
499     * inputs, rather than as if it never tolerates them.
500     *
501     * We rely on checkers to implement special cases to catch dangerous calls to join(), etc. based
502     * on what they know about the particular Joiner instances the calls are performed on.
503     *
504     * (In addition to useForNull, we also offer skipNulls. It, too, tolerates null inputs, but its
505     * tolerance is implemented differently: Its implementation avoids calling this toString(Object)
506     * method in the first place.)
507     */
508    requireNonNull(part);
509    return (part instanceof CharSequence) ? (CharSequence) part : part.toString();
510  }
511
512  private static Iterable<@Nullable Object> iterable(
513      @CheckForNull Object first, @CheckForNull Object second, @Nullable Object[] rest) {
514    checkNotNull(rest);
515    return new AbstractList<@Nullable Object>() {
516      @Override
517      public int size() {
518        return rest.length + 2;
519      }
520
521      @Override
522      @CheckForNull
523      public Object get(int index) {
524        switch (index) {
525          case 0:
526            return first;
527          case 1:
528            return second;
529          default:
530            return rest[index - 2];
531        }
532      }
533    };
534  }
535
536  // cloned from ImmutableCollection
537  private static int expandedCapacity(int oldCapacity, int minCapacity) {
538    if (minCapacity < 0) {
539      throw new IllegalArgumentException("cannot store more than Integer.MAX_VALUE elements");
540    } else if (minCapacity <= oldCapacity) {
541      return oldCapacity;
542    }
543    // careful of overflow!
544    int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
545    if (newCapacity < minCapacity) {
546      newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
547    }
548    if (newCapacity < 0) {
549      newCapacity = Integer.MAX_VALUE;
550      // guaranteed to be >= newCapacity
551    }
552    return newCapacity;
553  }
554}