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