001/*
002 * Copyright (C) 2007 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 com.google.common.annotations.GwtCompatible;
018import com.google.errorprone.annotations.CanIgnoreReturnValue;
019import javax.annotation.Nullable;
020
021/**
022 * Static convenience methods that help a method or constructor check whether it was invoked
023 * correctly (that is, whether its <i>preconditions</i> were met).
024 *
025 * <p>If the precondition is not met, the {@code Preconditions} method throws an unchecked exception
026 * of a specified type, which helps the method in which the exception was thrown communicate that
027 * its caller has made a mistake. This allows constructs such as
028 *
029 * <pre>{@code
030 * public static double sqrt(double value) {
031 *   if (value < 0) {
032 *     throw new IllegalArgumentException("input is negative: " + value);
033 *   }
034 *   // calculate square root
035 * }
036 * }</pre>
037 *
038 * <p>to be replaced with the more compact
039 *
040 * <pre>{@code
041 * public static double sqrt(double value) {
042 *   checkArgument(value >= 0, "input is negative: %s", value);
043 *   // calculate square root
044 * }
045 * }</pre>
046 *
047 * <p>so that a hypothetical bad caller of this method, such as:
048 *
049 * <pre>{@code
050 *   void exampleBadCaller() {
051 *     double d = sqrt(-1.0);
052 * }
053 * }</pre>
054 *
055 * <p>would be flagged as having called {@code sqrt()} with an illegal argument.
056 *
057 * <h3>Performance</h3>
058 *
059 * <p>Avoid passing message arguments that are expensive to compute; your code will always compute
060 * them, even though they usually won't be needed. If you have such arguments, use the conventional
061 * if/throw idiom instead.
062 *
063 * <p>Depending on your message arguments, memory may be allocated for boxing and varargs array
064 * creation. However, the methods of this class have a large number of overloads that prevent such
065 * allocations in many common cases.
066 *
067 * <p>The message string is not formatted unless the exception will be thrown, so the cost of the
068 * string formatting itself should not be a concern.
069 *
070 * <p>As with any performance concerns, you should consider profiling your code (in a production
071 * environment if possible) before spending a lot of effort on tweaking a particular element.
072 *
073 * <h3>Other types of preconditions</h3>
074 *
075 * <p>Not every type of precondition failure is supported by these methods. Continue to throw
076 * standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link
077 * UnsupportedOperationException} in the situations they are intended for.
078 *
079 * <h3>Non-preconditions</h3>
080 *
081 * <p>It is of course possible to use the methods of this class to check for invalid conditions
082 * which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is
083 * misleading to future readers of the code and of stack traces. See <a
084 * href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional failures
085 * explained</a> in the Guava User Guide for more advice. Notably, {@link Verify} offers assertions
086 * similar to those in this class for non-precondition checks.
087 *
088 * <h3>{@code java.util.Objects.requireNonNull()}</h3>
089 *
090 * <p>Projects which use {@code com.google.common} should generally avoid the use of {@link
091 * java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link
092 * #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation.
093 * (The same goes for the message-accepting overloads.)
094 *
095 * <h3>Only {@code %s} is supported</h3>
096 *
097 * <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is
098 * supported, not the full range of {@link java.util.Formatter} specifiers.
099 *
100 * <h3>More information</h3>
101 *
102 * <p>See the Guava User Guide on <a
103 * href="https://github.com/google/guava/wiki/PreconditionsExplained">using {@code
104 * Preconditions}</a>.
105 *
106 * @author Kevin Bourrillion
107 * @since 2.0
108 */
109@GwtCompatible
110public final class Preconditions {
111  private Preconditions() {}
112
113  /**
114   * Ensures the truth of an expression involving one or more parameters to the calling method.
115   *
116   * @param expression a boolean expression
117   * @throws IllegalArgumentException if {@code expression} is false
118   */
119  public static void checkArgument(boolean expression) {
120    if (!expression) {
121      throw new IllegalArgumentException();
122    }
123  }
124
125  /**
126   * Ensures the truth of an expression involving one or more parameters to the calling method.
127   *
128   * @param expression a boolean expression
129   * @param errorMessage the exception message to use if the check fails; will be converted to a
130   *     string using {@link String#valueOf(Object)}
131   * @throws IllegalArgumentException if {@code expression} is false
132   */
133  public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
134    if (!expression) {
135      throw new IllegalArgumentException(String.valueOf(errorMessage));
136    }
137  }
138
139  /**
140   * Ensures the truth of an expression involving one or more parameters to the calling method.
141   *
142   * @param expression a boolean expression
143   * @param errorMessageTemplate a template for the exception message should the check fail. The
144   *     message is formed by replacing each {@code %s} placeholder in the template with an
145   *     argument. These are matched by position - the first {@code %s} gets {@code
146   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
147   *     square braces. Unmatched placeholders will be left as-is.
148   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
149   *     are converted to strings using {@link String#valueOf(Object)}.
150   * @throws IllegalArgumentException if {@code expression} is false
151   */
152  public static void checkArgument(
153      boolean expression,
154      @Nullable String errorMessageTemplate,
155      @Nullable Object... errorMessageArgs) {
156    if (!expression) {
157      throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
158    }
159  }
160
161  /**
162   * Ensures the truth of an expression involving one or more parameters to the calling method.
163   *
164   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
165   *
166   * @since 20.0 (varargs overload since 2.0)
167   */
168  public static void checkArgument(boolean b, @Nullable String errorMessageTemplate, char p1) {
169    if (!b) {
170      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
171    }
172  }
173
174  /**
175   * Ensures the truth of an expression involving one or more parameters to the calling method.
176   *
177   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
178   *
179   * @since 20.0 (varargs overload since 2.0)
180   */
181  public static void checkArgument(boolean b, @Nullable String errorMessageTemplate, int p1) {
182    if (!b) {
183      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
184    }
185  }
186
187  /**
188   * Ensures the truth of an expression involving one or more parameters to the calling method.
189   *
190   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
191   *
192   * @since 20.0 (varargs overload since 2.0)
193   */
194  public static void checkArgument(boolean b, @Nullable String errorMessageTemplate, long p1) {
195    if (!b) {
196      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
197    }
198  }
199
200  /**
201   * Ensures the truth of an expression involving one or more parameters to the calling method.
202   *
203   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
204   *
205   * @since 20.0 (varargs overload since 2.0)
206   */
207  public static void checkArgument(
208      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1) {
209    if (!b) {
210      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
211    }
212  }
213
214  /**
215   * Ensures the truth of an expression involving one or more parameters to the calling method.
216   *
217   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
218   *
219   * @since 20.0 (varargs overload since 2.0)
220   */
221  public static void checkArgument(
222      boolean b, @Nullable String errorMessageTemplate, char p1, char p2) {
223    if (!b) {
224      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
225    }
226  }
227
228  /**
229   * Ensures the truth of an expression involving one or more parameters to the calling method.
230   *
231   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
232   *
233   * @since 20.0 (varargs overload since 2.0)
234   */
235  public static void checkArgument(
236      boolean b, @Nullable String errorMessageTemplate, char p1, int p2) {
237    if (!b) {
238      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
239    }
240  }
241
242  /**
243   * Ensures the truth of an expression involving one or more parameters to the calling method.
244   *
245   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
246   *
247   * @since 20.0 (varargs overload since 2.0)
248   */
249  public static void checkArgument(
250      boolean b, @Nullable String errorMessageTemplate, char p1, long p2) {
251    if (!b) {
252      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
253    }
254  }
255
256  /**
257   * Ensures the truth of an expression involving one or more parameters to the calling method.
258   *
259   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
260   *
261   * @since 20.0 (varargs overload since 2.0)
262   */
263  public static void checkArgument(
264      boolean b, @Nullable String errorMessageTemplate, char p1, @Nullable Object p2) {
265    if (!b) {
266      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
267    }
268  }
269
270  /**
271   * Ensures the truth of an expression involving one or more parameters to the calling method.
272   *
273   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
274   *
275   * @since 20.0 (varargs overload since 2.0)
276   */
277  public static void checkArgument(
278      boolean b, @Nullable String errorMessageTemplate, int p1, char p2) {
279    if (!b) {
280      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
281    }
282  }
283
284  /**
285   * Ensures the truth of an expression involving one or more parameters to the calling method.
286   *
287   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
288   *
289   * @since 20.0 (varargs overload since 2.0)
290   */
291  public static void checkArgument(
292      boolean b, @Nullable String errorMessageTemplate, int p1, int p2) {
293    if (!b) {
294      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
295    }
296  }
297
298  /**
299   * Ensures the truth of an expression involving one or more parameters to the calling method.
300   *
301   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
302   *
303   * @since 20.0 (varargs overload since 2.0)
304   */
305  public static void checkArgument(
306      boolean b, @Nullable String errorMessageTemplate, int p1, long p2) {
307    if (!b) {
308      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
309    }
310  }
311
312  /**
313   * Ensures the truth of an expression involving one or more parameters to the calling method.
314   *
315   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
316   *
317   * @since 20.0 (varargs overload since 2.0)
318   */
319  public static void checkArgument(
320      boolean b, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2) {
321    if (!b) {
322      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
323    }
324  }
325
326  /**
327   * Ensures the truth of an expression involving one or more parameters to the calling method.
328   *
329   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
330   *
331   * @since 20.0 (varargs overload since 2.0)
332   */
333  public static void checkArgument(
334      boolean b, @Nullable String errorMessageTemplate, long p1, char p2) {
335    if (!b) {
336      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
337    }
338  }
339
340  /**
341   * Ensures the truth of an expression involving one or more parameters to the calling method.
342   *
343   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
344   *
345   * @since 20.0 (varargs overload since 2.0)
346   */
347  public static void checkArgument(
348      boolean b, @Nullable String errorMessageTemplate, long p1, int p2) {
349    if (!b) {
350      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
351    }
352  }
353
354  /**
355   * Ensures the truth of an expression involving one or more parameters to the calling method.
356   *
357   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
358   *
359   * @since 20.0 (varargs overload since 2.0)
360   */
361  public static void checkArgument(
362      boolean b, @Nullable String errorMessageTemplate, long p1, long p2) {
363    if (!b) {
364      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
365    }
366  }
367
368  /**
369   * Ensures the truth of an expression involving one or more parameters to the calling method.
370   *
371   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
372   *
373   * @since 20.0 (varargs overload since 2.0)
374   */
375  public static void checkArgument(
376      boolean b, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
377    if (!b) {
378      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
379    }
380  }
381
382  /**
383   * Ensures the truth of an expression involving one or more parameters to the calling method.
384   *
385   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
386   *
387   * @since 20.0 (varargs overload since 2.0)
388   */
389  public static void checkArgument(
390      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, char p2) {
391    if (!b) {
392      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
393    }
394  }
395
396  /**
397   * Ensures the truth of an expression involving one or more parameters to the calling method.
398   *
399   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
400   *
401   * @since 20.0 (varargs overload since 2.0)
402   */
403  public static void checkArgument(
404      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
405    if (!b) {
406      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
407    }
408  }
409
410  /**
411   * Ensures the truth of an expression involving one or more parameters to the calling method.
412   *
413   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
414   *
415   * @since 20.0 (varargs overload since 2.0)
416   */
417  public static void checkArgument(
418      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
419    if (!b) {
420      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
421    }
422  }
423
424  /**
425   * Ensures the truth of an expression involving one or more parameters to the calling method.
426   *
427   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
428   *
429   * @since 20.0 (varargs overload since 2.0)
430   */
431  public static void checkArgument(
432      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
433    if (!b) {
434      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
435    }
436  }
437
438  /**
439   * Ensures the truth of an expression involving one or more parameters to the calling method.
440   *
441   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
442   *
443   * @since 20.0 (varargs overload since 2.0)
444   */
445  public static void checkArgument(
446      boolean b,
447      @Nullable String errorMessageTemplate,
448      @Nullable Object p1,
449      @Nullable Object p2,
450      @Nullable Object p3) {
451    if (!b) {
452      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3));
453    }
454  }
455
456  /**
457   * Ensures the truth of an expression involving one or more parameters to the calling method.
458   *
459   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
460   *
461   * @since 20.0 (varargs overload since 2.0)
462   */
463  public static void checkArgument(
464      boolean b,
465      @Nullable String errorMessageTemplate,
466      @Nullable Object p1,
467      @Nullable Object p2,
468      @Nullable Object p3,
469      @Nullable Object p4) {
470    if (!b) {
471      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3, p4));
472    }
473  }
474
475  /**
476   * Ensures the truth of an expression involving the state of the calling instance, but not
477   * involving any parameters to the calling method.
478   *
479   * @param expression a boolean expression
480   * @throws IllegalStateException if {@code expression} is false
481   * @see Verify#verify Verify.verify()
482   */
483  public static void checkState(boolean expression) {
484    if (!expression) {
485      throw new IllegalStateException();
486    }
487  }
488
489  /**
490   * Ensures the truth of an expression involving the state of the calling instance, but not
491   * involving any parameters to the calling method.
492   *
493   * @param expression a boolean expression
494   * @param errorMessage the exception message to use if the check fails; will be converted to a
495   *     string using {@link String#valueOf(Object)}
496   * @throws IllegalStateException if {@code expression} is false
497   * @see Verify#verify Verify.verify()
498   */
499  public static void checkState(boolean expression, @Nullable Object errorMessage) {
500    if (!expression) {
501      throw new IllegalStateException(String.valueOf(errorMessage));
502    }
503  }
504
505  /**
506   * Ensures the truth of an expression involving the state of the calling instance, but not
507   * involving any parameters to the calling method.
508   *
509   * @param expression a boolean expression
510   * @param errorMessageTemplate a template for the exception message should the check fail. The
511   *     message is formed by replacing each {@code %s} placeholder in the template with an
512   *     argument. These are matched by position - the first {@code %s} gets {@code
513   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
514   *     square braces. Unmatched placeholders will be left as-is.
515   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
516   *     are converted to strings using {@link String#valueOf(Object)}.
517   * @throws IllegalStateException if {@code expression} is false
518   * @see Verify#verify Verify.verify()
519   */
520  public static void checkState(
521      boolean expression,
522      @Nullable String errorMessageTemplate,
523      @Nullable Object... errorMessageArgs) {
524    if (!expression) {
525      throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
526    }
527  }
528
529  /**
530   * Ensures the truth of an expression involving the state of the calling instance, but not
531   * involving any parameters to the calling method.
532   *
533   * <p>See {@link #checkState(boolean, String, Object...)} for details.
534   *
535   * @since 20.0 (varargs overload since 2.0)
536   */
537  public static void checkState(boolean b, @Nullable String errorMessageTemplate, char p1) {
538    if (!b) {
539      throw new IllegalStateException(format(errorMessageTemplate, p1));
540    }
541  }
542
543  /**
544   * Ensures the truth of an expression involving the state of the calling instance, but not
545   * involving any parameters to the calling method.
546   *
547   * <p>See {@link #checkState(boolean, String, Object...)} for details.
548   *
549   * @since 20.0 (varargs overload since 2.0)
550   */
551  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1) {
552    if (!b) {
553      throw new IllegalStateException(format(errorMessageTemplate, p1));
554    }
555  }
556
557  /**
558   * Ensures the truth of an expression involving the state of the calling instance, but not
559   * involving any parameters to the calling method.
560   *
561   * <p>See {@link #checkState(boolean, String, Object...)} for details.
562   *
563   * @since 20.0 (varargs overload since 2.0)
564   */
565  public static void checkState(boolean b, @Nullable String errorMessageTemplate, long p1) {
566    if (!b) {
567      throw new IllegalStateException(format(errorMessageTemplate, p1));
568    }
569  }
570
571  /**
572   * Ensures the truth of an expression involving the state of the calling instance, but not
573   * involving any parameters to the calling method.
574   *
575   * <p>See {@link #checkState(boolean, String, Object...)} for details.
576   *
577   * @since 20.0 (varargs overload since 2.0)
578   */
579  public static void checkState(
580      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1) {
581    if (!b) {
582      throw new IllegalStateException(format(errorMessageTemplate, p1));
583    }
584  }
585
586  /**
587   * Ensures the truth of an expression involving the state of the calling instance, but not
588   * involving any parameters to the calling method.
589   *
590   * <p>See {@link #checkState(boolean, String, Object...)} for details.
591   *
592   * @since 20.0 (varargs overload since 2.0)
593   */
594  public static void checkState(
595      boolean b, @Nullable String errorMessageTemplate, char p1, char p2) {
596    if (!b) {
597      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
598    }
599  }
600
601  /**
602   * Ensures the truth of an expression involving the state of the calling instance, but not
603   * involving any parameters to the calling method.
604   *
605   * <p>See {@link #checkState(boolean, String, Object...)} for details.
606   *
607   * @since 20.0 (varargs overload since 2.0)
608   */
609  public static void checkState(boolean b, @Nullable String errorMessageTemplate, char p1, int p2) {
610    if (!b) {
611      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
612    }
613  }
614
615  /**
616   * Ensures the truth of an expression involving the state of the calling instance, but not
617   * involving any parameters to the calling method.
618   *
619   * <p>See {@link #checkState(boolean, String, Object...)} for details.
620   *
621   * @since 20.0 (varargs overload since 2.0)
622   */
623  public static void checkState(
624      boolean b, @Nullable String errorMessageTemplate, char p1, long p2) {
625    if (!b) {
626      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
627    }
628  }
629
630  /**
631   * Ensures the truth of an expression involving the state of the calling instance, but not
632   * involving any parameters to the calling method.
633   *
634   * <p>See {@link #checkState(boolean, String, Object...)} for details.
635   *
636   * @since 20.0 (varargs overload since 2.0)
637   */
638  public static void checkState(
639      boolean b, @Nullable String errorMessageTemplate, char p1, @Nullable Object p2) {
640    if (!b) {
641      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
642    }
643  }
644
645  /**
646   * Ensures the truth of an expression involving the state of the calling instance, but not
647   * involving any parameters to the calling method.
648   *
649   * <p>See {@link #checkState(boolean, String, Object...)} for details.
650   *
651   * @since 20.0 (varargs overload since 2.0)
652   */
653  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1, char p2) {
654    if (!b) {
655      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
656    }
657  }
658
659  /**
660   * Ensures the truth of an expression involving the state of the calling instance, but not
661   * involving any parameters to the calling method.
662   *
663   * <p>See {@link #checkState(boolean, String, Object...)} for details.
664   *
665   * @since 20.0 (varargs overload since 2.0)
666   */
667  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1, int p2) {
668    if (!b) {
669      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
670    }
671  }
672
673  /**
674   * Ensures the truth of an expression involving the state of the calling instance, but not
675   * involving any parameters to the calling method.
676   *
677   * <p>See {@link #checkState(boolean, String, Object...)} for details.
678   *
679   * @since 20.0 (varargs overload since 2.0)
680   */
681  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1, long p2) {
682    if (!b) {
683      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
684    }
685  }
686
687  /**
688   * Ensures the truth of an expression involving the state of the calling instance, but not
689   * involving any parameters to the calling method.
690   *
691   * <p>See {@link #checkState(boolean, String, Object...)} for details.
692   *
693   * @since 20.0 (varargs overload since 2.0)
694   */
695  public static void checkState(
696      boolean b, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2) {
697    if (!b) {
698      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
699    }
700  }
701
702  /**
703   * Ensures the truth of an expression involving the state of the calling instance, but not
704   * involving any parameters to the calling method.
705   *
706   * <p>See {@link #checkState(boolean, String, Object...)} for details.
707   *
708   * @since 20.0 (varargs overload since 2.0)
709   */
710  public static void checkState(
711      boolean b, @Nullable String errorMessageTemplate, long p1, char p2) {
712    if (!b) {
713      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
714    }
715  }
716
717  /**
718   * Ensures the truth of an expression involving the state of the calling instance, but not
719   * involving any parameters to the calling method.
720   *
721   * <p>See {@link #checkState(boolean, String, Object...)} for details.
722   *
723   * @since 20.0 (varargs overload since 2.0)
724   */
725  public static void checkState(boolean b, @Nullable String errorMessageTemplate, long p1, int p2) {
726    if (!b) {
727      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
728    }
729  }
730
731  /**
732   * Ensures the truth of an expression involving the state of the calling instance, but not
733   * involving any parameters to the calling method.
734   *
735   * <p>See {@link #checkState(boolean, String, Object...)} for details.
736   *
737   * @since 20.0 (varargs overload since 2.0)
738   */
739  public static void checkState(
740      boolean b, @Nullable String errorMessageTemplate, long p1, long p2) {
741    if (!b) {
742      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
743    }
744  }
745
746  /**
747   * Ensures the truth of an expression involving the state of the calling instance, but not
748   * involving any parameters to the calling method.
749   *
750   * <p>See {@link #checkState(boolean, String, Object...)} for details.
751   *
752   * @since 20.0 (varargs overload since 2.0)
753   */
754  public static void checkState(
755      boolean b, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
756    if (!b) {
757      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
758    }
759  }
760
761  /**
762   * Ensures the truth of an expression involving the state of the calling instance, but not
763   * involving any parameters to the calling method.
764   *
765   * <p>See {@link #checkState(boolean, String, Object...)} for details.
766   *
767   * @since 20.0 (varargs overload since 2.0)
768   */
769  public static void checkState(
770      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, char p2) {
771    if (!b) {
772      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
773    }
774  }
775
776  /**
777   * Ensures the truth of an expression involving the state of the calling instance, but not
778   * involving any parameters to the calling method.
779   *
780   * <p>See {@link #checkState(boolean, String, Object...)} for details.
781   *
782   * @since 20.0 (varargs overload since 2.0)
783   */
784  public static void checkState(
785      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
786    if (!b) {
787      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
788    }
789  }
790
791  /**
792   * Ensures the truth of an expression involving the state of the calling instance, but not
793   * involving any parameters to the calling method.
794   *
795   * <p>See {@link #checkState(boolean, String, Object...)} for details.
796   *
797   * @since 20.0 (varargs overload since 2.0)
798   */
799  public static void checkState(
800      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
801    if (!b) {
802      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
803    }
804  }
805
806  /**
807   * Ensures the truth of an expression involving the state of the calling instance, but not
808   * involving any parameters to the calling method.
809   *
810   * <p>See {@link #checkState(boolean, String, Object...)} for details.
811   *
812   * @since 20.0 (varargs overload since 2.0)
813   */
814  public static void checkState(
815      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
816    if (!b) {
817      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
818    }
819  }
820
821  /**
822   * Ensures the truth of an expression involving the state of the calling instance, but not
823   * involving any parameters to the calling method.
824   *
825   * <p>See {@link #checkState(boolean, String, Object...)} for details.
826   *
827   * @since 20.0 (varargs overload since 2.0)
828   */
829  public static void checkState(
830      boolean b,
831      @Nullable String errorMessageTemplate,
832      @Nullable Object p1,
833      @Nullable Object p2,
834      @Nullable Object p3) {
835    if (!b) {
836      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
837    }
838  }
839
840  /**
841   * Ensures the truth of an expression involving the state of the calling instance, but not
842   * involving any parameters to the calling method.
843   *
844   * <p>See {@link #checkState(boolean, String, Object...)} for details.
845   *
846   * @since 20.0 (varargs overload since 2.0)
847   */
848  public static void checkState(
849      boolean b,
850      @Nullable String errorMessageTemplate,
851      @Nullable Object p1,
852      @Nullable Object p2,
853      @Nullable Object p3,
854      @Nullable Object p4) {
855    if (!b) {
856      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3, p4));
857    }
858  }
859
860  /**
861   * Ensures that an object reference passed as a parameter to the calling method is not null.
862   *
863   * @param reference an object reference
864   * @return the non-null reference that was validated
865   * @throws NullPointerException if {@code reference} is null
866   * @see Verify#verifyNotNull Verify.verifyNotNull()
867   */
868  @CanIgnoreReturnValue
869  public static <T> T checkNotNull(T reference) {
870    if (reference == null) {
871      throw new NullPointerException();
872    }
873    return reference;
874  }
875
876  /**
877   * Ensures that an object reference passed as a parameter to the calling method is not null.
878   *
879   * @param reference an object reference
880   * @param errorMessage the exception message to use if the check fails; will be converted to a
881   *     string using {@link String#valueOf(Object)}
882   * @return the non-null reference that was validated
883   * @throws NullPointerException if {@code reference} is null
884   * @see Verify#verifyNotNull Verify.verifyNotNull()
885   */
886  @CanIgnoreReturnValue
887  public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
888    if (reference == null) {
889      throw new NullPointerException(String.valueOf(errorMessage));
890    }
891    return reference;
892  }
893
894  /**
895   * Ensures that an object reference passed as a parameter to the calling method is not null.
896   *
897   * @param reference an object reference
898   * @param errorMessageTemplate a template for the exception message should the check fail. The
899   *     message is formed by replacing each {@code %s} placeholder in the template with an
900   *     argument. These are matched by position - the first {@code %s} gets {@code
901   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
902   *     square braces. Unmatched placeholders will be left as-is.
903   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
904   *     are converted to strings using {@link String#valueOf(Object)}.
905   * @return the non-null reference that was validated
906   * @throws NullPointerException if {@code reference} is null
907   * @see Verify#verifyNotNull Verify.verifyNotNull()
908   */
909  @CanIgnoreReturnValue
910  public static <T> T checkNotNull(
911      T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
912    if (reference == null) {
913      throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
914    }
915    return reference;
916  }
917
918  /**
919   * Ensures that an object reference passed as a parameter to the calling method is not null.
920   *
921   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
922   *
923   * @since 20.0 (varargs overload since 2.0)
924   */
925  @CanIgnoreReturnValue
926  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1) {
927    if (obj == null) {
928      throw new NullPointerException(format(errorMessageTemplate, p1));
929    }
930    return obj;
931  }
932
933  /**
934   * Ensures that an object reference passed as a parameter to the calling method is not null.
935   *
936   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
937   *
938   * @since 20.0 (varargs overload since 2.0)
939   */
940  @CanIgnoreReturnValue
941  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1) {
942    if (obj == null) {
943      throw new NullPointerException(format(errorMessageTemplate, p1));
944    }
945    return obj;
946  }
947
948  /**
949   * Ensures that an object reference passed as a parameter to the calling method is not null.
950   *
951   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
952   *
953   * @since 20.0 (varargs overload since 2.0)
954   */
955  @CanIgnoreReturnValue
956  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1) {
957    if (obj == null) {
958      throw new NullPointerException(format(errorMessageTemplate, p1));
959    }
960    return obj;
961  }
962
963  /**
964   * Ensures that an object reference passed as a parameter to the calling method is not null.
965   *
966   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
967   *
968   * @since 20.0 (varargs overload since 2.0)
969   */
970  @CanIgnoreReturnValue
971  public static <T> T checkNotNull(
972      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1) {
973    if (obj == null) {
974      throw new NullPointerException(format(errorMessageTemplate, p1));
975    }
976    return obj;
977  }
978
979  /**
980   * Ensures that an object reference passed as a parameter to the calling method is not null.
981   *
982   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
983   *
984   * @since 20.0 (varargs overload since 2.0)
985   */
986  @CanIgnoreReturnValue
987  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, char p2) {
988    if (obj == null) {
989      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
990    }
991    return obj;
992  }
993
994  /**
995   * Ensures that an object reference passed as a parameter to the calling method is not null.
996   *
997   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
998   *
999   * @since 20.0 (varargs overload since 2.0)
1000   */
1001  @CanIgnoreReturnValue
1002  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, int p2) {
1003    if (obj == null) {
1004      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1005    }
1006    return obj;
1007  }
1008
1009  /**
1010   * Ensures that an object reference passed as a parameter to the calling method is not null.
1011   *
1012   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1013   *
1014   * @since 20.0 (varargs overload since 2.0)
1015   */
1016  @CanIgnoreReturnValue
1017  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, long p2) {
1018    if (obj == null) {
1019      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1020    }
1021    return obj;
1022  }
1023
1024  /**
1025   * Ensures that an object reference passed as a parameter to the calling method is not null.
1026   *
1027   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1028   *
1029   * @since 20.0 (varargs overload since 2.0)
1030   */
1031  @CanIgnoreReturnValue
1032  public static <T> T checkNotNull(
1033      T obj, @Nullable String errorMessageTemplate, char p1, @Nullable Object p2) {
1034    if (obj == null) {
1035      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1036    }
1037    return obj;
1038  }
1039
1040  /**
1041   * Ensures that an object reference passed as a parameter to the calling method is not null.
1042   *
1043   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1044   *
1045   * @since 20.0 (varargs overload since 2.0)
1046   */
1047  @CanIgnoreReturnValue
1048  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, char p2) {
1049    if (obj == null) {
1050      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1051    }
1052    return obj;
1053  }
1054
1055  /**
1056   * Ensures that an object reference passed as a parameter to the calling method is not null.
1057   *
1058   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1059   *
1060   * @since 20.0 (varargs overload since 2.0)
1061   */
1062  @CanIgnoreReturnValue
1063  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, int p2) {
1064    if (obj == null) {
1065      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1066    }
1067    return obj;
1068  }
1069
1070  /**
1071   * Ensures that an object reference passed as a parameter to the calling method is not null.
1072   *
1073   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1074   *
1075   * @since 20.0 (varargs overload since 2.0)
1076   */
1077  @CanIgnoreReturnValue
1078  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, long p2) {
1079    if (obj == null) {
1080      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1081    }
1082    return obj;
1083  }
1084
1085  /**
1086   * Ensures that an object reference passed as a parameter to the calling method is not null.
1087   *
1088   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1089   *
1090   * @since 20.0 (varargs overload since 2.0)
1091   */
1092  @CanIgnoreReturnValue
1093  public static <T> T checkNotNull(
1094      T obj, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2) {
1095    if (obj == null) {
1096      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1097    }
1098    return obj;
1099  }
1100
1101  /**
1102   * Ensures that an object reference passed as a parameter to the calling method is not null.
1103   *
1104   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1105   *
1106   * @since 20.0 (varargs overload since 2.0)
1107   */
1108  @CanIgnoreReturnValue
1109  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, char p2) {
1110    if (obj == null) {
1111      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1112    }
1113    return obj;
1114  }
1115
1116  /**
1117   * Ensures that an object reference passed as a parameter to the calling method is not null.
1118   *
1119   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1120   *
1121   * @since 20.0 (varargs overload since 2.0)
1122   */
1123  @CanIgnoreReturnValue
1124  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, int p2) {
1125    if (obj == null) {
1126      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1127    }
1128    return obj;
1129  }
1130
1131  /**
1132   * Ensures that an object reference passed as a parameter to the calling method is not null.
1133   *
1134   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1135   *
1136   * @since 20.0 (varargs overload since 2.0)
1137   */
1138  @CanIgnoreReturnValue
1139  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, long p2) {
1140    if (obj == null) {
1141      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1142    }
1143    return obj;
1144  }
1145
1146  /**
1147   * Ensures that an object reference passed as a parameter to the calling method is not null.
1148   *
1149   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1150   *
1151   * @since 20.0 (varargs overload since 2.0)
1152   */
1153  @CanIgnoreReturnValue
1154  public static <T> T checkNotNull(
1155      T obj, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
1156    if (obj == null) {
1157      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1158    }
1159    return obj;
1160  }
1161
1162  /**
1163   * Ensures that an object reference passed as a parameter to the calling method is not null.
1164   *
1165   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1166   *
1167   * @since 20.0 (varargs overload since 2.0)
1168   */
1169  @CanIgnoreReturnValue
1170  public static <T> T checkNotNull(
1171      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, char p2) {
1172    if (obj == null) {
1173      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1174    }
1175    return obj;
1176  }
1177
1178  /**
1179   * Ensures that an object reference passed as a parameter to the calling method is not null.
1180   *
1181   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1182   *
1183   * @since 20.0 (varargs overload since 2.0)
1184   */
1185  @CanIgnoreReturnValue
1186  public static <T> T checkNotNull(
1187      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
1188    if (obj == null) {
1189      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1190    }
1191    return obj;
1192  }
1193
1194  /**
1195   * Ensures that an object reference passed as a parameter to the calling method is not null.
1196   *
1197   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1198   *
1199   * @since 20.0 (varargs overload since 2.0)
1200   */
1201  @CanIgnoreReturnValue
1202  public static <T> T checkNotNull(
1203      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
1204    if (obj == null) {
1205      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1206    }
1207    return obj;
1208  }
1209
1210  /**
1211   * Ensures that an object reference passed as a parameter to the calling method is not null.
1212   *
1213   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1214   *
1215   * @since 20.0 (varargs overload since 2.0)
1216   */
1217  @CanIgnoreReturnValue
1218  public static <T> T checkNotNull(
1219      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
1220    if (obj == null) {
1221      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1222    }
1223    return obj;
1224  }
1225
1226  /**
1227   * Ensures that an object reference passed as a parameter to the calling method is not null.
1228   *
1229   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1230   *
1231   * @since 20.0 (varargs overload since 2.0)
1232   */
1233  @CanIgnoreReturnValue
1234  public static <T> T checkNotNull(
1235      T obj,
1236      @Nullable String errorMessageTemplate,
1237      @Nullable Object p1,
1238      @Nullable Object p2,
1239      @Nullable Object p3) {
1240    if (obj == null) {
1241      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3));
1242    }
1243    return obj;
1244  }
1245
1246  /**
1247   * Ensures that an object reference passed as a parameter to the calling method is not null.
1248   *
1249   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1250   *
1251   * @since 20.0 (varargs overload since 2.0)
1252   */
1253  @CanIgnoreReturnValue
1254  public static <T> T checkNotNull(
1255      T obj,
1256      @Nullable String errorMessageTemplate,
1257      @Nullable Object p1,
1258      @Nullable Object p2,
1259      @Nullable Object p3,
1260      @Nullable Object p4) {
1261    if (obj == null) {
1262      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3, p4));
1263    }
1264    return obj;
1265  }
1266
1267  /*
1268   * All recent hotspots (as of 2009) *really* like to have the natural code
1269   *
1270   * if (guardExpression) {
1271   *    throw new BadException(messageExpression);
1272   * }
1273   *
1274   * refactored so that messageExpression is moved to a separate String-returning method.
1275   *
1276   * if (guardExpression) {
1277   *    throw new BadException(badMsg(...));
1278   * }
1279   *
1280   * The alternative natural refactorings into void or Exception-returning methods are much slower.
1281   * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is
1282   * a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
1283   *
1284   * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
1285   * RangeCheckMicroBenchmark in the JDK that was used to test this.
1286   *
1287   * But the methods in this class want to throw different exceptions, depending on the args, so it
1288   * appears that this pattern is not directly applicable. But we can use the ridiculous, devious
1289   * trick of throwing an exception in the middle of the construction of another exception. Hotspot
1290   * is fine with that.
1291   */
1292
1293  /**
1294   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1295   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1296   *
1297   * @param index a user-supplied index identifying an element of an array, list or string
1298   * @param size the size of that array, list or string
1299   * @return the value of {@code index}
1300   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1301   * @throws IllegalArgumentException if {@code size} is negative
1302   */
1303  @CanIgnoreReturnValue
1304  public static int checkElementIndex(int index, int size) {
1305    return checkElementIndex(index, size, "index");
1306  }
1307
1308  /**
1309   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1310   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1311   *
1312   * @param index a user-supplied index identifying an element of an array, list or string
1313   * @param size the size of that array, list or string
1314   * @param desc the text to use to describe this index in an error message
1315   * @return the value of {@code index}
1316   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1317   * @throws IllegalArgumentException if {@code size} is negative
1318   */
1319  @CanIgnoreReturnValue
1320  public static int checkElementIndex(int index, int size, @Nullable String desc) {
1321    // Carefully optimized for execution by hotspot (explanatory comment above)
1322    if (index < 0 || index >= size) {
1323      throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
1324    }
1325    return index;
1326  }
1327
1328  private static String badElementIndex(int index, int size, String desc) {
1329    if (index < 0) {
1330      return format("%s (%s) must not be negative", desc, index);
1331    } else if (size < 0) {
1332      throw new IllegalArgumentException("negative size: " + size);
1333    } else { // index >= size
1334      return format("%s (%s) must be less than size (%s)", desc, index, size);
1335    }
1336  }
1337
1338  /**
1339   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1340   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1341   *
1342   * @param index a user-supplied index identifying a position in an array, list or string
1343   * @param size the size of that array, list or string
1344   * @return the value of {@code index}
1345   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1346   * @throws IllegalArgumentException if {@code size} is negative
1347   */
1348  @CanIgnoreReturnValue
1349  public static int checkPositionIndex(int index, int size) {
1350    return checkPositionIndex(index, size, "index");
1351  }
1352
1353  /**
1354   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1355   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1356   *
1357   * @param index a user-supplied index identifying a position in an array, list or string
1358   * @param size the size of that array, list or string
1359   * @param desc the text to use to describe this index in an error message
1360   * @return the value of {@code index}
1361   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1362   * @throws IllegalArgumentException if {@code size} is negative
1363   */
1364  @CanIgnoreReturnValue
1365  public static int checkPositionIndex(int index, int size, @Nullable String desc) {
1366    // Carefully optimized for execution by hotspot (explanatory comment above)
1367    if (index < 0 || index > size) {
1368      throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
1369    }
1370    return index;
1371  }
1372
1373  private static String badPositionIndex(int index, int size, String desc) {
1374    if (index < 0) {
1375      return format("%s (%s) must not be negative", desc, index);
1376    } else if (size < 0) {
1377      throw new IllegalArgumentException("negative size: " + size);
1378    } else { // index > size
1379      return format("%s (%s) must not be greater than size (%s)", desc, index, size);
1380    }
1381  }
1382
1383  /**
1384   * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list
1385   * or string of size {@code size}, and are in order. A position index may range from zero to
1386   * {@code size}, inclusive.
1387   *
1388   * @param start a user-supplied index identifying a starting position in an array, list or string
1389   * @param end a user-supplied index identifying a ending position in an array, list or string
1390   * @param size the size of that array, list or string
1391   * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size},
1392   *     or if {@code end} is less than {@code start}
1393   * @throws IllegalArgumentException if {@code size} is negative
1394   */
1395  public static void checkPositionIndexes(int start, int end, int size) {
1396    // Carefully optimized for execution by hotspot (explanatory comment above)
1397    if (start < 0 || end < start || end > size) {
1398      throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
1399    }
1400  }
1401
1402  private static String badPositionIndexes(int start, int end, int size) {
1403    if (start < 0 || start > size) {
1404      return badPositionIndex(start, size, "start index");
1405    }
1406    if (end < 0 || end > size) {
1407      return badPositionIndex(end, size, "end index");
1408    }
1409    // end < start
1410    return format("end index (%s) must not be less than start index (%s)", end, start);
1411  }
1412
1413  /**
1414   * Substitutes each {@code %s} in {@code template} with an argument. These are matched by
1415   * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
1416   * placeholders, the unmatched arguments will be appended to the end of the formatted message in
1417   * square braces.
1418   *
1419   * @param template a string containing 0 or more {@code %s} placeholders. null is treated as
1420   *     "null".
1421   * @param args the arguments to be substituted into the message template. Arguments are converted
1422   *     to strings using {@link String#valueOf(Object)}. Arguments can be null.
1423   */
1424  // Note that this is somewhat-improperly used from Verify.java as well.
1425  static String format(@Nullable String template, @Nullable Object... args) {
1426    template = String.valueOf(template); // null -> "null"
1427
1428    args = args == null ? new Object[]{"(Object[])null"} : args;
1429
1430    // start substituting the arguments into the '%s' placeholders
1431    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
1432    int templateStart = 0;
1433    int i = 0;
1434    while (i < args.length) {
1435      int placeholderStart = template.indexOf("%s", templateStart);
1436      if (placeholderStart == -1) {
1437        break;
1438      }
1439      builder.append(template, templateStart, placeholderStart);
1440      builder.append(args[i++]);
1441      templateStart = placeholderStart + 2;
1442    }
1443    builder.append(template, templateStart, template.length());
1444
1445    // if we run out of placeholders, append the extra args in square braces
1446    if (i < args.length) {
1447      builder.append(" [");
1448      builder.append(args[i++]);
1449      while (i < args.length) {
1450        builder.append(", ");
1451        builder.append(args[i++]);
1452      }
1453      builder.append(']');
1454    }
1455
1456    return builder.toString();
1457  }
1458}