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