001/*
002 * Copyright (C) 2010 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.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static java.lang.Math.min;
020import static java.util.logging.Level.WARNING;
021
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.VisibleForTesting;
024import com.google.errorprone.annotations.InlineMe;
025import com.google.errorprone.annotations.InlineMeValidationDisabled;
026import java.util.logging.Logger;
027import org.jspecify.annotations.Nullable;
028
029/**
030 * Static utility methods pertaining to {@code String} or {@code CharSequence} instances.
031 *
032 * @author Kevin Bourrillion
033 * @since 3.0
034 */
035@GwtCompatible
036public final class Strings {
037  private Strings() {}
038
039  /**
040   * Returns the given string if it is non-null; the empty string otherwise.
041   *
042   * @param string the string to test and possibly return
043   * @return {@code string} itself if it is non-null; {@code ""} if it is null
044   */
045  public static String nullToEmpty(@Nullable String string) {
046    return Platform.nullToEmpty(string);
047  }
048
049  /**
050   * Returns the given string if it is nonempty; {@code null} otherwise.
051   *
052   * @param string the string to test and possibly return
053   * @return {@code string} itself if it is nonempty; {@code null} if it is empty or null
054   */
055  public static @Nullable String emptyToNull(@Nullable String string) {
056    return Platform.emptyToNull(string);
057  }
058
059  /**
060   * Returns {@code true} if the given string is null or is the empty string.
061   *
062   * <p>Consider normalizing your string references with {@link #nullToEmpty}. If you do, you can
063   * use {@link String#isEmpty()} instead of this method, and you won't need special null-safe forms
064   * of methods like {@link String#toUpperCase} either. Or, if you'd like to normalize "in the other
065   * direction," converting empty strings to {@code null}, you can use {@link #emptyToNull}.
066   *
067   * @param string a string reference to check
068   * @return {@code true} if the string is null or is the empty string
069   */
070  public static boolean isNullOrEmpty(@Nullable String string) {
071    return Platform.stringIsNullOrEmpty(string);
072  }
073
074  /**
075   * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended
076   * with as many copies of {@code padChar} as are necessary to reach that length. For example,
077   *
078   * <ul>
079   *   <li>{@code padStart("7", 3, '0')} returns {@code "007"}
080   *   <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
081   * </ul>
082   *
083   * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
084   *
085   * @param string the string which should appear at the end of the result
086   * @param minLength the minimum length the resulting string must have. Can be zero or negative, in
087   *     which case the input string is always returned.
088   * @param padChar the character to insert at the beginning of the result until the minimum length
089   *     is reached
090   * @return the padded string
091   */
092  public static String padStart(String string, int minLength, char padChar) {
093    checkNotNull(string); // eager for GWT.
094    if (string.length() >= minLength) {
095      return string;
096    }
097    StringBuilder sb = new StringBuilder(minLength);
098    for (int i = string.length(); i < minLength; i++) {
099      sb.append(padChar);
100    }
101    sb.append(string);
102    return sb.toString();
103  }
104
105  /**
106   * Returns a string, of length at least {@code minLength}, consisting of {@code string} appended
107   * with as many copies of {@code padChar} as are necessary to reach that length. For example,
108   *
109   * <ul>
110   *   <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
111   *   <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
112   * </ul>
113   *
114   * <p>See {@link java.util.Formatter} for a richer set of formatting capabilities.
115   *
116   * @param string the string which should appear at the beginning of the result
117   * @param minLength the minimum length the resulting string must have. Can be zero or negative, in
118   *     which case the input string is always returned.
119   * @param padChar the character to append to the end of the result until the minimum length is
120   *     reached
121   * @return the padded string
122   */
123  public static String padEnd(String string, int minLength, char padChar) {
124    checkNotNull(string); // eager for GWT.
125    if (string.length() >= minLength) {
126      return string;
127    }
128    StringBuilder sb = new StringBuilder(minLength);
129    sb.append(string);
130    for (int i = string.length(); i < minLength; i++) {
131      sb.append(padChar);
132    }
133    return sb.toString();
134  }
135
136  /**
137   * Returns a string consisting of a specific number of concatenated copies of an input string. For
138   * example, {@code repeat("hey", 3)} returns the string {@code "heyheyhey"}.
139   *
140   * <p><b>Java 11+ users:</b> use {@code string.repeat(count)} instead.
141   *
142   * @param string any non-null string
143   * @param count the number of times to repeat it; a nonnegative integer
144   * @return a string containing {@code string} repeated {@code count} times (the empty string if
145   *     {@code count} is zero)
146   * @throws IllegalArgumentException if {@code count} is negative
147   */
148  @InlineMe(replacement = "string.repeat(count)")
149  @InlineMeValidationDisabled("Java 11+ API only")
150  public static String repeat(String string, int count) {
151    checkNotNull(string); // eager for GWT.
152
153    if (count <= 1) {
154      checkArgument(count >= 0, "invalid count: %s", count);
155      return (count == 0) ? "" : string;
156    }
157
158    // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
159    final int len = string.length();
160    final long longSize = (long) len * (long) count;
161    final int size = (int) longSize;
162    if (size != longSize) {
163      throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);
164    }
165
166    final char[] array = new char[size];
167    string.getChars(0, len, array, 0);
168    int n;
169    for (n = len; n < size - n; n <<= 1) {
170      System.arraycopy(array, 0, array, n, n);
171    }
172    System.arraycopy(array, 0, array, n, size - n);
173    return new String(array);
174  }
175
176  /**
177   * Returns the longest string {@code prefix} such that {@code a.toString().startsWith(prefix) &&
178   * b.toString().startsWith(prefix)}, taking care not to split surrogate pairs. If {@code a} and
179   * {@code b} have no common prefix, returns the empty string.
180   *
181   * @since 11.0
182   */
183  public static String commonPrefix(CharSequence a, CharSequence b) {
184    checkNotNull(a);
185    checkNotNull(b);
186
187    int maxPrefixLength = min(a.length(), b.length());
188    int p = 0;
189    while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
190      p++;
191    }
192    if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
193      p--;
194    }
195    return a.subSequence(0, p).toString();
196  }
197
198  /**
199   * Returns the longest string {@code suffix} such that {@code a.toString().endsWith(suffix) &&
200   * b.toString().endsWith(suffix)}, taking care not to split surrogate pairs. If {@code a} and
201   * {@code b} have no common suffix, returns the empty string.
202   *
203   * @since 11.0
204   */
205  public static String commonSuffix(CharSequence a, CharSequence b) {
206    checkNotNull(a);
207    checkNotNull(b);
208
209    int maxSuffixLength = min(a.length(), b.length());
210    int s = 0;
211    while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
212      s++;
213    }
214    if (validSurrogatePairAt(a, a.length() - s - 1)
215        || validSurrogatePairAt(b, b.length() - s - 1)) {
216      s--;
217    }
218    return a.subSequence(a.length() - s, a.length()).toString();
219  }
220
221  /**
222   * True when a valid surrogate pair starts at the given {@code index} in the given {@code string}.
223   * Out-of-range indexes return false.
224   */
225  @VisibleForTesting
226  static boolean validSurrogatePairAt(CharSequence string, int index) {
227    return index >= 0
228        && index <= (string.length() - 2)
229        && Character.isHighSurrogate(string.charAt(index))
230        && Character.isLowSurrogate(string.charAt(index + 1));
231  }
232
233  /**
234   * Returns the given {@code template} string with each occurrence of {@code "%s"} replaced with
235   * the corresponding argument value from {@code args}; or, if the placeholder and argument counts
236   * do not match, returns a best-effort form of that string. Will not throw an exception under
237   * normal conditions.
238   *
239   * <p><b>Note:</b> For most string-formatting needs, use {@link String#format String.format},
240   * {@link java.io.PrintWriter#format PrintWriter.format}, and related methods. These support the
241   * full range of <a
242   * href="https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html#syntax">format
243   * specifiers</a>, and alert you to usage errors by throwing {@link
244   * java.util.IllegalFormatException}.
245   *
246   * <p>In certain cases, such as outputting debugging information or constructing a message to be
247   * used for another unchecked exception, an exception during string formatting would serve little
248   * purpose except to supplant the real information you were trying to provide. These are the cases
249   * this method is made for; it instead generates a best-effort string with all supplied argument
250   * values present. This method is also useful in environments such as GWT where {@code
251   * String.format} is not available. As an example, method implementations of the {@link
252   * Preconditions} class use this formatter, for both of the reasons just discussed.
253   *
254   * <p><b>Warning:</b> Only the exact two-character placeholder sequence {@code "%s"} is
255   * recognized.
256   *
257   * @param template a string containing zero or more {@code "%s"} placeholder sequences. {@code
258   *     null} is treated as the four-character string {@code "null"}.
259   * @param args the arguments to be substituted into the message template. The first argument
260   *     specified is substituted for the first occurrence of {@code "%s"} in the template, and so
261   *     forth. A {@code null} argument is converted to the four-character string {@code "null"};
262   *     non-null values are converted to strings using {@link Object#toString()}.
263   * @since 25.1
264   */
265  // TODO(diamondm) consider using Arrays.toString() for array parameters
266  public static String lenientFormat(
267      @Nullable String template, @Nullable Object @Nullable ... args) {
268    template = String.valueOf(template); // null -> "null"
269
270    if (args == null) {
271      args = new Object[] {"(Object[])null"};
272    } else {
273      for (int i = 0; i < args.length; i++) {
274        args[i] = lenientToString(args[i]);
275      }
276    }
277
278    // start substituting the arguments into the '%s' placeholders
279    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
280    int templateStart = 0;
281    int i = 0;
282    while (i < args.length) {
283      int placeholderStart = template.indexOf("%s", templateStart);
284      if (placeholderStart == -1) {
285        break;
286      }
287      builder.append(template, templateStart, placeholderStart);
288      builder.append(args[i++]);
289      templateStart = placeholderStart + 2;
290    }
291    builder.append(template, templateStart, template.length());
292
293    // if we run out of placeholders, append the extra args in square braces
294    if (i < args.length) {
295      builder.append(" [");
296      builder.append(args[i++]);
297      while (i < args.length) {
298        builder.append(", ");
299        builder.append(args[i++]);
300      }
301      builder.append(']');
302    }
303
304    return builder.toString();
305  }
306
307  private static String lenientToString(@Nullable Object o) {
308    if (o == null) {
309      return "null";
310    }
311    try {
312      return o.toString();
313    } catch (Exception e) {
314      // Default toString() behavior - see Object.toString()
315      String objectToString =
316          o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
317      // Logger is created inline with fixed name to avoid forcing Proguard to create another class.
318      Logger.getLogger("com.google.common.base.Strings")
319          .log(WARNING, "Exception during lenientFormat for " + objectToString, e);
320      return "<" + objectToString + " threw " + e.getClass().getName() + ">";
321    }
322  }
323}