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   * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
152   *     {@code errorMessageArgs} is null (don't let this happen)
153   */
154  public static void checkArgument(
155      boolean expression,
156      @Nullable String errorMessageTemplate,
157      @Nullable Object... errorMessageArgs) {
158    if (!expression) {
159      throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
160    }
161  }
162
163  /**
164   * Ensures the truth of an expression involving one or more parameters to the calling method.
165   *
166   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
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  public static void checkArgument(boolean b, @Nullable String errorMessageTemplate, int p1) {
180    if (!b) {
181      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
182    }
183  }
184
185  /**
186   * Ensures the truth of an expression involving one or more parameters to the calling method.
187   *
188   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
189   */
190  public static void checkArgument(boolean b, @Nullable String errorMessageTemplate, long p1) {
191    if (!b) {
192      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
193    }
194  }
195
196  /**
197   * Ensures the truth of an expression involving one or more parameters to the calling method.
198   *
199   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
200   */
201  public static void checkArgument(
202      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1) {
203    if (!b) {
204      throw new IllegalArgumentException(format(errorMessageTemplate, p1));
205    }
206  }
207
208  /**
209   * Ensures the truth of an expression involving one or more parameters to the calling method.
210   *
211   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
212   */
213  public static void checkArgument(
214      boolean b, @Nullable String errorMessageTemplate, char p1, char p2) {
215    if (!b) {
216      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
217    }
218  }
219
220  /**
221   * Ensures the truth of an expression involving one or more parameters to the calling method.
222   *
223   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
224   */
225  public static void checkArgument(
226      boolean b, @Nullable String errorMessageTemplate, char p1, int p2) {
227    if (!b) {
228      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
229    }
230  }
231
232  /**
233   * Ensures the truth of an expression involving one or more parameters to the calling method.
234   *
235   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
236   */
237  public static void checkArgument(
238      boolean b, @Nullable String errorMessageTemplate, char p1, long p2) {
239    if (!b) {
240      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
241    }
242  }
243
244  /**
245   * Ensures the truth of an expression involving one or more parameters to the calling method.
246   *
247   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
248   */
249  public static void checkArgument(
250      boolean b, @Nullable String errorMessageTemplate, char p1, @Nullable Object 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  public static void checkArgument(
262      boolean b, @Nullable String errorMessageTemplate, int p1, char p2) {
263    if (!b) {
264      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
265    }
266  }
267
268  /**
269   * Ensures the truth of an expression involving one or more parameters to the calling method.
270   *
271   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
272   */
273  public static void checkArgument(
274      boolean b, @Nullable String errorMessageTemplate, int p1, int p2) {
275    if (!b) {
276      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
277    }
278  }
279
280  /**
281   * Ensures the truth of an expression involving one or more parameters to the calling method.
282   *
283   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
284   */
285  public static void checkArgument(
286      boolean b, @Nullable String errorMessageTemplate, int p1, long p2) {
287    if (!b) {
288      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
289    }
290  }
291
292  /**
293   * Ensures the truth of an expression involving one or more parameters to the calling method.
294   *
295   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
296   */
297  public static void checkArgument(
298      boolean b, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2) {
299    if (!b) {
300      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
301    }
302  }
303
304  /**
305   * Ensures the truth of an expression involving one or more parameters to the calling method.
306   *
307   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
308   */
309  public static void checkArgument(
310      boolean b, @Nullable String errorMessageTemplate, long p1, char p2) {
311    if (!b) {
312      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
313    }
314  }
315
316  /**
317   * Ensures the truth of an expression involving one or more parameters to the calling method.
318   *
319   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
320   */
321  public static void checkArgument(
322      boolean b, @Nullable String errorMessageTemplate, long p1, int p2) {
323    if (!b) {
324      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
325    }
326  }
327
328  /**
329   * Ensures the truth of an expression involving one or more parameters to the calling method.
330   *
331   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
332   */
333  public static void checkArgument(
334      boolean b, @Nullable String errorMessageTemplate, long p1, long 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  public static void checkArgument(
346      boolean b, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
347    if (!b) {
348      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
349    }
350  }
351
352  /**
353   * Ensures the truth of an expression involving one or more parameters to the calling method.
354   *
355   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
356   */
357  public static void checkArgument(
358      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, char p2) {
359    if (!b) {
360      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
361    }
362  }
363
364  /**
365   * Ensures the truth of an expression involving one or more parameters to the calling method.
366   *
367   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
368   */
369  public static void checkArgument(
370      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
371    if (!b) {
372      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
373    }
374  }
375
376  /**
377   * Ensures the truth of an expression involving one or more parameters to the calling method.
378   *
379   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
380   */
381  public static void checkArgument(
382      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
383    if (!b) {
384      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
385    }
386  }
387
388  /**
389   * Ensures the truth of an expression involving one or more parameters to the calling method.
390   *
391   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
392   */
393  public static void checkArgument(
394      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
395    if (!b) {
396      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2));
397    }
398  }
399
400  /**
401   * Ensures the truth of an expression involving one or more parameters to the calling method.
402   *
403   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
404   */
405  public static void checkArgument(
406      boolean b,
407      @Nullable String errorMessageTemplate,
408      @Nullable Object p1,
409      @Nullable Object p2,
410      @Nullable Object p3) {
411    if (!b) {
412      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3));
413    }
414  }
415
416  /**
417   * Ensures the truth of an expression involving one or more parameters to the calling method.
418   *
419   * <p>See {@link #checkArgument(boolean, String, Object...)} for details.
420   */
421  public static void checkArgument(
422      boolean b,
423      @Nullable String errorMessageTemplate,
424      @Nullable Object p1,
425      @Nullable Object p2,
426      @Nullable Object p3,
427      @Nullable Object p4) {
428    if (!b) {
429      throw new IllegalArgumentException(format(errorMessageTemplate, p1, p2, p3, p4));
430    }
431  }
432
433  /**
434   * Ensures the truth of an expression involving the state of the calling instance, but not
435   * involving any parameters to the calling method.
436   *
437   * @param expression a boolean expression
438   * @throws IllegalStateException if {@code expression} is false
439   * @see Verify#verify Verify.verify()
440   */
441  public static void checkState(boolean expression) {
442    if (!expression) {
443      throw new IllegalStateException();
444    }
445  }
446
447  /**
448   * Ensures the truth of an expression involving the state of the calling instance, but not
449   * involving any parameters to the calling method.
450   *
451   * @param expression a boolean expression
452   * @param errorMessage the exception message to use if the check fails; will be converted to a
453   *     string using {@link String#valueOf(Object)}
454   * @throws IllegalStateException if {@code expression} is false
455   * @see Verify#verify Verify.verify()
456   */
457  public static void checkState(boolean expression, @Nullable Object errorMessage) {
458    if (!expression) {
459      throw new IllegalStateException(String.valueOf(errorMessage));
460    }
461  }
462
463  /**
464   * Ensures the truth of an expression involving the state of the calling instance, but not
465   * involving any parameters to the calling method.
466   *
467   * @param expression a boolean expression
468   * @param errorMessageTemplate a template for the exception message should the check fail. The
469   *     message is formed by replacing each {@code %s} placeholder in the template with an
470   *     argument. These are matched by position - the first {@code %s} gets {@code
471   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
472   *     square braces. Unmatched placeholders will be left as-is.
473   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
474   *     are converted to strings using {@link String#valueOf(Object)}.
475   * @throws IllegalStateException if {@code expression} is false
476   * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
477   *     {@code errorMessageArgs} is null (don't let this happen)
478   * @see Verify#verify Verify.verify()
479   */
480  public static void checkState(
481      boolean expression,
482      @Nullable String errorMessageTemplate,
483      @Nullable Object... errorMessageArgs) {
484    if (!expression) {
485      throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
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   * <p>See {@link #checkState(boolean, String, Object...)} for details.
494   */
495  public static void checkState(boolean b, @Nullable String errorMessageTemplate, char p1) {
496    if (!b) {
497      throw new IllegalStateException(format(errorMessageTemplate, p1));
498    }
499  }
500
501  /**
502   * Ensures the truth of an expression involving the state of the calling instance, but not
503   * involving any parameters to the calling method.
504   *
505   * <p>See {@link #checkState(boolean, String, Object...)} for details.
506   */
507  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1) {
508    if (!b) {
509      throw new IllegalStateException(format(errorMessageTemplate, p1));
510    }
511  }
512
513  /**
514   * Ensures the truth of an expression involving the state of the calling instance, but not
515   * involving any parameters to the calling method.
516   *
517   * <p>See {@link #checkState(boolean, String, Object...)} for details.
518   */
519  public static void checkState(boolean b, @Nullable String errorMessageTemplate, long p1) {
520    if (!b) {
521      throw new IllegalStateException(format(errorMessageTemplate, p1));
522    }
523  }
524
525  /**
526   * Ensures the truth of an expression involving the state of the calling instance, but not
527   * involving any parameters to the calling method.
528   *
529   * <p>See {@link #checkState(boolean, String, Object...)} for details.
530   */
531  public static void checkState(
532      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1) {
533    if (!b) {
534      throw new IllegalStateException(format(errorMessageTemplate, p1));
535    }
536  }
537
538  /**
539   * Ensures the truth of an expression involving the state of the calling instance, but not
540   * involving any parameters to the calling method.
541   *
542   * <p>See {@link #checkState(boolean, String, Object...)} for details.
543   */
544  public static void checkState(
545      boolean b, @Nullable String errorMessageTemplate, char p1, char p2) {
546    if (!b) {
547      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
548    }
549  }
550
551  /**
552   * Ensures the truth of an expression involving the state of the calling instance, but not
553   * involving any parameters to the calling method.
554   *
555   * <p>See {@link #checkState(boolean, String, Object...)} for details.
556   */
557  public static void checkState(boolean b, @Nullable String errorMessageTemplate, char p1, int p2) {
558    if (!b) {
559      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
560    }
561  }
562
563  /**
564   * Ensures the truth of an expression involving the state of the calling instance, but not
565   * involving any parameters to the calling method.
566   *
567   * <p>See {@link #checkState(boolean, String, Object...)} for details.
568   */
569  public static void checkState(
570      boolean b, @Nullable String errorMessageTemplate, char p1, long p2) {
571    if (!b) {
572      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
573    }
574  }
575
576  /**
577   * Ensures the truth of an expression involving the state of the calling instance, but not
578   * involving any parameters to the calling method.
579   *
580   * <p>See {@link #checkState(boolean, String, Object...)} for details.
581   */
582  public static void checkState(
583      boolean b, @Nullable String errorMessageTemplate, char p1, @Nullable Object p2) {
584    if (!b) {
585      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
586    }
587  }
588
589  /**
590   * Ensures the truth of an expression involving the state of the calling instance, but not
591   * involving any parameters to the calling method.
592   *
593   * <p>See {@link #checkState(boolean, String, Object...)} for details.
594   */
595  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int 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  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1, int p2) {
608    if (!b) {
609      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
610    }
611  }
612
613  /**
614   * Ensures the truth of an expression involving the state of the calling instance, but not
615   * involving any parameters to the calling method.
616   *
617   * <p>See {@link #checkState(boolean, String, Object...)} for details.
618   */
619  public static void checkState(boolean b, @Nullable String errorMessageTemplate, int p1, long p2) {
620    if (!b) {
621      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
622    }
623  }
624
625  /**
626   * Ensures the truth of an expression involving the state of the calling instance, but not
627   * involving any parameters to the calling method.
628   *
629   * <p>See {@link #checkState(boolean, String, Object...)} for details.
630   */
631  public static void checkState(
632      boolean b, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2) {
633    if (!b) {
634      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
635    }
636  }
637
638  /**
639   * Ensures the truth of an expression involving the state of the calling instance, but not
640   * involving any parameters to the calling method.
641   *
642   * <p>See {@link #checkState(boolean, String, Object...)} for details.
643   */
644  public static void checkState(
645      boolean b, @Nullable String errorMessageTemplate, long p1, char p2) {
646    if (!b) {
647      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
648    }
649  }
650
651  /**
652   * Ensures the truth of an expression involving the state of the calling instance, but not
653   * involving any parameters to the calling method.
654   *
655   * <p>See {@link #checkState(boolean, String, Object...)} for details.
656   */
657  public static void checkState(boolean b, @Nullable String errorMessageTemplate, long p1, int p2) {
658    if (!b) {
659      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
660    }
661  }
662
663  /**
664   * Ensures the truth of an expression involving the state of the calling instance, but not
665   * involving any parameters to the calling method.
666   *
667   * <p>See {@link #checkState(boolean, String, Object...)} for details.
668   */
669  public static void checkState(
670      boolean b, @Nullable String errorMessageTemplate, long p1, long p2) {
671    if (!b) {
672      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
673    }
674  }
675
676  /**
677   * Ensures the truth of an expression involving the state of the calling instance, but not
678   * involving any parameters to the calling method.
679   *
680   * <p>See {@link #checkState(boolean, String, Object...)} for details.
681   */
682  public static void checkState(
683      boolean b, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
684    if (!b) {
685      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
686    }
687  }
688
689  /**
690   * Ensures the truth of an expression involving the state of the calling instance, but not
691   * involving any parameters to the calling method.
692   *
693   * <p>See {@link #checkState(boolean, String, Object...)} for details.
694   */
695  public static void checkState(
696      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, char 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  public static void checkState(
709      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
710    if (!b) {
711      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
712    }
713  }
714
715  /**
716   * Ensures the truth of an expression involving the state of the calling instance, but not
717   * involving any parameters to the calling method.
718   *
719   * <p>See {@link #checkState(boolean, String, Object...)} for details.
720   */
721  public static void checkState(
722      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
723    if (!b) {
724      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
725    }
726  }
727
728  /**
729   * Ensures the truth of an expression involving the state of the calling instance, but not
730   * involving any parameters to the calling method.
731   *
732   * <p>See {@link #checkState(boolean, String, Object...)} for details.
733   */
734  public static void checkState(
735      boolean b, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
736    if (!b) {
737      throw new IllegalStateException(format(errorMessageTemplate, p1, p2));
738    }
739  }
740
741  /**
742   * Ensures the truth of an expression involving the state of the calling instance, but not
743   * involving any parameters to the calling method.
744   *
745   * <p>See {@link #checkState(boolean, String, Object...)} for details.
746   */
747  public static void checkState(
748      boolean b,
749      @Nullable String errorMessageTemplate,
750      @Nullable Object p1,
751      @Nullable Object p2,
752      @Nullable Object p3) {
753    if (!b) {
754      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
755    }
756  }
757
758  /**
759   * Ensures the truth of an expression involving the state of the calling instance, but not
760   * involving any parameters to the calling method.
761   *
762   * <p>See {@link #checkState(boolean, String, Object...)} for details.
763   */
764  public static void checkState(
765      boolean b,
766      @Nullable String errorMessageTemplate,
767      @Nullable Object p1,
768      @Nullable Object p2,
769      @Nullable Object p3,
770      @Nullable Object p4) {
771    if (!b) {
772      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3, p4));
773    }
774  }
775
776  /**
777   * Ensures that an object reference passed as a parameter to the calling method is not null.
778   *
779   * @param reference an object reference
780   * @return the non-null reference that was validated
781   * @throws NullPointerException if {@code reference} is null
782   * @see Verify#verifyNotNull Verify.verifyNotNull()
783   */
784  @CanIgnoreReturnValue
785  public static <T> T checkNotNull(T reference) {
786    if (reference == null) {
787      throw new NullPointerException();
788    }
789    return reference;
790  }
791
792  /**
793   * Ensures that an object reference passed as a parameter to the calling method is not null.
794   *
795   * @param reference an object reference
796   * @param errorMessage the exception message to use if the check fails; will be converted to a
797   *     string using {@link String#valueOf(Object)}
798   * @return the non-null reference that was validated
799   * @throws NullPointerException if {@code reference} is null
800   * @see Verify#verifyNotNull Verify.verifyNotNull()
801   */
802  @CanIgnoreReturnValue
803  public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
804    if (reference == null) {
805      throw new NullPointerException(String.valueOf(errorMessage));
806    }
807    return reference;
808  }
809
810  /**
811   * Ensures that an object reference passed as a parameter to the calling method is not null.
812   *
813   * @param reference an object reference
814   * @param errorMessageTemplate a template for the exception message should the check fail. The
815   *     message is formed by replacing each {@code %s} placeholder in the template with an
816   *     argument. These are matched by position - the first {@code %s} gets {@code
817   *     errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in
818   *     square braces. Unmatched placeholders will be left as-is.
819   * @param errorMessageArgs the arguments to be substituted into the message template. Arguments
820   *     are converted to strings using {@link String#valueOf(Object)}.
821   * @return the non-null reference that was validated
822   * @throws NullPointerException if {@code reference} is null
823   * @see Verify#verifyNotNull Verify.verifyNotNull()
824   */
825  @CanIgnoreReturnValue
826  public static <T> T checkNotNull(
827      T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
828    if (reference == null) {
829      // If either of these parameters is null, the right thing happens anyway
830      throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
831    }
832    return reference;
833  }
834
835  /**
836   * Ensures that an object reference passed as a parameter to the calling method is not null.
837   *
838   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
839   */
840  @CanIgnoreReturnValue
841  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1) {
842    if (obj == null) {
843      throw new NullPointerException(format(errorMessageTemplate, p1));
844    }
845    return obj;
846  }
847
848  /**
849   * Ensures that an object reference passed as a parameter to the calling method is not null.
850   *
851   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
852   */
853  @CanIgnoreReturnValue
854  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1) {
855    if (obj == null) {
856      throw new NullPointerException(format(errorMessageTemplate, p1));
857    }
858    return obj;
859  }
860
861  /**
862   * Ensures that an object reference passed as a parameter to the calling method is not null.
863   *
864   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
865   */
866  @CanIgnoreReturnValue
867  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1) {
868    if (obj == null) {
869      throw new NullPointerException(format(errorMessageTemplate, p1));
870    }
871    return obj;
872  }
873
874  /**
875   * Ensures that an object reference passed as a parameter to the calling method is not null.
876   *
877   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
878   */
879  @CanIgnoreReturnValue
880  public static <T> T checkNotNull(
881      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1) {
882    if (obj == null) {
883      throw new NullPointerException(format(errorMessageTemplate, p1));
884    }
885    return obj;
886  }
887
888  /**
889   * Ensures that an object reference passed as a parameter to the calling method is not null.
890   *
891   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
892   */
893  @CanIgnoreReturnValue
894  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, char p2) {
895    if (obj == null) {
896      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
897    }
898    return obj;
899  }
900
901  /**
902   * Ensures that an object reference passed as a parameter to the calling method is not null.
903   *
904   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
905   */
906  @CanIgnoreReturnValue
907  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, int p2) {
908    if (obj == null) {
909      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
910    }
911    return obj;
912  }
913
914  /**
915   * Ensures that an object reference passed as a parameter to the calling method is not null.
916   *
917   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
918   */
919  @CanIgnoreReturnValue
920  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, char p1, long p2) {
921    if (obj == null) {
922      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
923    }
924    return obj;
925  }
926
927  /**
928   * Ensures that an object reference passed as a parameter to the calling method is not null.
929   *
930   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
931   */
932  @CanIgnoreReturnValue
933  public static <T> T checkNotNull(
934      T obj, @Nullable String errorMessageTemplate, char p1, @Nullable Object p2) {
935    if (obj == null) {
936      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
937    }
938    return obj;
939  }
940
941  /**
942   * Ensures that an object reference passed as a parameter to the calling method is not null.
943   *
944   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
945   */
946  @CanIgnoreReturnValue
947  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, char p2) {
948    if (obj == null) {
949      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
950    }
951    return obj;
952  }
953
954  /**
955   * Ensures that an object reference passed as a parameter to the calling method is not null.
956   *
957   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
958   */
959  @CanIgnoreReturnValue
960  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, int p2) {
961    if (obj == null) {
962      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
963    }
964    return obj;
965  }
966
967  /**
968   * Ensures that an object reference passed as a parameter to the calling method is not null.
969   *
970   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
971   */
972  @CanIgnoreReturnValue
973  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, int p1, long p2) {
974    if (obj == null) {
975      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
976    }
977    return obj;
978  }
979
980  /**
981   * Ensures that an object reference passed as a parameter to the calling method is not null.
982   *
983   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
984   */
985  @CanIgnoreReturnValue
986  public static <T> T checkNotNull(
987      T obj, @Nullable String errorMessageTemplate, int p1, @Nullable Object 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  @CanIgnoreReturnValue
1000  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, char p2) {
1001    if (obj == null) {
1002      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1003    }
1004    return obj;
1005  }
1006
1007  /**
1008   * Ensures that an object reference passed as a parameter to the calling method is not null.
1009   *
1010   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1011   */
1012  @CanIgnoreReturnValue
1013  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, int p2) {
1014    if (obj == null) {
1015      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1016    }
1017    return obj;
1018  }
1019
1020  /**
1021   * Ensures that an object reference passed as a parameter to the calling method is not null.
1022   *
1023   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1024   */
1025  @CanIgnoreReturnValue
1026  public static <T> T checkNotNull(T obj, @Nullable String errorMessageTemplate, long p1, long p2) {
1027    if (obj == null) {
1028      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1029    }
1030    return obj;
1031  }
1032
1033  /**
1034   * Ensures that an object reference passed as a parameter to the calling method is not null.
1035   *
1036   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1037   */
1038  @CanIgnoreReturnValue
1039  public static <T> T checkNotNull(
1040      T obj, @Nullable String errorMessageTemplate, long p1, @Nullable Object p2) {
1041    if (obj == null) {
1042      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1043    }
1044    return obj;
1045  }
1046
1047  /**
1048   * Ensures that an object reference passed as a parameter to the calling method is not null.
1049   *
1050   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1051   */
1052  @CanIgnoreReturnValue
1053  public static <T> T checkNotNull(
1054      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, char p2) {
1055    if (obj == null) {
1056      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1057    }
1058    return obj;
1059  }
1060
1061  /**
1062   * Ensures that an object reference passed as a parameter to the calling method is not null.
1063   *
1064   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1065   */
1066  @CanIgnoreReturnValue
1067  public static <T> T checkNotNull(
1068      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, int p2) {
1069    if (obj == null) {
1070      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1071    }
1072    return obj;
1073  }
1074
1075  /**
1076   * Ensures that an object reference passed as a parameter to the calling method is not null.
1077   *
1078   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1079   */
1080  @CanIgnoreReturnValue
1081  public static <T> T checkNotNull(
1082      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, long p2) {
1083    if (obj == null) {
1084      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1085    }
1086    return obj;
1087  }
1088
1089  /**
1090   * Ensures that an object reference passed as a parameter to the calling method is not null.
1091   *
1092   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1093   */
1094  @CanIgnoreReturnValue
1095  public static <T> T checkNotNull(
1096      T obj, @Nullable String errorMessageTemplate, @Nullable Object p1, @Nullable Object p2) {
1097    if (obj == null) {
1098      throw new NullPointerException(format(errorMessageTemplate, p1, p2));
1099    }
1100    return obj;
1101  }
1102
1103  /**
1104   * Ensures that an object reference passed as a parameter to the calling method is not null.
1105   *
1106   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1107   */
1108  @CanIgnoreReturnValue
1109  public static <T> T checkNotNull(
1110      T obj,
1111      @Nullable String errorMessageTemplate,
1112      @Nullable Object p1,
1113      @Nullable Object p2,
1114      @Nullable Object p3) {
1115    if (obj == null) {
1116      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3));
1117    }
1118    return obj;
1119  }
1120
1121  /**
1122   * Ensures that an object reference passed as a parameter to the calling method is not null.
1123   *
1124   * <p>See {@link #checkNotNull(Object, String, Object...)} for details.
1125   */
1126  @CanIgnoreReturnValue
1127  public static <T> T checkNotNull(
1128      T obj,
1129      @Nullable String errorMessageTemplate,
1130      @Nullable Object p1,
1131      @Nullable Object p2,
1132      @Nullable Object p3,
1133      @Nullable Object p4) {
1134    if (obj == null) {
1135      throw new NullPointerException(format(errorMessageTemplate, p1, p2, p3, p4));
1136    }
1137    return obj;
1138  }
1139
1140  /*
1141   * All recent hotspots (as of 2009) *really* like to have the natural code
1142   *
1143   * if (guardExpression) {
1144   *    throw new BadException(messageExpression);
1145   * }
1146   *
1147   * refactored so that messageExpression is moved to a separate String-returning method.
1148   *
1149   * if (guardExpression) {
1150   *    throw new BadException(badMsg(...));
1151   * }
1152   *
1153   * The alternative natural refactorings into void or Exception-returning methods are much slower.
1154   * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is
1155   * a hotspot optimizer bug, which should be fixed, but that's a separate, big project).
1156   *
1157   * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a
1158   * RangeCheckMicroBenchmark in the JDK that was used to test this.
1159   *
1160   * But the methods in this class want to throw different exceptions, depending on the args, so it
1161   * appears that this pattern is not directly applicable. But we can use the ridiculous, devious
1162   * trick of throwing an exception in the middle of the construction of another exception. Hotspot
1163   * is fine with that.
1164   */
1165
1166  /**
1167   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1168   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1169   *
1170   * @param index a user-supplied index identifying an element of an array, list or string
1171   * @param size the size of that array, list or string
1172   * @return the value of {@code index}
1173   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1174   * @throws IllegalArgumentException if {@code size} is negative
1175   */
1176  @CanIgnoreReturnValue
1177  public static int checkElementIndex(int index, int size) {
1178    return checkElementIndex(index, size, "index");
1179  }
1180
1181  /**
1182   * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
1183   * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
1184   *
1185   * @param index a user-supplied index identifying an element of an array, list or string
1186   * @param size the size of that array, list or string
1187   * @param desc the text to use to describe this index in an error message
1188   * @return the value of {@code index}
1189   * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
1190   * @throws IllegalArgumentException if {@code size} is negative
1191   */
1192  @CanIgnoreReturnValue
1193  public static int checkElementIndex(int index, int size, @Nullable String desc) {
1194    // Carefully optimized for execution by hotspot (explanatory comment above)
1195    if (index < 0 || index >= size) {
1196      throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
1197    }
1198    return index;
1199  }
1200
1201  private static String badElementIndex(int index, int size, String desc) {
1202    if (index < 0) {
1203      return format("%s (%s) must not be negative", desc, index);
1204    } else if (size < 0) {
1205      throw new IllegalArgumentException("negative size: " + size);
1206    } else { // index >= size
1207      return format("%s (%s) must be less than size (%s)", desc, index, size);
1208    }
1209  }
1210
1211  /**
1212   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1213   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1214   *
1215   * @param index a user-supplied index identifying a position in an array, list or string
1216   * @param size the size of that array, list or string
1217   * @return the value of {@code index}
1218   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1219   * @throws IllegalArgumentException if {@code size} is negative
1220   */
1221  @CanIgnoreReturnValue
1222  public static int checkPositionIndex(int index, int size) {
1223    return checkPositionIndex(index, size, "index");
1224  }
1225
1226  /**
1227   * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of
1228   * size {@code size}. A position index may range from zero to {@code size}, inclusive.
1229   *
1230   * @param index a user-supplied index identifying a position in an array, list or string
1231   * @param size the size of that array, list or string
1232   * @param desc the text to use to describe this index in an error message
1233   * @return the value of {@code index}
1234   * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size}
1235   * @throws IllegalArgumentException if {@code size} is negative
1236   */
1237  @CanIgnoreReturnValue
1238  public static int checkPositionIndex(int index, int size, @Nullable String desc) {
1239    // Carefully optimized for execution by hotspot (explanatory comment above)
1240    if (index < 0 || index > size) {
1241      throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
1242    }
1243    return index;
1244  }
1245
1246  private static String badPositionIndex(int index, int size, String desc) {
1247    if (index < 0) {
1248      return format("%s (%s) must not be negative", desc, index);
1249    } else if (size < 0) {
1250      throw new IllegalArgumentException("negative size: " + size);
1251    } else { // index > size
1252      return format("%s (%s) must not be greater than size (%s)", desc, index, size);
1253    }
1254  }
1255
1256  /**
1257   * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list
1258   * or string of size {@code size}, and are in order. A position index may range from zero to
1259   * {@code size}, inclusive.
1260   *
1261   * @param start a user-supplied index identifying a starting position in an array, list or string
1262   * @param end a user-supplied index identifying a ending position in an array, list or string
1263   * @param size the size of that array, list or string
1264   * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size},
1265   *     or if {@code end} is less than {@code start}
1266   * @throws IllegalArgumentException if {@code size} is negative
1267   */
1268  public static void checkPositionIndexes(int start, int end, int size) {
1269    // Carefully optimized for execution by hotspot (explanatory comment above)
1270    if (start < 0 || end < start || end > size) {
1271      throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
1272    }
1273  }
1274
1275  private static String badPositionIndexes(int start, int end, int size) {
1276    if (start < 0 || start > size) {
1277      return badPositionIndex(start, size, "start index");
1278    }
1279    if (end < 0 || end > size) {
1280      return badPositionIndex(end, size, "end index");
1281    }
1282    // end < start
1283    return format("end index (%s) must not be less than start index (%s)", end, start);
1284  }
1285
1286  /**
1287   * Substitutes each {@code %s} in {@code template} with an argument. These are matched by
1288   * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
1289   * placeholders, the unmatched arguments will be appended to the end of the formatted message in
1290   * square braces.
1291   *
1292   * @param template a non-null string containing 0 or more {@code %s} placeholders.
1293   * @param args the arguments to be substituted into the message template. Arguments are converted
1294   *     to strings using {@link String#valueOf(Object)}. Arguments can be null.
1295   */
1296  // Note that this is somewhat-improperly used from Verify.java as well.
1297  static String format(String template, @Nullable Object... args) {
1298    template = String.valueOf(template); // null -> "null"
1299
1300    // start substituting the arguments into the '%s' placeholders
1301    StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
1302    int templateStart = 0;
1303    int i = 0;
1304    while (i < args.length) {
1305      int placeholderStart = template.indexOf("%s", templateStart);
1306      if (placeholderStart == -1) {
1307        break;
1308      }
1309      builder.append(template, templateStart, placeholderStart);
1310      builder.append(args[i++]);
1311      templateStart = placeholderStart + 2;
1312    }
1313    builder.append(template, templateStart, template.length());
1314
1315    // if we run out of placeholders, append the extra args in square braces
1316    if (i < args.length) {
1317      builder.append(" [");
1318      builder.append(args[i++]);
1319      while (i < args.length) {
1320        builder.append(", ");
1321        builder.append(args[i++]);
1322      }
1323      builder.append(']');
1324    }
1325
1326    return builder.toString();
1327  }
1328}