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    /*
210     * If we can quickly determine how many elements there are likely to be, then we can use the
211     * fastest possible implementation, which delegates to the array overload of String.join.
212     *
213     * In theory, we can quickly determine the size of any Collection. However, thanks to
214     * regrettable implementations like our own Sets.filter, Collection.size() is sometimes a
215     * linear-time operation, and it can even have side effects. Thus, we limit the special case to
216     * List, which is _even more likely_ to have size() implemented to be fast and side-effect-free.
217     *
218     * We could consider recognizing specific other collections as safe (like ImmutableCollection,
219     * except ContiguousSet!) or as not worth this optimization (CopyOnWriteArrayList?).
220     */
221    if (parts instanceof List) {
222      int size = ((List<?>) parts).size();
223      if (size == 0) {
224        return "";
225      }
226      CharSequence[] toJoin = new CharSequence[size];
227      int i = 0;
228      for (Object part : parts) {
229        if (i == toJoin.length) {
230          /*
231           * We first initialized toJoin to the size of the input collection. However, that size can
232           * go out of date (for a collection like CopyOnWriteArrayList, which may have been safely
233           * modified concurrently), or it might have been only an estimate to begin with (for a
234           * collection like ConcurrentHashMap, which sums up several counters that may not be in
235           * sync with one another). We accommodate that by resizing as necessary.
236           */
237          toJoin = Arrays.copyOf(toJoin, expandedCapacity(toJoin.length, toJoin.length + 1));
238        }
239        toJoin[i++] = toString(part);
240      }
241      // We might not have seen the expected number of elements, as discussed above.
242      if (i != toJoin.length) {
243        toJoin = Arrays.copyOf(toJoin, i);
244      }
245      // What we care about is Android, under which this method is always desugared:
246      // https://r8.googlesource.com/r8/+/05ba76883518bff06496d6d7df5f06b94a88fb00/src/main/java/com/android/tools/r8/ir/desugar/BackportedMethodRewriter.java#831
247      @SuppressWarnings("Java7ApiChecker")
248      String result = String.join(separator, toJoin);
249      return result;
250    }
251    return join(parts.iterator());
252  }
253
254  /*
255   * TODO: b/381289911 - Make the Iterator overload use StringJoiner (including Android or not)—or
256   * some other optimization, given that StringJoiner can over-allocate:
257   * https://bugs.openjdk.org/browse/JDK-8305774
258   */
259
260  // TODO: b/381289911 - Optimize MapJoiner similarly to Joiner (including Android or not).
261
262  /**
263   * Returns a string containing the string representation of each of {@code parts}, using the
264   * previously configured separator between each.
265   *
266   * @since 11.0
267   */
268  public final String join(Iterator<? extends @Nullable Object> parts) {
269    return appendTo(new StringBuilder(), parts).toString();
270  }
271
272  /**
273   * Returns a string containing the string representation of each of {@code parts}, using the
274   * previously configured separator between each.
275   */
276  public final String join(@Nullable Object[] parts) {
277    @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker
278    List<?> partsList = Arrays.<@Nullable Object>asList(parts);
279    return join(partsList);
280  }
281
282  /**
283   * Returns a string containing the string representation of each argument, using the previously
284   * configured separator between each.
285   */
286  public final String join(
287      @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) {
288    return join(iterable(first, second, rest));
289  }
290
291  /**
292   * Returns a joiner with the same behavior as this one, except automatically substituting {@code
293   * nullText} for any provided null elements.
294   */
295  public Joiner useForNull(String nullText) {
296    checkNotNull(nullText);
297    return new Joiner(this) {
298      @Override
299      CharSequence toString(@CheckForNull Object part) {
300        return (part == null) ? nullText : Joiner.this.toString(part);
301      }
302
303      @Override
304      public Joiner useForNull(String nullText) {
305        throw new UnsupportedOperationException("already specified useForNull");
306      }
307
308      @Override
309      public Joiner skipNulls() {
310        throw new UnsupportedOperationException("already specified useForNull");
311      }
312    };
313  }
314
315  /**
316   * Returns a joiner with the same behavior as this joiner, except automatically skipping over any
317   * provided null elements.
318   */
319  public Joiner skipNulls() {
320    return new Joiner(this) {
321      @Override
322      @SuppressWarnings("JoinIterableIterator") // suggests infinite recursion
323      public String join(Iterable<? extends @Nullable Object> parts) {
324        return join(parts.iterator());
325      }
326
327      @Override
328      public <A extends Appendable> A appendTo(
329          A appendable, Iterator<? extends @Nullable Object> parts) throws IOException {
330        checkNotNull(appendable, "appendable");
331        checkNotNull(parts, "parts");
332        while (parts.hasNext()) {
333          Object part = parts.next();
334          if (part != null) {
335            appendable.append(Joiner.this.toString(part));
336            break;
337          }
338        }
339        while (parts.hasNext()) {
340          Object part = parts.next();
341          if (part != null) {
342            appendable.append(separator);
343            appendable.append(Joiner.this.toString(part));
344          }
345        }
346        return appendable;
347      }
348
349      @Override
350      public Joiner useForNull(String nullText) {
351        throw new UnsupportedOperationException("already specified skipNulls");
352      }
353
354      @Override
355      public MapJoiner withKeyValueSeparator(String kvs) {
356        throw new UnsupportedOperationException("can't use .skipNulls() with maps");
357      }
358    };
359  }
360
361  /**
362   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
363   * this {@code Joiner} otherwise.
364   *
365   * @since 20.0
366   */
367  public MapJoiner withKeyValueSeparator(char keyValueSeparator) {
368    return withKeyValueSeparator(String.valueOf(keyValueSeparator));
369  }
370
371  /**
372   * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
373   * this {@code Joiner} otherwise.
374   */
375  public MapJoiner withKeyValueSeparator(String keyValueSeparator) {
376    return new MapJoiner(this, keyValueSeparator);
377  }
378
379  /**
380   * An object that joins map entries in the same manner as {@code Joiner} joins iterables and
381   * arrays. Like {@code Joiner}, it is thread-safe and immutable.
382   *
383   * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code
384   * Multimap} entries in two distinct modes:
385   *
386   * <ul>
387   *   <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a
388   *       {@code MapJoiner} method that accepts entries as input, and receive output of the form
389   *       {@code key1=A&key1=B&key2=C}.
390   *   <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code
391   *       MapJoiner} method that accepts a map as input, and receive output of the form {@code
392   *       key1=[A, B]&key2=C}.
393   * </ul>
394   *
395   * @since 2.0
396   */
397  public static final class MapJoiner {
398    private final Joiner joiner;
399    private final String keyValueSeparator;
400
401    private MapJoiner(Joiner joiner, String keyValueSeparator) {
402      this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull
403      this.keyValueSeparator = checkNotNull(keyValueSeparator);
404    }
405
406    /**
407     * Appends the string representation of each entry of {@code map}, using the previously
408     * configured separator and key-value separator, to {@code appendable}.
409     */
410    @CanIgnoreReturnValue
411    public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {
412      return appendTo(appendable, map.entrySet());
413    }
414
415    /**
416     * Appends the string representation of each entry of {@code map}, using the previously
417     * configured separator and key-value separator, to {@code builder}. Identical to {@link
418     * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.
419     */
420    @CanIgnoreReturnValue
421    public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {
422      return appendTo(builder, map.entrySet());
423    }
424
425    /**
426     * Appends the string representation of each entry in {@code entries}, using the previously
427     * configured separator and key-value separator, to {@code appendable}.
428     *
429     * @since 10.0
430     */
431    @CanIgnoreReturnValue
432    public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
433        throws IOException {
434      return appendTo(appendable, entries.iterator());
435    }
436
437    /**
438     * Appends the string representation of each entry in {@code entries}, using the previously
439     * configured separator and key-value separator, to {@code appendable}.
440     *
441     * @since 11.0
442     */
443    @CanIgnoreReturnValue
444    public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
445        throws IOException {
446      checkNotNull(appendable);
447      if (parts.hasNext()) {
448        Entry<?, ?> entry = parts.next();
449        appendable.append(joiner.toString(entry.getKey()));
450        appendable.append(keyValueSeparator);
451        appendable.append(joiner.toString(entry.getValue()));
452        while (parts.hasNext()) {
453          appendable.append(joiner.separator);
454          Entry<?, ?> e = parts.next();
455          appendable.append(joiner.toString(e.getKey()));
456          appendable.append(keyValueSeparator);
457          appendable.append(joiner.toString(e.getValue()));
458        }
459      }
460      return appendable;
461    }
462
463    /**
464     * Appends the string representation of each entry in {@code entries}, using the previously
465     * configured separator and key-value separator, to {@code builder}. Identical to {@link
466     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
467     *
468     * @since 10.0
469     */
470    @CanIgnoreReturnValue
471    public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
472      return appendTo(builder, entries.iterator());
473    }
474
475    /**
476     * Appends the string representation of each entry in {@code entries}, using the previously
477     * configured separator and key-value separator, to {@code builder}. Identical to {@link
478     * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
479     *
480     * @since 11.0
481     */
482    @CanIgnoreReturnValue
483    public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
484      try {
485        appendTo((Appendable) builder, entries);
486      } catch (IOException impossible) {
487        throw new AssertionError(impossible);
488      }
489      return builder;
490    }
491
492    /**
493     * Returns a string containing the string representation of each entry of {@code map}, using the
494     * previously configured separator and key-value separator.
495     */
496    public String join(Map<?, ?> map) {
497      return join(map.entrySet());
498    }
499
500    /**
501     * Returns a string containing the string representation of each entry in {@code entries}, using
502     * the previously configured separator and key-value separator.
503     *
504     * @since 10.0
505     */
506    public String join(Iterable<? extends Entry<?, ?>> entries) {
507      return join(entries.iterator());
508    }
509
510    /**
511     * Returns a string containing the string representation of each entry in {@code entries}, using
512     * the previously configured separator and key-value separator.
513     *
514     * @since 11.0
515     */
516    public String join(Iterator<? extends Entry<?, ?>> entries) {
517      return appendTo(new StringBuilder(), entries).toString();
518    }
519
520    /**
521     * Returns a map joiner with the same behavior as this one, except automatically substituting
522     * {@code nullText} for any provided null keys or values.
523     */
524    public MapJoiner useForNull(String nullText) {
525      return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);
526    }
527  }
528
529  // TODO(cpovirk): Rename to "toCharSequence."
530  CharSequence toString(@CheckForNull Object part) {
531    /*
532     * requireNonNull is not safe: Joiner.on(...).join(somethingThatContainsNull) will indeed throw.
533     * However, Joiner.on(...).useForNull(...).join(somethingThatContainsNull) *is* safe -- because
534     * it returns a subclass of Joiner that overrides this method to tolerate null inputs.
535     *
536     * Unfortunately, we don't distinguish between these two cases in our public API: Joiner.on(...)
537     * and Joiner.on(...).useForNull(...) both declare the same return type: plain Joiner. To ensure
538     * that users *can* pass null arguments to Joiner, we annotate it as if it always tolerates null
539     * inputs, rather than as if it never tolerates them.
540     *
541     * We rely on checkers to implement special cases to catch dangerous calls to join(), etc. based
542     * on what they know about the particular Joiner instances the calls are performed on.
543     *
544     * (In addition to useForNull, we also offer skipNulls. It, too, tolerates null inputs, but its
545     * tolerance is implemented differently: Its implementation avoids calling this toString(Object)
546     * method in the first place.)
547     */
548    requireNonNull(part);
549    return (part instanceof CharSequence) ? (CharSequence) part : part.toString();
550  }
551
552  private static Iterable<@Nullable Object> iterable(
553      @CheckForNull Object first, @CheckForNull Object second, @Nullable Object[] rest) {
554    checkNotNull(rest);
555    return new AbstractList<@Nullable Object>() {
556      @Override
557      public int size() {
558        return rest.length + 2;
559      }
560
561      @Override
562      @CheckForNull
563      public Object get(int index) {
564        switch (index) {
565          case 0:
566            return first;
567          case 1:
568            return second;
569          default:
570            return rest[index - 2];
571        }
572      }
573    };
574  }
575
576  // cloned from ImmutableCollection
577  private static int expandedCapacity(int oldCapacity, int minCapacity) {
578    if (minCapacity < 0) {
579      throw new IllegalArgumentException("cannot store more than Integer.MAX_VALUE elements");
580    } else if (minCapacity <= oldCapacity) {
581      return oldCapacity;
582    }
583    // careful of overflow!
584    int newCapacity = oldCapacity + (oldCapacity >> 1) + 1;
585    if (newCapacity < minCapacity) {
586      newCapacity = Integer.highestOneBit(minCapacity - 1) << 1;
587    }
588    if (newCapacity < 0) {
589      newCapacity = Integer.MAX_VALUE;
590      // guaranteed to be >= newCapacity
591    }
592    return newCapacity;
593  }
594}